admin管理员组

文章数量:1401592

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.

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.

Share Improve this question edited May 23, 2017 at 10:27 CommunityBot 11 silver badge asked Feb 26, 2016 at 12:09 imdevjyotiimdevjyoti 611 silver badge5 bronze badges 2
  • need to do it as we run the mand on cmd prompt, like "node file.js" – imdevjyoti Commented Feb 26, 2016 at 12:10
  • Where are you using this, appium ?? – Pankaj Kumar Katiyar Commented Feb 26, 2016 at 12:53
Add a ment  | 

2 Answers 2

Reset to default 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.

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./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();

本文标签: javascriptExecute an external js file using selenium webdriverStack Overflow