在UIWebView中,我可以通过以下方式获取JSContext
:
[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]
当WKWebView和应用程序到达此行代码时,同样的方式无效。
有没有办法在WKWebView中获取JSContext?
提前感谢。
答案 0 :(得分:10)
您无法获取上下文,因为布局和javascript是在另一个进程上处理的。
相反,将脚本添加到webview配置中,并将视图控制器(或其他对象)设置为脚本消息处理程序。
现在,像这样发送来自JavaScript的消息:
window.webkit.messageHandlers.interOp.postMessage(message)
您的脚本消息处理程序将收到回调:
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"%@", message.body);
}
答案 1 :(得分:1)
像这样配置你的wkwebview并相应地添加处理程序并以类似模式从脚本发布消息
NSString *myScriptSource = @"alert('Hello, World!')";
WKUserScript *s = [[WKUserScript alloc] initWithSource:myScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
WKUserContentController *c = [[WKUserContentController alloc] init];
[c addUserScript:s];
// Add a script message handler for receiving "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.buttonClicked.postMessage script message
[c addScriptMessageHandler:self name:@"buttonClicked"];
WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
conf.userContentController = c;
WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:conf];
[self.view addSubview:webview];
webview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Do any additional setup after loading the view, typically from a nib.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
[webview loadRequest:request];
实现脚本消息处理程序" WKScriptMessageHandler"方法名称
#pragma mark -WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"buttonClicked"]) {
self.buttonClicked ++;
}
// JS objects are automatically mapped to ObjC objects
id messageBody = message.body;
if ([messageBody isKindOfClass:[NSDictionary class]]) {
NSString* idOfTappedButton = messageBody[@"ButtonId"];
[self updateColorOfButtonWithId:idOfTappedButton];
}
}
并发布消息格式js,如此
var button = document.getElementById("clickMeButton");
button.addEventListener("click", function() {
var messgeToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messgeToPost);
},false);
答案 2 :(得分:-1)
XWebView是解决您问题的好方法。它可以在native和JS之间建立桥梁,并提供绑定样式的API。