0

我被卡住了,函数“userContentController”永远不会调用。

用户内容控制器功能

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("Function Called")
        let showData = message.body as? String
        print(showData ?? "No Value received")
    }

viewDidLoad

        super.viewDidLoad()

        let configuration = WKWebViewConfiguration()
        configuration.userContentController.add(self, name: "send")
        let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
        let wweb = WKWebView(frame: rect, configuration: configuration)


        if let filePath = Bundle.main.url(forResource: "Script", withExtension: "html") {
            let request = NSURLRequest(url: filePath)
            wweb.load(request as URLRequest)
        }
    }

剧本

<html>
    <script>
        window.webkit.messageHandlers.send.postMessage("Hell from JavaScript");
    </script>
    <!--<h1><script src="http://scripts.myradiostream.com/s33/14866/status.js?online=BU RADiO OnAir&offline=BU RADiO OffAir&nosource=BU RADiO Coming OnAir Soon"></script></h1>
     -->
</html>
4

1 回答 1

0

尝试在脚本中传递字典而不是字符串。

示例:window.webkit.messageHandlers.send.postMessage({"body": "来自 JavaScript 的地狱"})

于 2020-01-22T07:45:28.410 回答