【问题标题】:Capturing console.log within a UIWebView在 UIWebView 中捕获 console.log
【发布时间】:2013-03-29 06:56:19
【问题描述】:

我正在使用 MonoTouch 编写一个 iOS 应用程序,它与 UIWebView 进行一些 javascript 交互。出于调试目的,如果能够在 UIWebView 中运行的 javascript 中“捕获”console.log 以及应用程序输出的其余部分,那就太好了。这可能吗?使用常规 Objective-C 代码的示例也可以。

【问题讨论】:

    标签: javascript ios uiwebview xamarin.ios


    【解决方案1】:

    经过一番谷歌搜索,我得到了这个答案:Javascript console.log() in an iOS UIWebView

    将其转换为 MonoTouch 会产生此解决方案:

    using System;
    using System.Web;
    using System.Json;
    using MonoTouch.UIKit;
    
    namespace View
    {
        public class JsBridgeWebView : UIWebView
        {
    
            public object BridgeDelegate {get;set;}
    
            private const string BRIDGE_JS = @"
                function invokeNative(functionName, args) {
                    var iframe = document.createElement('IFRAME');
                    iframe.setAttribute('src', 'jsbridge://' + functionName + '#' + JSON.stringify(args));
                    document.documentElement.appendChild(iframe);
                    iframe.parentNode.removeChild(iframe);
                    iframe = null;  
                }
    
                var console = {
                    log: function(msg) {
                        invokeNative('Log', [msg]);
                    }
                };  
            ";
    
            public JsBridgeWebView ()
            {
                ShouldStartLoad += LoadHandler;
                LoadFinished += (sender, e) => {
                    EvaluateJavascript(BRIDGE_JS);
                };
            }
    
            public bool LoadHandler (UIWebView webView, MonoTouch.Foundation.NSUrlRequest request, UIWebViewNavigationType navigationType)
            {
                var url = request.Url;
                if(url.Scheme.Equals("jsbridge")) {
                    var func = url.Host;
                    if(func.Equals("Log")) {
                        // console.log
                        var args = JsonObject.Parse(HttpUtility.UrlDecode(url.Fragment));
                        var msg = (string)args[0];
                        Console.WriteLine(msg);
                        return false;
                    }
                    return true;
                }
            }   
        }
    }
    

    现在,UIWebView 中 javascript 中的所有 console.log 语句都将发送到 Console.WriteLine。这当然可以扩展到人们想要的任何类型的输出。

    【讨论】:

      【解决方案2】:

      您能否添加执行类似操作的 javascript 代码来覆盖该方法:

      console.log = function(var text) {
          consoleforios += text;
      }
      

      然后从 web 视图中调用:

      string console = webView.EvaluatingJavaScript("return consoleforios;");
      

      这可能不是我会永久保留的东西,但它应该可以工作。

      【讨论】:

      • 这是一个选项,但不是我想要的。
      猜你喜欢
      • 2012-03-25
      • 2012-01-31
      • 2011-09-24
      • 2012-07-09
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      相关资源
      最近更新 更多