【问题标题】: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;");
这可能不是我会永久保留的东西,但它应该可以工作。