We have a sample HTML page, which just links the .js file:
sample.html:
<html>
<head>
<script src="test.js"></script>
</head>
<body></body>
</html>
The .js file is literally just:
test.js
function myFunction() {
return "hello";
}
So All I want is to evaluate that Javascript function (for now). In the Swift file:
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)
}
Two which we get the 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}
Am I approaching this totally wrong?