我的JavaScript注入到webkitView听任何点击事件可惜脚本不工作的所有网页,如“https://www.zara.com”的文件体,否则它适用于其他网页像谷歌等...
这是我的代码:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
private var url = URL(string: "https://www.google.com")!
override func viewDidLoad() {
super.viewDidLoad()
initializeWebView()
loadData()
}
private func initializeWebView() {
let javascript = """
window.onload = function() {
document.addEventListener("click", function(evt) {
var tagClicked = document.elementFromPoint(evt.clientX, evt.clientY);
window.webkit.messageHandlers.jsMessenger.postMessage(tagClicked.outerHTML.toString());
});
}
"""
let userScript = WKUserScript.init(source: javascript,
injectionTime: .atDocumentStart, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(userScript)
webView.configuration.userContentController.add(self, name: "jsMessenger")
}
private func loadData() {
let request = URLRequest(url: url)
webView?.load(URLRequest.init(url: url))
}
}
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.body)
}
}
你应该初始化WKUserScript与forMainFrameOnly: false
参数。您可以在此处找到有关此参数的详细信息:WKUserScript forMainFrameOnly