How do I load a javascript file into the DOM using selenium?

According to this: http://docs.seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriver.jsp

You might be using the browserbot to obtain a handle to the current
window or document of the test. Fortunately, WebDriver always
evaluates JS in the context of the current window, so you can use
“window” or “document” directly.

Alternatively, you might be using the browserbot to locate elements.
In WebDriver, the idiom for doing this is to first locate the element,
and then pass that as an argument to the Javascript. Thus:

So does the following work in webdriver?

WebDriver driver = new FirefoxDriver();
((JavascriptExecutor) driver)
  .executeScript("var s=window.document.createElement('script');\
  s.src="https://stackoverflow.com/questions/17385779/somescript.js";\
  window.document.head.appendChild(s);");

Leave a Comment