4

How can we execute an external .js file using selenium webdriver file using java selenium. I got some reference "Call external javascript functions from java code", however invoke function is able to accept the function inside that file. I want to just execute the whole file as a whole.

2
  • need to do it as we run the command on cmd prompt, like "node file.js" Commented Feb 26, 2016 at 12:10
  • Where are you using this, appium ?? Commented Feb 26, 2016 at 12:53

2 Answers 2

3

It's as simple as this to run an external JavaScript from your server upon the client:

// Assume Guava, but whatever you use to load files...
String externalJS = Files.toString( new File("external.js"), Charset.forName("utf-8"));

// Execute, assume no arguments, and no value to return
Object ignore = ((JavascriptExecutor) driver).executeScript(externalJS);

The link you provided isn't useful, because it's about executing JavaScript upon the server (within the Java VM) rather than upon the browser/device client.

If rather than executing, you're interested in injecting JavaScript into the page for other scripts etc. to interact with (i.e. rather than a one-off execution), see this question.

Sign up to request clarification or add additional context in comments.

Comments

2

Here is the code for nodeJS calling external JS and executing a function within the JS:

var fs = require('fs');
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;

 var driver = new webdriver.Builder()
.forBrowser('phantomjs')
.build();

var axeSource = fs.readFileSync('lib/axe.js', 'utf8');

driver
    .get('http://www.google.com/ncr')       
driver.executeScript(axeSource)
    .then(function(){
        driver.switchTo().defaultContent();
         driver.executeAsyncScript(function() {
           var callback = arguments[arguments.length - 1];
            window.axe.a11yCheck(document, null, function (results) {
                callback(results);
            });

         }).then(function(str) {
                var viola = processResults(str);
                console.log(viola);
            });
    })


driver.quit();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.