我正在用MonoTouch编写一个iOS应用程序,它与UIWebView进行一些javascript交互.出于调试目的,能够“捕获”UIWebView中运行的javascript中的console.log以及应用程序输出的其余部分会很好.这可能吗?使用常规Objective-C代码的示例也可以.
最佳答案
经过一些谷歌搜索,我得到了这个答案: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.这当然可以扩展到人们想要的任何类型的输出.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。