我是靠谱客的博主 爱撒娇凉面,最近开发中收集的这篇文章主要介绍(转)Selenium-11: Execute JavaScript with JavascriptExecutor,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Outline

Sometimes we cannot handle some conditions or problems with Webdriver, web controls don’t react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change values, test flash/HTML5 and so on. In order to do these, we can use Selenium’s JavascriptExecutor interface which executes JavaScript through Selenium driver. It has “executeScript” & “executeAsyncScript” methods, to run JavaScript on current browser.

Please, also check my “Selenium Webdriver wait for JavaScript JQuery and Angular” article to learn how to wait Asynchronous calls in your test automation codes.

Before sync and async JavaScript theory and examples, I want to show how to see and run javascript commands on a browser’s console tab. For example, when you go http://www.anaesthetist.com/mnm/javascript/calc.htmwebsite you will see a calculator which is written with Javascript.

First of all, we have to enable Script and Console panels.

javascript

javascript

In Script tab you can see the written Javascript code.

javascript

In Console tab you can call JavaScript functions and see their results.

javascript

javascript

Let’s do an example. In our example page as you see below calculation is done by “Calculate()” function. If we click “9” and then click “+” and then click “3” and at last step call “Calculate()” function on Console tab, we will get the “12” as a result.

javascript_6

javascript_7

Now, let’s do this example with Selenium JavascriptExecutor.

Test Scenario

  1. Go to http://www.anaesthetist.com/mnm/javascript/calc.htm
  2. Click “9”
  3. Click “+”
  4. Click “3”
  5. Declare JavascriptExecutor and Call Calculate() method.
  6. Assert that result is 12

Test Code:

 

Execute JavaScript with executeScript() Method

JavascriptExecutor interface comprises of executeScript() method that executes JavaScript in the context of the currently selected frame or window.
Within the script, use document to refer to the current document. Local variables will not be available once the script has finished executing, though global variables will persist.

[1]
If the script has a return value (i.e. if the script contains a return statement), then the following steps will be taken:  [1]
•    For an  HTML element, this method returns a  WebElement
•    For a  decimal, a  Double is returned
•    For a  non-decimal number, a  Long is returned
•    For a  boolean, a  Boolean is returned
•    For all  other cases, a  String is returned.
•    For an  array, return a  List<Object> with each object following the rules above. We support nested lists.
•    Unless the value is null or there is no return value, in which null is returned.

 

Arguments must be a number, a boolean, a StringWebElement, or a list of any combination of the above. An exception will be thrown if the arguments do not meet these criteria. [1]

javascript_8

I want to give extra examples that shows you what can you do with JavascriptExecutor.

Alert Pop window

Get Page Title

Refresh Browser Window

Scroll-Down Until an Element Displayed

Highlight an Element

javascript_9

Hide and Show an Element

javascript_10

Create an Anonymous Function and add it to the Global Window

Navigate to Other Page

» Source Code of All Examples for executeScript() Method «

 

Execute JavaScript with executeAsyncScript() Method

JavascriptExecutor interface comprises of executeAsyncScript() method that is called an additional final argument “arguments[arguments.lenght-1];” which is a callback function to signal that async execution has finished. We have to call from JavaScript, to tell Webdriver, that our Asynchronous execution has finished. If we do not do that, then executeAsyncScpript will timeout and throw a timeout exception.

The first argument passed to the callback function will be used as the script’s result. This value will be handled as follows: [1]

  • For an HTML element, this method returns a WebElement
  • For a number, a Long is returned
  • For a boolean, a Boolean is returned
  • For all other cases, a String is returned.
  • For an array, return a List<Object> with each object following the rules above. We support nested lists.
  • Unless the value is null or there is no return value, in which null is returned

Before we execute AsyncScriptwe have to make sure to set the script timeoutIts default is 0If we do not set a script timeout, our executeAsyncScript will immediately timeout and it won’t work.

Make sure you set the script timeout before you call it.

I want to show you two examples for AsyncScript. One of them is sleep browser for 4 seconds (4000 milliseconds). The second one is about injecting XMLHttpRequest and wait for the result.

