问题描述
在UIWebView中,我可以通过以下方式获取JSContext
:
In UIWebView, I can get JSContext
through:
[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]
同样的方法在 WKWebView 中不起作用,当它到达这行代码时应用程序崩溃.
The same way doesn't work in WKWebView and app crashes when it arrives this line of code.
有没有办法在WKWebView中获取JSContext?
Is there a way to get JSContext in WKWebView?
提前致谢.
推荐答案
您无法获取上下文,因为布局和 javascript 在另一个进程中处理.
You cannot obtain the context, because layout and javascript is handled on another process.
相反,将脚本添加到您的 webview 配置中,并将您的视图控制器(或其他对象)设置为脚本消息处理程序.
Instead, add scripts to your webview configuration, and set your view controller (or another object) as the script message handler.
现在,像这样从 JavaScript 发送消息:
Now, send messages from JavaScript like so:
window.webkit.messageHandlers.interOp.postMessage(message)
您的脚本消息处理程序将收到回调:
Your script message handler will receive a callback:
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"%@", message.body);
}
这篇关于如何从 WKWebView 获取 JSContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!