I am trying to execute JavaScript through Swift. I am trying to enter text into a textbox and click a button. However, when I try to do both, only the text entering works. It works when I only try to do one. Changing the order (clicking the button and then entering the text) still only enters the text, but doesn't click the button. In addition, if I manually enter text into the box, the JavaScript won't change the text, but it will click the button. Here is the JavaScript:
function grabID (parent, child)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(child);
if ( descendants.length )
return descendants[0];
return null;
}
grabID("search-form", "input").value = "test";
grabID("search-form", "button").click();
I use the function grabID to reference the search bar and button because they don't have an ID. When I put this exact code into the JavaScript console on Chrome, it works perfectly without any issues. I have tried multiple different ways of calling this, first putting the JavaScript all into one EvaluateJavaScript
, then I broke it up into multiple calls of EvaluateJavaScript
. All of this returned the same odd result. I am currently trying:
if let jsSourcePath = Bundle.main.path(forResource: "scripted", ofType: "js") {
do {
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
self.webby.evaluateJavaScript(jsSourceContents)
}
catch {
print(error.localizedDescription)
}
}
Scripted.js is the file where the JavaScript is and webby is the Web View. For testing purposes, this is in a function that is called when a button is clicked in the app. How could I change this so it always changes the text (even if there is already text in the search bar) and always clicks the button? Thanks.