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
How to Find The Nth Root of a Value
Getting Common Data from Two Different Types of Array
How to Write to a Variable from Within The Firebase Getdocument Function (Swift)
Converting Scanlocation from Utf16 Units to Character Index in Nsscanner (Swift)
Vapor 3 - How to Check for Similar Email Before Saving Object
How to a Convert a Dictionary Slice to a Dictionary in Swift
How to Disable The Automatic Activation of an Arcoachingoverlayview
Dynamic Dispatching Protocol Extension Doesn't Work Multiple Targets
Cannot Decode Object of Class (Ampathpopupbutton)'
Navigationlink Doesn't Work with New .Searchable Modifier on Swiftui 3.0
Binary to Hexadecimal in Swift
How to Specify Japanese Encoding for a UIlabel
Swift Lose Precision in Decimal Formatting
Lsapplicationqueriesschemes and Derived Data
How to Print Http Request to Console
Struct Memberwise Initialization - Omitting Values for Properties That Have Defaults