donkey donkey - 4 months ago 147
Swift Question

What is WKErrorDomain error 4 from WKWebView

fatal error: LPWebView encounters an error: Error Domain=WKErrorDomain Code=4
"A JavaScript exception occurred" UserInfo=0x79d9c700
{NSLocalizedDescription=A JavaScript exception occurred}

I encountered this error when I tried to evaluate a JavaScript function with WKWebView.

I used
to load a template to the webview.

let bundle = NSBundle.mainBundle()

if let editorURL = bundle.URLForResource(self.kTemplateName,
withExtension: "html") {
var error : NSError?
//get html string from editor.html
if let htmlString = String(contentsOfURL: editorURL, encoding: NSUTF8StringEncoding, error: &error){
if error != nil {
assertionFailure("error encountered reading html string for \(error)")
} else {
self.loadHTMLString(htmlString, baseURL: bundle.bundleURL)

} else {
assertionFailure("LPWebView template not found")

I wonder what this error code means and how to solve it?

Thank you very much!


So if we dig into the headers:

/*! @constant WKErrorDomain Indicates a WebKit error. */
@availability(iOS, introduced=8.0)
let WKErrorDomain: String

/*! @enum WKErrorCode
 @abstract Constants used by NSError to indicate errors in the WebKit domain.
 @constant WKErrorUnkcnown                       Indicates that an unknown error occurred.
 @constant WKErrorWebContentProcessTerminated   Indicates that the Web Content process was terminated.
 @constant WKErrorWebViewInvalidated            Indicates that the WKWebView was invalidated.
 @constant WKErrorJavaScriptExceptionOccurred   Indicates that a JavaScript exception occurred.
@availability(iOS, introduced=8.0)
enum WKErrorCode : Int {

    case Unknown
    case WebContentProcessTerminated
    case WebViewInvalidated
    case JavaScriptExceptionOccurred

Error code 4 would corresponds to JavaScriptExceptionOccurred, or WKErrorJavaScriptExceptionOccurred.

In other words, the JavaScript function causes some error.

Probably not more here that you couldn't guess already. For resolution, I would suggest using the developer features of a web browser such as Safari, loading the HTML and debugging.

In fact, as explained in the WWDC 2014 video, "Introducing the Modern WebKit API", your desktop Safari browser can "inspect the WKWebView using the Safari web inspector, including any user scripts that you've injected."

To use this, while the WKWebView is loaded in memory in your running app on the iOS simulator, open the desktop Safari browser and access Develop on the top menu bar then iOS Simulator. That will show a drop down of the web view's document objects.

For more info on debugging JavaScript, take a look at Web Inspector: Understanding Stack Traces