在WebkitView注入的JavaScript听不工作的所有网页点击任何事件文档体

问题描述 投票:0回答:1

我的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)
    }
}
javascript ios swift webkit
1个回答
0
投票

你应该初始化WKUserScript与forMainFrameOnly: false参数。您可以在此处找到有关此参数的详细信息:WKUserScript forMainFrameOnly

© www.soinside.com 2019 - 2024. All rights reserved.