简体   繁体   中英

How do I throw a javascript error for iOS evaluateJavaScript to catch it?

In evaluateJavaScript I call a javascript function that fetches an array of objects. If it fails, it calls a handleError function that throws an error.

I know that the handleError function is being called (I have a console.log statement) but when I throw an error, evaluateJavaScript is not capturing it.

Here's what I'm doing:

In my .swift file:

evaluateJavaScript("window.sampleFunctionThatHandlesFetch()", completionHandler: {(_ result: Any?, _ error: Error?) -> Void in
            print("result: \(result)")
            print("error: \(error)")
})

error is always nil.

In the .js file:

var handleError = function handleError(errorText) {
         throw new Error(errorText);
};

How can I throw the error for evaluateJavaScript to capture it inside error ?

The simplest solution I can suggest is just posting a message to your webView. That is, of course, if you're using WKWebView to display web content.

To do so you need to adopt WKScriptMessageHandler by the class you have your WKWebView instance declared in.

Then you need to modify web view's initialization to use custom configuration with required message handler:

let config = WKWebViewConfiguration()
let contentController = WKUserContentController()
contentController.add(self, name: "aMessageHandler")        
config.userContentController = contentController
yourWKWebViewInstance = WKWebView(frame: someCGRect, configuration: config)

After doing so you will be able to receive messages through this function

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
{
    if message.name == "aMessageHandler"
    {
        let yourMessage = message.body as? String
        // Do whatever you need to do with it
    }
}

And to post this message in JS you need to invoke postMessage method like so:

var handleError = function handleError(errorText) {
     window.webkit.messageHandlers.aMessageHandler.postMessage(errorText);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM