在WKWebView中处理JavaScript事件 [英] Handling JavaScript events in WKWebView

查看:378
本文介绍了在WKWebView中处理JavaScript事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获 WKWebView 中的每个 onClick 事件。
该网站仅使用JavaScript,因此我无法处理任何内容:

  func webView(_ webView:WKWebView, decisionPolicyFor navigationAction:WKNavigationAction,decisionHandler:@escaping(WKNavigationActionPolicy) - > Void)

我该怎么办你可以使用WKUserScript将它添加到WKWebView配置的userContentController中。

  let config = WKWebViewConfiguration()
let source =document.addEventListener('click',function(){window.webkit.messageHandlers.iosListener .postMessage('click clack!');})
let script = WKUserScript(source:source,injectionTime:.atDocumentEnd,forMainFrameOnly:false)
config.userContentController.addUserScript(script)
config.userContentController.add(self,name:iosListener)
webView = WKWebView(frame:UIScreen.main.bounds,configuratio n:config)

这将使脚本在文档加载完成后将其注入页面。现在,您需要实现WKScriptMessageHandler协议来接收消息:

  func userContentController(_ userContentController:WKUserContentController,didReceive message:WKScriptMessage ){
print(message:\(message.body))
//以及你想采取的其他任何行动
}


I'm trying to catch every onClick event in WKWebView. The website is working only with JavaScript so I cannot handle anything in:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

How can I do this?

解决方案

you can use a WKUserScript and add it to the userContentController of the WKWebView's configuration.

    let config = WKWebViewConfiguration()
    let source = "document.addEventListener('click', function(){ window.webkit.messageHandlers.iosListener.postMessage('click clack!'); })"
    let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
    config.userContentController.addUserScript(script)
    config.userContentController.add(self, name: "iosListener")
    webView = WKWebView(frame: UIScreen.main.bounds, configuration: config)

this will make the script and inject it into the page when the document is finished loading. Now, you need to implement the WKScriptMessageHandler protocol to receive the message:

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("message: \(message.body)")
        // and whatever other actions you want to take
    }

这篇关于在WKWebView中处理JavaScript事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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