首页 > 解决方案 > 如何在 Swift 的 web 视图中运行 javascript

问题描述

我需要我的 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。

感谢您的任何建议。

标签: iosswiftwkwebviewevaluatejavascript

解决方案


您需要将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')")
}

在此处输入图像描述


此外

有一个示例项目可以模拟本地和 Web 之间的双向通信。


推荐阅读