什么是 WKWebView 的 WKErrorDomain 错误 4

问题描述 投票:0回答:1
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")
}

我想知道这个错误代码是什么意思以及如何解决?

非常感谢!

javascript xcode swift ios8 wkwebview
1个回答
17
投票

所以如果我们深入研究标题:

/*! @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

换句话说,JavaScript 函数会导致一些错误。

这里可能没有你猜不到的更多内容。为了解决问题,我建议使用 Safari 等 Web 浏览器的开发人员功能,加载 HTML 并进行调试。

事实上,正如 WWDC 2014 视频“现代 WebKit API 简介” 中所解释的那样,您的桌面 Safari 浏览器可以 “使用 Safari Web 检查器检查

WKWebView
,包括您注入的任何用户脚本。 “

要使用它,当

WKWebView
加载到 iOS 模拟器上正在运行的应用程序的内存中时,打开桌面 Safari 浏览器并访问顶部菜单栏上的 Develop,然后访问 iOS Simulator。这将显示 Web 视图的文档对象的下拉列表。

有关调试 JavaScript 的更多信息,请查看Web 检查器:了解堆栈跟踪

© www.soinside.com 2019 - 2024. All rights reserved.