I'm loading WKWebView with a webpage and I'm trying to execute javascrip:

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

But I'm getting this error:

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}

Why I'm getting this error?, any of you knows what I'm doing wrong or a way around this?

1 Answers

2
Rachit On

document.getElementById() returns null if the element couldn't be found. So I think 'someElement' name is not present in the web page.