First, we initialize the driver using the following method:
1 New firefoxdriver (); 2
1. Direct incoming JavaScript code
You can pass in JavaScript code directly to JSE:
1 Jse.executescript ("Window.document.getElementById (' Jingshou ')." Click () ";
2. Incoming webelement execution JS:
1 webelement element = Driver.findelement (By.id ("Jingshou")); 2 Jse.executescript ("Arguments[0].click ();", Element);
Or:
1 Jse.executescript ("Arguments[0].onclick=function () {alert (' This is my alert! ');}", Element)
where Auguments[0] represents element, even we can pass in more parameters, such as
1 Webelement div = driver.findelemnt (by.id ("mydiv")); 2 Jse.executescript ("Arguments[0].setattribute (' style ', arguments[1])", Div, "height:1000px");
By executing the above code, the div We specify adds (modifies) the properties of style {height:1000px}
Use JavaScript in Webdriver to use Javascriptexector objects on the ground
First, through the downward transformation javascriptexecutor js = (javascriptexecutor) driver; Convert to Javascriptexector Object
Then call the Executescript () method to execute JS.
Cases:
1. Open the Google home page
2. Get the title---document.title in the Web page via JS
3. Get the number of links in the Web page----var links = document.getelementsbytagname (' A '); Return links.length
The specific implementation is as follows
1 Packagecom.example.tests; 2 Import Staticorg.junit.assert.*; 3 Importorg.junit.*; 4 Importorg.openqa.selenium.*; 5 ImportOrg.openqa.selenium.ie.InternetExplorerDriver; 6 7 Public classTest {8 @Test9 Public voidTestjavascriptcalls () {TenWebdriver Driver =NewInternetexplorerdriver (); OneDriver.get ("http://www.google.com.hk"); AJavascriptexecutor js =(javascriptexecutor) driver; -string title = (string) js.executescript ("Return Document.title"); -Assertequals ("Google", title); the LongLinks = (Long) js.executescript ("var links =" -+ "document.getElementsByTagName (' A ');" -+ "Return Links.length"); -Assertequals (32, links); + Driver.close (); - } +}
To return data from JavaScript code, we need to use the return keyword. Based on the type of return value, we need to transform the Executescript () method. For values with decimal points, use a double type, non-decimal values can use a long type, Boolean values can use the Boolean type, and if you are returning an HTML node, you can use the Webelement type, the literal value, and the string type. If a list of objects is returned, any value based on the object type can be.
Executing JavaScript in Webdriver