sample.html:
<html><head><script src="test.js">
.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 “A JavaScript exception occurred” UserInfo={WKJavaScriptExceptionLineNumber=1,WKJavaScriptExceptionMessage=ReferenceError: Can’t find variable: myFunction,WKJavaScriptExceptionSourceURL=about:blank,NSLocalizedDescription=A JavaScript exception occurred,WKJavaScriptExceptionColumnNumber=11}
我接近这个完全错了吗?
最佳答案
你不是那么远.
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) } } }原文链接:https://www.f2er.com/html/426935.html