Reputation: 129
I am trying to inject Javascript code into Selenium webdriver using external javascript source. So basically, I inject the DOM with this:
public class Testing extends BaseInitialization{
public static void main(String args[]) {
new Testing();
}
public Testing() {
driver.get("http://www.google.com/");
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse
.executeScript("var s=window.document.createElement('script');" +
" s.type = 'text/javascript'; s.src='elementController.js';" +
" window.document.head.appendChild(s);");
jse.executeScript("test();");
}
}
And here is my js file:
document.ourFunction = function(){
alert("Hey");
}
function test() {
alert(1);
}
And this is a snippet from my project structure (js file is at the same level as Testing class is):
But for some reason, the external javascript is not loaded at all. Injection itself seems to work because when I replace the source file name with direct javascript (alert for example), then it works (Browser opens, it goes to google and alerts), but when I try to take javascript from js file, then it fails. What am I doing wrong?
Upvotes: 0
Views: 2297
Reputation: 13712
You must insert the script node into head node, this will make the browser to execute the javascript in script node or in src file. This is very important.
Below code worked fine when run on my chrome, an alert with test will pop-up.
public void aa() throws InterruptedException {
String script =
"var head= document.getElementsByTagName('head')[0];" +
"var script= document.createElement('script');" +
"script.type= 'text/javascript';" +
"script.src= 'test.js';" +
"head.appendChild(script);";
driver.get("file:///C:/workspace/js-projects/tey/reports/cucumber_report.html");
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(script);
Thread.sleep(3000);
js.executeScript("test()");
Thread.sleep(10000);
}
Content of test.js
function test() {
alert('test');
}
Upvotes: 1
Reputation: 129
Okay. I would like to update the answer. I am not sure, but maybe the thing with the following input is that it will never find this external location because it tries to look this file from google server. But when I use Scanner class to make a javascript string and add it directly to s.src, then it seems to work.
Upvotes: 0