gpt4 book ai didi

javascript - 回调Javascript PostMessage iOS Swift

转载 作者:行者123 更新时间:2023-12-01 18:03:29 46 4
gpt4 key购买 nike

请告诉我,有一个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
可能是什么问题呢?
对不起我的英语不好。

最佳答案

我已在主捆绑包中将共享的HTML和javascript代码添加为“example.html”,并对您的代码进行了更改。在我的末端运行良好。

override func viewDidLoad() {
super.viewDidLoad()
//Url from the html
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "example", ofType: "HTML") ?? "")

// Configuring WKEWebview
let config: WKWebViewConfiguration = WKWebViewConfiguration()
config.userContentController.add(self, name: "test")
webView = WKWebView(frame: self.view.frame, configuration: config)
webView?.navigationDelegate = self

//Constraints related changes
webView.translatesAutoresizingMaskIntoConstraints = true
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

self.view.addSubview(self.webView)
// Load file
self.webView?.loadFileURL(url, allowingReadAccessTo: Bundle.main.bundleURL)
}
您可以使用以下方式加载网页
self.webView.load(URLRequest(url: "https://www.site"))
试试看,让我知道您是否遇到任何问题。

关于javascript - 回调Javascript PostMessage iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62741535/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com