0
我嘗試從我的Web視圖中獲取與WKWebView
的JavaScript消息。但沒有出現IOS控制檯中......WKWebView中的javascript橋樑不起作用
我實現這個代碼:
- (void) webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error {
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20)];
self.webView.backgroundColor = [UIColor whiteColor];
self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
self.webView.scrollView.delegate = self;
[self.view addSubview:self.webView];
// Setup WKUserContentController instance for injecting user script
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]
init];
WKUserContentController* userController = [[WKUserContentController alloc]init];
[userController addScriptMessageHandler: self name:@"notification"];
configuration.userContentController = userController;
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/test.php"]]];
}
- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message {
NSLog(@"%@", message.body);
}
和HTML/JS:
<div id="test" onclick="test();">test</div>
<script type="text/javascript" src="jquery.js"></script>
<script>
function test(){
alert('click');
$('#test').text('hello');
window.webkit.messageHandlers.notification.postMessage("click");
}
</script>
我不會從我的網頁得到任何日誌,當我點擊在div(警報不起作用,但測試 - >你好作品)
感謝支持
它這一點。謝謝。我加載之前添加了配置,它的工作原理 – user3279327
@ user3279327很樂意提供幫助。請接受答案。 –