如何在来自 Swift 的网络视图中 运行 javascript

How to run javascript in a webview from Swift

我需要我的 swift class 与它引用的 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
    }

但是,网络视图未触发警报。代码有什么问题,或者您还需要做些什么才能在 Web 视图上将 Swift 变为 运行 一些 javascript。

感谢您的任何建议。

您需要将 info in javascript alert 转换为原生 UIAlert.

添加 WKUIDelegate 中描述的警报处理程序委托。

func webView(_ webView: WKWebView,
             runJavaScriptAlertPanelWithMessage message: String,
             initiatedByFrame frame: WKFrameInfo,
             completionHandler: @escaping () -> Void) {

    let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
    let title = NSLocalizedString("OK", comment: "OK Button")
    let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
        alert.dismiss(animated: true, completion: nil)
    }
    alert.addAction(ok)
    present(alert, animated: true)
    completionHandler()
}

然后像下面这样调用(你的代码中有一个类型);

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("alert('hello from the webview')")
}


另外

有一个示例 project 以两种方式模拟本机和 Web 之间的双向通信。