如何从WKWebView获取JSContext?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (169)

在UIWebView中,我可以JSContext通过:

[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]

同样的方式在WKWebView中不起作用,当它到达这行代码时,应用程序崩溃。

有没有办法在WKWebView中获取JSContext?

提前致谢。

提问于
用户回答回答于

无法获得上下文,因为布局和javascript是在另一个进程上处理的。

相反,将脚本添加到WebView配置中,并将视图控制器(或其他对象)设置为脚本消息处理程序。

现在,从JavaScript发送消息,如下所示:

window.webkit.messageHandlers.interOp.postMessage(message)

你的脚本消息处理程序将收到一个回调:

- (void)userContentController:(WKUserContentController *)userContentController 
                            didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"%@", message.body);
}
用户回答回答于

像这样配置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);

扫码关注云+社区