我们有一个示例HTML页面,它只链接.js文件:
sample.html:
.js文件实际上只是:
test.js
function myFunction() { return "hello"; }
所以我想要的是评估Javascript函数(现在).在Swift文件中:
let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration()) let path = Bundle.main.url(forResource: "sample", withExtension: "html")! let text = try! String(contentsOf: path, encoding: String.Encoding.utf8) webView.loadHTMLString(text, baseURL: nil) webView.evaluateJavaScript("myFunction()") { (any, error) in dump(error) }
我们得到错误的两个:
Error Domain = WKErrorDomain Code = 4"发生JavaScript异常"UserInfo = {WKJavaScriptExceptionLineNumber = 1,WKJavaScriptExceptionMessage = ReferenceError:找不到变量:myFunction,WKJavaScriptExceptionSourceURL = about:blank,NSLocalizedDescription =发生JavaScript异常,WKJavaScriptExceptionColumnNumber = 11}
我接近这个完全错了吗?
你不是那么远.
首先,您可以通过设置baseURL来修改代码:
webView.loadHTMLString(text, baseURL: path)
或者使用URLRequest(在我看来更好).
if let path = Bundle.main.url(forResource: "sample", withExtension: "html"){ let myURLRequest:URLRequest = URLRequest(url: path) webView.load(myURLRequest) }
第二件事是你必须等待加载内容.因此,您首先需要为webview设置一个委托(确保在加载html之前添加此行).
webView.navigationDelegate = self
然后,为您的类添加一个扩展名(我的类在此处命名为"ViewController",但将其更改为您的类的名称)以在加载页面时调用evaluateJavascript.
extension ViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { print("Finished navigating to url \(webView.url)") webView.evaluateJavaScript("myFunction()") { (any, error) in dump(error) print(any) } } }