如何从WKWebView获取JSContext [英] How to get JSContext from WKWebView

查看:1597
本文介绍了如何从WKWebView获取JSContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