我需要我的 swift 类与它引用的 wkwebview 中的 html 和 javascript 进行交互,特别是向它提供一个变量。
我以为我会从尝试让 webview 触发警报开始:
这是代码:
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self as? WKNavigationDelegate
if let url = Bundle.main.url(forResource: "tradingview", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
}
// Try one way in viewdidload. Compiles but doesn't do anything
webView.evaluateJavaScript("alert('hello from the webview');");
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//try another way. Also doesn't do anything
webView.evaluateJavaScript("alert('hello from webview')"), completionHandler: nil)
}
override func loadView() {
self.view = webView
}
但是,webview 没有触发警报。代码有什么问题,或者您需要做些什么才能让 Swift 在 webview 上运行一些 javascript。
感谢您的任何建议。