Swift Wkwebview: Can't Find Variable Error When Calling Method

JavaScript exception when calling a function via `evaluateJavaScript` on WKWebView, which has a local .js file

You're not that far.

First, you can either modify your code by setting the baseURL:

webView.loadHTMLString(text, baseURL: path)

or use an URLRequest instead (better in my opinion).

if let path = Bundle.main.url(forResource: "sample", withExtension: "html"){  
let myURLRequest:URLRequest = URLRequest(url: path)
webView.load(myURLRequest)
}

The second thing is you have to wait for the content to be loaded.
So you first need to set a delegate for your webview (Make sure you add this line before before loading the html).

webView.navigationDelegate = self

Then, add an extension to your class for the delegate ( My class is named "ViewController" here, but change it to the name of your class ) to call evaluateJavascript when the page is loaded.

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)
}

}
}

Can't find variable webkit on iOS 14.2

Try calling it from window (using window.webkit)

javascript embedded in html not running in wkwebview

You should be calling your javascript in this WKNavigationDelegate method, which is called when the webview finishes loading.

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("initMap()", completionHandler: { (value, err) in
// Handle response here.
})
}

Also, I'm not sure why you're calling two different webview.load() requests - maybe don't do that?

Will JavaScripts embedded in an HTML file loaded by WKWebView be accessible?

I figured it out - will put the answer here hoping it helps someone else:

The problem was here:

webView.loadHTMLString(html!, baseURL: nil)

I had to ensure baseURL is not nil, the following fixes it:

webView.loadHTMLString(html!, baseURL: Bundle.main.bundleURL)



Related Topics



Leave a reply



Submit