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

后端 未结 2 1756
失恋的感觉
失恋的感觉 2020-12-01 03:22

I\'m using Selenium WebDriver to try to insert an external javascript file into the DOM, rather than type out the entire thing into executeScript.

It looks like it p

相关标签:
2条回答
  • 2020-12-01 03:44

    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='somescript.js';\
      window.document.head.appendChild(s);");
    
    0 讨论(0)
  • 2020-12-01 03:55

    Injecting our JS-File into DOM

    Injecting our JS-File into browsers application from our local server, so that we can access our function using document object.

    injectingToDOM.js

    var getHeadTag = document.getElementsByTagName('head')[0]; 
    var newScriptTag = document.createElement('script'); 
    newScriptTag.type='text/javascript'; 
    newScriptTag.src='http://localhost:8088/WebApplication/OurOwnJavaScriptFile.js';
    // adding <script> to <head>
    getHeadTag.appendChild(newScriptTag);
    

    OurSeleniumCode.java

    String baseURL = "http://-----/";
    driver = new FirefoxDriver();
    driver.navigate().to(baseURL);
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    Scanner sc = new Scanner(new FileInputStream(new File("injectingToDOM.js")));
    String inject = ""; 
        while (sc.hasNext()) {          
            String[] s = sc.next().split("\r\n");   
            for (int i = 0; i < s.length; i++) {
                inject += s[i];
                inject += " ";
            }           
        }       
        jse.executeScript(inject);
        jse.executeScript("return ourFunction");
    

    OurOwnJavaScriptFile.js

    document.ourFunction =  function(){ .....}
    

    Note : If you are passing JS-File as String to executeScript() then don't use any comments in between JavaScript code, like injectingToDOM.js remove all comments data.

    0 讨论(0)
提交回复
热议问题