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?

3
  • Could you please print just error and not error.localizedDescription? You are hiding detailed information from yourself! Commented Apr 22, 2019 at 16:05
  • @Sulthan I have updated the error. Please let me know if you need anything else Commented Apr 22, 2019 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. Commented Apr 22, 2019 at 21:13

1 Answer 1

2
+25

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.