在UIWebView中,我可以让JSContext
通过:
[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]
同样的方式在WKWebView中不起作用,当应用程序到达这行代码时就会崩溃。
有没有办法在WKWebView中使用JSContext?
提前谢谢。
发布于 2014-09-16 03:55:28
无法获取上下文,因为布局和javascript是在另一个进程上处理的。
相反,将脚本添加到您的webview配置中,并将视图控制器(或其他对象)设置为脚本消息处理程序。
现在,从JavaScript发送消息,如下所示:
window.webkit.messageHandlers.interOp.postMessage(message)
您的脚本消息处理程序将收到回调:
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"%@", message.body);
}
发布于 2017-02-28 14:38:59
像这样配置您的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);
https://stackoverflow.com/questions/25792131
复制相似问题