First Example: Performing a sleep in the browser under test.

Test Scenario:

  • First I will get the start time before waiting 4 seconds by using executeAsyncScript() method.
  • Then, I will use executeAsyncScript() to wait 4 seconds.
  • Then, I will get the current time
  • I will subtract (current time – start time) = passed time
  • Assert that passed time is greater than 4 seconds.

Test Code:

Console Output:

javascript_11

Second Example: Injecting a XMLHttpRequest with POST Method

Our test site is: http://phppot.com/demo/jquery-dependent-dropdown-list-countries-and-states/

It contains a getState(val) function to gather cities according to the country parameter.

javascript_15

Before selecting country lets open Firefox or Chrome’s network tab and then select “USA” as a country.
Then you will see the POST request details as shown below:

Headers:
You can see the all details about headers as shown below.

javascript_12

Post:
Then click the POST tab to see parameters that we send by POST method. In this example our parameter is “country_id” and its value is “5”.

javascript_13

Response:
In this tab, you can see the response of the POST method.

javascript_14

Now it is time to test below scenario.

  1. Select USA as a country.
  2. Use executeAsyncScript() method to wait callback function executed. It signals that async execution has finished.
  3. Assert that response contains “New York”

Test Code:

Console Output:

javascript_16

References

[1]  https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html
 

 

By  Onur Baskirt| January 27th, 2016|Selenium, Test Automation, Web Automation|11 Comments

About the Author: Onur Baskirt

 
onur baskirt
Onur Baskirt is a senior IT professional with 10+ years of experience. He worked at Bahçesehir University, ST Microelectronics, Huawei and Ericsson as research assistant, design verification engineer and software test leader. Also, he worked as software test leader and software operations manager at Turkey's biggest technology retailer, Teknosa. Now, he is working as Head of Software Testing and Manager of two Development Teams at Kariyer.net. His current research areas are technical software testing, programming, and computer science. Formerly, he has several research works and papers on digital chip design & verification. His hobbies are sport, dancing, traveling, and nutrition. You can find detailed information about him on his linked-in page.

