Cocoa Swift:错误evaluateJavaScript可选(“发生JavaScript异常”)

问题描述 投票:1回答:1

我正在加载带有网页的WKWebView,我正在尝试执行javascript:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { 
     webView.evaluateJavaScript("document.getElementById('someElement').innerText") { (result, error) in
        if error != nil {
            print(error?.localizedDescription ?? "")
        }
    }
}

但是我收到了这个错误:

po error
▿ Optional<Error>
  - some : Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=TypeError: null is not an object (evaluating 'document.getElementById('someElement').innerText'), WKJavaScriptExceptionColumnNumber=39, WKJavaScriptExceptionSourceURL=https://somewebsite.com/, NSLocalizedDescription=A JavaScript exception occurred}

为什么我收到这个错误?,你们中的任何人都知道我做错了什么或解决这个问题?

swift cocoa wkwebview wknavigationdelegate
1个回答
2
投票

如果找不到该元素,document.getElementById()将返回null。所以我认为网页中没有'someElement'这个名字。

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