Fatal error: LPWebView encounters an error: Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo=0x79d9c700 {NSLocalizedDescription=A JavaScript exception occurred}
当我尝试使用WKWebView评估JavaScript函数时遇到此错误.
我使用loadHTMLString将模板加载到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") }
非常感谢你!
解决方法
所以如果我们深入研究标题:
/*! @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 }
错误代码4将对应于JavaScriptExceptionOccurred或WKErrorJavaScriptExceptionOccurred.
可能不会在这里你已经猜不到了.为了解决这个问题,我建议使用Safari等Web浏览器的开发人员功能,加载HTML和调试.
事实上,正如WWDC 2014 video,“Introducing the Modern WebKit API”中所解释的,您的桌面Safari浏览器可以“使用Safari Web检查器检查WKWebView,包括您注入的任何用户脚本”.
要使用此功能,当WKWebView加载到iOS模拟器上正在运行的应用程序的内存中时,打开桌面Safari浏览器并访问顶部菜单栏上的Develop,然后访问iOS模拟器.这将显示Web视图的文档对象的下拉列表.
有关调试JavaScript的更多信息,请查看Web Inspector: Understanding Stack Traces