I want to enter text in a specific element of the WKWebView with the ID "Username" after loading this url: https://app.oncoursesystems.com/homeworkportal/index/brrsd
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=https://app.oncoursesystems.com/homeworkportal/index/brrsd, NSLocalizedDescription=A JavaScript exception occurred})
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})
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
document.getElementById('frame').contentWindow.document.getElementById('Username')