30

在 UIWebView 中,我可以JSContext通过:

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

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

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

提前致谢。

4

2 回答 2

14

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

相反,将脚本添加到您的 webview 配置中,并将您的视图控制器(或另一个对象)设置为脚本消息处理程序。

现在,像这样从 JavaScript 发送消息:

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

您的脚本消息处理程序将收到回调:

- (void)userContentController:(WKUserContentController *)userContentController 
                            didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"%@", message.body);
}
于 2014-09-15T19:55:27.703 回答
3

像这样配置您的 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);
于 2017-02-28T06:38:58.623 回答