回调 javascript postMessage ios swift

请告诉我,有一个 ios 应用程序,它包含 WebKitView,其中有一个包含以下代码的站点:


<div id="test" style="height: 40px; width: 100px; background-color: powderblue;">Hello</div>

<script type="text/javascript">

document.getElementById("test").addEventListener("click", function () {

   window.webkit.messageHandlers.test.postMessage("TEXT");

});

</script>

申请代码:


import UIKit

import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {

    

    var webView: WKWebView!

    

    override func loadView() {

        webView = WKWebView()

        webView.navigationDelegate = self

        view = webView

    }

    

    override func viewDidLoad() {

        super.viewDidLoad()

        let url = URL(string: "https://site")!

        webView.load(URLRequest(url: url))

        let config: WKWebViewConfiguration = WKWebViewConfiguration()

        config.userContentController.add(self, name: "test")

        webView = WKWebView(frame: self.view.frame, configuration: config)

        webView?.navigationDelegate = self

        self.webView?.load(URLRequest(url:url))

    }


    

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

        if message.name == "test", let messageBody = message.body as? String {

            print(messageBody)

        }

    }

}


在xcode中点击div时,日志中显示如下错误


[general] Connection to daemon was invalidated

可能是什么问题呢?对不起我的英语不好。


叮当猫咪
浏览 174回答 1
1回答

冉冉说

我已将主包中的共享 HTML 和 javascript 代码添加为“example.html”,并对您的代码进行了更改。它在我的最后工作正常。override func viewDidLoad() {&nbsp; &nbsp; &nbsp; &nbsp; super.viewDidLoad()&nbsp; &nbsp; &nbsp; &nbsp; //Url from the html&nbsp; &nbsp; &nbsp; &nbsp; let url = URL(fileURLWithPath: Bundle.main.path(forResource: "example", ofType: "HTML") ?? "")&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // Configuring WKEWebview&nbsp; &nbsp; &nbsp; &nbsp; let config: WKWebViewConfiguration = WKWebViewConfiguration()&nbsp; &nbsp; &nbsp; &nbsp; config.userContentController.add(self, name: "test")&nbsp; &nbsp; &nbsp; &nbsp; webView = WKWebView(frame: self.view.frame, configuration: config)&nbsp; &nbsp; &nbsp; &nbsp; webView?.navigationDelegate = self&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //Constraints related changes&nbsp; &nbsp; &nbsp; &nbsp; webView.translatesAutoresizingMaskIntoConstraints = true&nbsp; &nbsp; &nbsp; &nbsp; webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]&nbsp; &nbsp; &nbsp; &nbsp; self.view.addSubview(self.webView)&nbsp; &nbsp; &nbsp; &nbsp; // Load file&nbsp; &nbsp; &nbsp; &nbsp; self.webView?.loadFileURL(url, allowingReadAccessTo: Bundle.main.bundleURL)&nbsp; &nbsp; }您可以使用加载您的网页self.webView.load(URLRequest(url: "https://www.site"))试试看,如果您遇到任何问题,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript