user8704637 user8704637 - 3 years ago 411
Javascript Question

getElementById returns null even after page is loaded - WkWebView and Swift

I want to enter text in a specific element of the WKWebView with the ID "Username" after loading this url:
The username field in the webview should be filled with whatever value I specify but whenever I run my code I get this error:

Error: Optional(Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=TypeError: null is not an object (evaluating 'document.getElementById("Username").value='xxx''), WKJavaScriptExceptionColumnNumber=52, WKJavaScriptExceptionSourceURL=, NSLocalizedDescription=A JavaScript exception occurred})

I tried running my code under the method func webView: didFinishNavigation: (with the WKNavigationDelegate) but I got the same error

Here is my code (these are all different tries to get the same result):

let js = "var myelement = document.getElementById(\"Username\").value='xxx'; myelement.innerHTML= \"New Text\";"
webView.evaluateJavaScript(js, completionHandler: nil)

webView.evaluateJavaScript("document.getElementById('Username').value='xxx'", completionHandler: nil)

webView.evaluateJavaScript("window.onload = function() { alert(document.getElementById('Username').value='xxx');};", nil)

//I got this error instead for the last one: Error: Optional(Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type" UserInfo={NSLocalizedDescription=JavaScript execution returned a result of an unsupported type})

I tried all of these on viewDidLoad, webView: didFinishNavigation: (to make sure the html is loaded), and on the click of a button

What can I do to successfully fill the username field of the form with the value 'xxx'? Is this caused by some problem in the link itself or is there somethign wrong with my code?

Answer Source

As per the provided link, the Username field is exist in the iFrame and that is why document.getElementById('Username') is returning null.

Try this instead

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download