I attempted to inject external JavaScript code into Selenium Webdriver by modifying the DOM. Here is the code snippet I used for 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();");
}
}
The corresponding JavaScript file looks like this:
document.ourFunction = function(){
alert("Hey");
}
function test() {
alert(1);
}
This image shows a snippet of my project structure where the JS file is located at the same level as the Testing class:
https://i.sstatic.net/vxfIh.png However, despite the injection process seeming to work, the external JavaScript file does not load properly. If I replace the source file name with direct JavaScript code (e.g., an alert), it works fine. But when I try to use the contents from the JS file, it fails. Can you identify what mistake I might be making?