I am using WKWebView to load HTML in the popup of my Safari App Extension. I am trying to send a message to this page using webView.evaluateJavaScript("myFunction()")
but it fails with error message EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)
.
I thought the page isn't loaded in the webView at first and hence throws this error but that is not the case here. The page loads completely but I get this error for some reason. Here is my code.
@IBOutlet var webView: WKWebView!
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("myFunction()", completionHandler: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
webView.configuration.userContentController.add(self, name: "popup")
webView.configuration.userContentController.add(self, name: "print")
webView.navigationDelegate = self
view.addSubview(webView!)
self.view = webView
if let url = Bundle.main.url(forResource: "MyPopup", withExtension: "html") {
webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())
}
}
I tried checking error inside the completionHandler but it doesn't go there. Any Ideas?
I believe you need to use main thread to execute JS in the webView. Try wrapping the call to webView.evaluateJavaScript()
in DispatchQueue.main.async { }
.