1

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?

user2924482
  • 8,380
  • 23
  • 89
  • 173
  • Could you please print just `error` and not `error.localizedDescription`? You are hiding detailed information from yourself! – Sulthan Apr 22 '19 at 16:05
  • @Sulthan I have updated the error. Please let me know if you need anything else – user2924482 Apr 22 '19 at 20:17
  • `null is not an object` is obvious. It means there is no element with the given identifier `someElement` (the method `getElementById` returns `null`). Make sure you have typed the identifier correctly and that it really exists in the document. – Sulthan Apr 22 '19 at 21:13

1 Answers1

2

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

Rachit Agarwal
  • 356
  • 2
  • 9