11 Comments

 
  1. Nitish March 6, 2016 at 1:50 pm  - Reply

    Gained a lot of information and techniques through this article !

  2. Manoj Pahuja March 10, 2016 at 4:21 am  - Reply

    Very useful

  3. Vladimir Belorusets March 11, 2016 at 4:57 am  - Reply

    Very good work!

  4. Sampath May 4, 2016 at 5:49 pm  - Reply

    Thanks a lot for sharing,

    Can you share your thoughts on how to perform with DragAndDrop Action using javascript?

    • onur baskirt
      Onur Baskirt May 5, 2016 at 2:28 am  - Reply

      Hi Sampath,

      Thanks for your valuable comments. I suggest you to check below two links.

      Python Version: http://stackoverflow.com/questions/29381233/how-to-simulate-html5-drag-and-drop-in-selenium-webdriver#_=_
      Java Version: https://github.com/vikramvi/Selenium-Java/commit/a1354ca5854315fded8fc80ba24a4717927d08c7

  5. Sumanta September 8, 2016 at 3:22 pm  - Reply

    I have one question on selenium…..How to scroll up or down on modal pop-up window? When i try to scroll the modal pop-up by programmatically, it only scrolls the background page but not the modal pop-up. Anybody can help me on this?

    • onur baskirt
      Onur Baskirt September 8, 2016 at 8:32 pm  - Reply

      Maybe you can try this with JAVASCRIPTEXECUTOR $(‘#yourmodal-id’).scrollTop($(‘#suggestDetails’).offset().top);

      Also, please check this solutions on stackoverflow:
      http://stackoverflow.com/questions/22709200/selenium-webdriver-scrolling-inside-a-div-popup
      http://stackoverflow.com/questions/28212634/scrolling-to-a-element-in-bootstrap-modal-in-web-driver-is-not-working

  6. Amol September 26, 2016 at 1:34 pm  - Reply

    Hello Onur,

    Can you please help me understand what is wrong in the below mentioned

    return (boolean) js.executeScript(“$(arguments[0]).hasAttribute($(arguments[1‌​]))”, element, attr);…..element is the WebElement and attr is the attribute which I want to search in the element and js is the JavaScriptExecutor

    • onur baskirt
      Onur Baskirt September 26, 2016 at 1:54 pm  - Reply

      Hi Amol,

      Please try below code.

      JavascriptExecutor js = (JavascriptExecutor) driver;
      WebElement element = driver.findElement(By.linkText(“Click ME”)); //This should be your element
      return js.executeScript(“arguments[0].hasAttribute(‘attr’)”,element);

      Reference: http://stackoverflow.com/questions/19934703/how-to-use-javascript-to-set-attribute-of-selected-web-element-using-selenium-we

  7. Sri Laks December 20, 2016 at 12:49 am  - Reply

    Hi Onur

    I want to login to facebook and post. Able to login to facebook. Once i logged in, we have placeholder to post. It is being displayed as “What’s in your mind”.

    I am able to control the container through javascript executor but unable to click. It means we have to make the container to be active to click. Do we really need to use Javascript executor or any other way to click and post in facebook (our) home page. Can i request you to clarify? Please do the needful. Please input facebook credentials to run this below code.

    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.interactions.Actions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class FBTextArea {

    WebDriver driver;

    public FBTextArea()
    {
    driver = new FirefoxDriver();
    }

    private void login(String userName, String password)
    {
    driver.get(“http://www.facebook.com”);
    driver.findElement(By.id(“email”)).sendKeys(userName);
    driver.findElement(By.id(“pass”)).sendKeys(password);
    driver.findElement(By.id(“loginbutton”)).click();
    }

    private WebElement waitAndGet(By by)
    {
    WebDriverWait wait = new WebDriverWait(driver, 30);
    return wait.until(ExpectedConditions.visibilityOfElementLocated(by));
    }

    public void textAreaPostActions()
    {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript(“document.getElementById(‘feedx_container’).style.display=’block'”);
    js.executeScript(“arguments[0].click();”, driver.findElement(By.xpath(“//div[@class=’_1mf _1mj’]”)));
    }
    public static void main(String[] args) {

    FBTextArea Fbt = new FBTextArea();
    Fbt.login(“”,””);
    Fbt.textAreaPostActions();

    }

    }

    • SW Test Academy January 15, 2017 at 6:26 pm  - Reply

      Hi Sri,

      As I know you are doing the right. I really could not figure out whats wrong with that solution. Maybe it is better to put some breakpoints and some debugging texts in your code and examine the problem. If you find a solution, please let us know. One more thing if the page use AJAX call, it is better to wait it with Jquery active property as shown below. Reference: http://stackoverflow.com/questions/33348600/selenium-wait-for-ajax-content-to-load-universal-approach

      public boolean waitForJSandJQueryToLoad() {

      WebDriverWait wait = new WebDriverWait(driver, 30);

      // wait for jQuery to load
      ExpectedCondition jQueryLoad = new ExpectedCondition() {
      @Override
      public Boolean apply(WebDriver driver) {
      try {
      return ((Long)((JavascriptExecutor)getDriver()).executeScript(“return jQuery.active”) == 0);
      }
      catch (Exception e) {
      // no jQuery present
      return true;
      }
      }
      };

      // wait for Javascript to load
      ExpectedCondition jsLoad = new ExpectedCondition() {
      @Override
      public Boolean apply(WebDriver driver) {
      return ((JavascriptExecutor)getDriver()).executeScript(“return document.readyState”)
      .toString().equals(“complete”);
      }
      };

      return wait.until(jQueryLoad) && wait.until(jsLoad);
      }

    •  

 

转载于:https://www.cnblogs.com/a00ium/p/7198014.html

最后

以上就是爱撒娇凉面为你收集整理的(转)Selenium-11: Execute JavaScript with JavascriptExecutor的全部内容,希望文章能够帮你解决(转)Selenium-11: Execute JavaScript with JavascriptExecutor所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部