ios - 如何在 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。
感谢您的任何建议。
解决方案
您需要将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 之间的双向通信。
推荐阅读
- python - Flake8 linter 通过 Bitbucket 管道仅对推送文件进行检查
- flink-streaming - 在 Flink SQL 中使用 ROW_NUMBER
- python - 检查图像文件是否与给定链接中的图像匹配
- javascript - 当验证失败时,我在每次新提交时都会收到递增数量的警报
- android - Android上的USB调试
- excel - Excel 工作表宏是否有原因在 Excel 2013 中损坏但在 Office 355 中工作正常?
- jsf - 在 JSF 中完成响应生成后,有什么方法可以调用方法吗?
- c - 我想用 C 制作程序打印每个全数
- swift - SwiftUI 和 Core Data:通过比较多个 fetches 来确定一个值
- c - 从结构的链接列表中打印字符串时读取大小为 1 的无效