您的位置:首页 > Web前端 > JavaScript

【selenium webdriver】selenium.JavascriptExecutor.executeScript() 使用实例

2018-03-29 09:28 656 查看
Example 1
Project: syndesis-qe   File: CommonSteps.java   View Source Code	Vote up	6 votes
/**
* Scroll the webpage.
*
* @param topBottom possible values: top, bottom
* @param leftRight possible values: left, right
* @returns {Promise<any>}
*/
@When("^scroll \"([^\"]*)\" \"([^\"]*)\"$")
public void scrollTo(String topBottom, String leftRight) {
WebDriver driver = WebDriverRunner.getWebDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;

int x = 0;
int y = 0;

Long width = (Long) jse.executeScript("return $(document).width()");
Long height = (Long) jse.executeScript("return $(document).height()");

if (leftRight.equals("right")) {
y = width.intValue();
}

if (topBottom.equals("bottom")) {
x = height.intValue();
}

jse.executeScript("(browserX, browserY) => window.scrollTo(browserX, browserY)", x, y);
}

Example 2
Project: ats-framework   File: HiddenHtmlTable.java   View Source Code	Vote up	6 votes
/**
* Get the value of the specified table field
*
* @param row the field row starting at 0
* @param column the field column starting at 0
* @return the value
*/
@Override
@PublicAtsApi
public String getFieldValue( int row, int column ) {

new HiddenHtmlElementState(this).waitToBecomeExisting();

WebElement table = HiddenHtmlElementLocator.findElement(this);
String script = "var table = arguments[0]; var row = arguments[1]; var col = arguments[2];"
+ "if (row > table.rows.length) { return \"Cannot access row \" + row + \" - table has \" + table.rows.length + \" rows\"; }"
+ "if (col > table.rows[row].cells.length) { return \"Cannot access column \" + col + \" - table row has \" + table.rows[row].cells.length + \" columns\"; }"
+ "return table.rows[row].cells[col];";

JavascriptExecutor jsExecutor = (JavascriptExecutor) webDriver;
Object value = jsExecutor.executeScript(script, table, row, column);
if (value instanceof WebElement) {

return ((WebElement) value).getText().trim();
}
return null;
}

Example 3
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   View Source Code	Vote up	6 votes
@Action(object = ObjectType.SELENIUM, desc = "Set encrypted data on [<Object>]", input=InputType.YES)
public void setEncryptedByJS() {
if (Data != null && Data.matches(".* Enc")) {
if (elementEnabled()) {
try {
Data = Data.substring(0, Data.lastIndexOf(" Enc"));
byte[] valueDecoded = Base64.decodeBase64(Data);
JavascriptExecutor js = (JavascriptExecutor) Driver;
js.executeScript("arguments[0].value='" + new String(valueDecoded) + "'", Element);
Report.updateTestLog(Action, "Entered Text '" + Data + "' on '" + ObjectName + "'", Status.DONE);
} catch (Exception ex) {
Report.updateTestLog(Action, ex.getMessage(), Status.FAIL);
Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
throw new ElementException(ElementException.ExceptionType.Element_Not_Enabled, ObjectName);
}
} else {
Report.updateTestLog(Action, "Data not encrypted '" + Data + "'", Status.DEBUG);
}
}

Example 4
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   View Source Code	Vote up	6 votes
@Action(object = ObjectType.SELENIUM, desc = "Click on [<Object>]")
public void clickByJS() {
if (elementPresent()) {
try {
JavascriptExecutor js = (JavascriptExecutor) Driver;
js.executeScript("arguments[0].click();", Element);
Report.updateTestLog(Action, "Clicked on " + ObjectName, Status.DONE);
} catch (Exception ex) {
Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
Report.updateTestLog(Action, "Couldn't click on " + ObjectName + " - Exception " + ex.getMessage(),
Status.FAIL);
}
} else {
throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
}
}

Example 5
Project: opentest   File: ExecuteScript.java   View Source Code	Vote up	6 votes
@Override
public void run() {
super.run();

String script = this.readStringArgument("script");
Boolean async = this.readBooleanArgument("async", false);
Integer timeoutSec = this.readIntArgument("timeoutSec", 20);

this.waitForAsyncCallsToFinish();

driver.manage().timeouts().setScriptTimeout(timeoutSec, TimeUnit.SECONDS);
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
if (async) {
jsExecutor.executeAsyncScript(script);
} else {
jsExecutor.executeScript(script);
}
}

Example 6
Project: Cognizant-Intelligent-Test-Scripter   File: JSCommands.java   View Source Code	Vote up	6 votes
@Action(object = ObjectType.SELENIUM, desc = "Clear the element [<Object>]")
public void clearByJS() {
if (elementPresent()) {
try {
JavascriptExecutor js = (JavascriptExecutor) Driver;
js.executeScript("arguments[0].value=''", Element);
Report.updateTestLog(Action, "Cleared value from '" + ObjectName + "'", Status.DONE);
} catch (Exception ex) {
Logger.getLogger(JSCommands.class.getName()).log(Level.SEVERE, null, ex);
Report.updateTestLog(Action,
"Couldn't clear value on " + ObjectName + " - Exception " + ex.getMessage(), Status.FAIL);
}
} else {
throw new ElementException(ElementException.ExceptionType.Element_Not_Found, ObjectName);
}
}

Example 7
Project: phoenix.webui.framework   File: SeleniumEngine.java   View Source Code	Vote up	5 votes
/**
* 计算工具栏高度
* @return 高度
*/
public int computeToolbarHeight()
{
JavascriptExecutor jsExe = (JavascriptExecutor) driver;
Object objectHeight = jsExe.executeScript("return window.outerHeight - window.innerHeight;");
if(objectHeight instanceof Long)
{
toolbarHeight = ((Long) objectHeight).intValue();
}

return toolbarHeight;
}

Example 8
Project: Cognizant-Intelligent-Test-Scripter   File: ImageCommand.java   View Source Code	Vote up	5 votes
public void pageDownBrowser(int dh) {
if (isHeadless()) {
SCREEN.type(Key.PAGE_DOWN);
} else {
dh = Math.max(0, dh);
JavascriptExecutor jse = ((JavascriptExecutor) Driver);
jse.executeScript(String.format("window.scrollBy(0, window.innerHeight-%s)", dh));
}
}

Example 9
Project: AlipayAuto   File: AlipayAuto.java   View Source Code	Vote up	5 votes
private static String getOppositeUser(String transactionNo) {
// ��ȡ�ؼ��ֶ�Ӧ��������
WebElement keywordInput = driver.findElement(By.id("J-keyword"));
keywordInput.clear();
keywordInput.sendKeys(transactionNo);
WebElement keywordSelect = driver.findElement(By.id("keyword"));
List<WebElement> options = keywordSelect.findElements(By.tagName("option"));
// until������ʾֱ���ɵ��ٵ�
// WebElement selectElement = wait.until(ExpectedConditions
// .visibilityOfElementLocated(By.id("keyword")));
// ��Ҫִ��JavaScript��䣬����ǿתdriver
JavascriptExecutor js = (JavascriptExecutor) driver;
// Ҳ������ô��setAttribute("style","");
js.executeScript("document.getElementById('keyword').style.display='list-item';");
js.executeScript("document.getElementById('keyword').removeAttribute('smartracker');");
js.executeScript("document.getElementById('keyword').options[1].selected = true;");
js.executeScript("document.getElementById('J-select-range').style.display='list-item';");
// ���ý���ʱ��ѡ��
Select selectTime = new Select(driver.findElement(By.id("J-select-range")));
selectTime.selectByIndex(3);// ѡ�е������������
System.out.println("selectTime.isMultiple() : " + selectTime.isMultiple());
// ���ùؼ���ѡ��
Select selectKeyword = new Select(driver.findElement(By.id("keyword")));
// selectKeyword.selectByValue("bizInNo");//�˴���value��д<option>��ǩ�е�valueֵ
selectKeyword.selectByIndex(1);// ѡ�е��ǽ��׺�
System.out.println("selectKeyword.isMultiple() : " + selectKeyword.isMultiple());
WebElement queryButton = driver.findElement(By.id("J-set-query-form"));// �õ�������ť
// ���������ť
queryButton.submit();
WebElement tr = driver.findElement(By.id("J-item-1"));// �Ȼ�ȡtr
WebElement td = tr.findElement(By.xpath("//*[@id=\"J-item-1\"]/td[5]/p[1]"));
return td.getText();
}

Example 10
Project: saladium   File: SaladiumDriver.java   View Source Code	Vote up	5 votes
@Override
public void html5Erreur(String selector) {
this.logger.debug("Appel du test messageErreur()");
JavascriptExecutor js = this;
Boolean s = (Boolean) js.executeScript("return document.querySelector('"
+ selector + "').validity.valid");
if (!s) {
Assert.fail(selector + " " + s
+ " Un message de sevérité ERROR devrait être présent!");
}
}

Example 11
Project: ats-framework   File: RealHtmlElementState.java   View Source Code	Vote up	5 votes
private void highlightElement(
boolean disregardConfiguration ) {

if (webDriver instanceof PhantomJSDriver) {
// it is headless browser
return;
}

if (disregardConfiguration || UiEngineConfigurator.getInstance().getHighlightElements()) {

try {
WebElement webElement = RealHtmlElementLocator.findElement(element);
String styleAttrValue = webElement.getAttribute("style");

JavascriptExecutor js = (JavascriptExecutor) webDriver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
webElement,
"background-color: #ff9; border: 1px solid yellow; box-shadow: 0px 0px 10px
c71e
#fa0;"); // to change text use: "color: yellow; text-shadow: 0 0 2px #f00;"
Thread.sleep(500);
js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
webElement,
styleAttrValue);
} catch (Exception e) {
// swallow this error as highlighting is not critical
}
}
}

Example 12
Project: Actitime-Framework   File: HelperManager.java   View Source Code	Vote up	5 votes
/**
* This method makes the driver scroll to the specified webelement in
* browser
**/
public static boolean scrollTo(WebElement wb, WebDriver driver) {
try {
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("arguments[0].scrollIntoView(true);", wb);

} catch (Exception e) {
e.printStackTrace();
}
return wb.isDisplayed();
}

Example 13
Project: AutomationFrameworkTPG   File: ParkMobile.java   View Source Code	Vote up	5 votes
public void addUserFunction(String userName, String passwordText){
user.sendKeys(userName);
password.sendKeys(passwordText);
loginButton.click();
waitForElement(userManagement, 30);
userManagement.sendKeys(Keys.ENTER);
JavascriptExecutor ex = (JavascriptExecutor)driver;
ex.executeScript("arguments[0].click();", addUser);
waitForElement(userType, 60);
}

Example 14
Project: Cognizant-Intelligent-Test-Scripter   File: SwitchTo.java   View Source Code	Vote up	5 votes
@Action(object = ObjectType.BROWSER, desc ="Open a new Browser window", input =InputType.OPTIONAL)
public void createAndSwitchToWindow() {
try {
JavascriptExecutor js = (JavascriptExecutor) Driver;
js.executeScript("window.open(arguments[0])", Data);
Set<String> Handles = Driver.getWindowHandles();
Driver.switchTo().window((String) Handles.toArray()[Handles.size() - 1]);
Report.updateTestLog(Action, "New Window Created and Switched to that ", Status.DONE);
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex);
Report.updateTestLog(Action, "Error in Switching Window -" + ex.getMessage(), Status.DEBUG);
}
}

Example 15
Project: Cognizant-Intelligent-Test-Scripter   File: AXE.java   View Source Code	Vote up	5 votes
private String execute(final String command, final Object... args) {
this.driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
JavascriptExecutor js = ((JavascriptExecutor) this.driver);
Object response = js.executeAsyncScript(command, args);
String result = (String) js.executeScript("return JSON.stringify(arguments[0]);", response);
return result;
}

Example 16
Project: Cognizant-Intelligent-Test-Scripter   File: Basic.java   View Source Code	Vote up	4 votes
private void highlightElement(WebElement element, String color) {
JavascriptExecutor js = (JavascriptExecutor) Driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, " outline:" + color + " solid 2px;");
}

Example 17
Project: BrainBridge   File: Service.java   View Source Code	Vote up	4 votes
/**
* Serves the given create request of the given client
*
* @param clientSocket
*            Client to serve
* @throws WindowHandleNotFoundException
*             If a window handle could not be found
* @throws IOException
*             If an I/O-Exception occurs
*/
private void serveCreateRequest(final Socket clientSocket) throws WindowHandleNotFoundException, IOException {
if (this.mLogger.isDebugEnabled()) {
this.mLogger.logDebug("Serving create request.");
}

// Check if limit is reached
if (this.mIdToBrainInstance.size() >= MAX_INSTANCES) {
HttpUtil.sendError(EHttpStatus.SERVICE_UNAVAILABLE, clientSocket);
this.mLogger.logInfo("Rejected create request, limit reached.");
return;
}

// Create a window handle for a new brain instance
String windowHandle = null;

// Create a new blank window
WebDriver rawDriver = this.mDriver;
while (rawDriver instanceof IWrapsWebDriver) {
rawDriver = ((IWrapsWebDriver) rawDriver).getRawDriver();
}

if (!(rawDriver instanceof JavascriptExecutor)) {
throw new DriverNewWindowUnsupportedException(rawDriver);
}
final JavascriptExecutor executor = (JavascriptExecutor) rawDriver;
this.mDriver.switchTo().window(this.mControlWindowHandle);
executor.executeScript("window.open();");

// Find the window
for (final String windowHandleCandidate : this.mDriver.getWindowHandles()) {
if (!this.mWindowHandles.contains(windowHandleCandidate)) {
windowHandle = windowHandleCandidate;
this.mWindowHandles.add(windowHandleCandidate);
break;
}
}

if (windowHandle == null) {
throw new WindowHandleNotFoundException();
}

// Create a new brain instance
final BrainInstance instance = new BrainInstance(this.mDriver, windowHandle);
instance.initialize();
final String id = instance.getId();

if (id == null) {
// Instance is invalid, throw it away
instance.shutdown();
this.mWindowHandles.remove(windowHandle);

this.mLogger.logError("Instance can not be created since id is null: " + id);
HttpUtil.sendError(EHttpStatus.INTERNAL_SERVER_ERROR, clientSocket);
return;
}

this.mIdToBrainInstance.put(id, instance);

this.mLogger.logInfo("Created instance: " + id);
HttpUtil.sendHttpAnswer(id, EHttpContentType.TEXT, EHttpStatus.OK, clientSocket);
}

Example 18
Project: twitter-stuff   File: SeleniumPlayground.java   View Source Code	Vote up	4 votes
public static void main(String[] args) {

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(Constants.APPLICATION_CONFIGURATION);

Properties properties = new Properties();
try {
properties.load(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

// Set the chrome executable location
System.setProperty(Constants.WEBDRIVER_CHROME_DRIVER, Constants.WEBDRIVER_CHROME_DRIVER_PATH);
WebDriver driver = new ChromeDriver();

driver.get("https://twitter.com");

WebElement loginButton = driver.findElement(By.linkText("Log in"));
loginButton.click();

WebDriverWait wait = new WebDriverWait(driver, 1000);
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("login-dialog")));

WebElement loginDialog = driver.findElement(By.id("login-dialog"));

WebElement usernameElement = loginDialog.findElement(By.cssSelector("input[type='text']"));
usernameElement.sendKeys(properties.getProperty("twitter.username", ""));

WebElement passwordElement = loginDialog.findElement(By.cssSelector("input[type='password']"));
passwordElement.sendKeys(properties.getProperty("twitter.password", ""));

WebElement submitElement = loginDialog.findElement(By.cssSelector("input[type='submit']"));
submitElement.click();

wait.until(
ExpectedConditions.invisibilityOfElementLocated(
By.id("login-dialog")));

driver.get("https://twitter.com/realDonaldTrump/status/738233323344920576");

// make the page zoom level 80%
// driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.COMMAND, Keys.SUBTRACT));
// driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.COMMAND, Keys.SUBTRACT));

JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
javascriptExecutor.executeScript("document.body.style.zoom = 80%");
}

Example 19
Project: zucchini   File: ScrollStep.java   View Source Code	Vote up	4 votes
@Then("^I scroll up$")
public void iScrollUp() throws Throwable {
JavascriptExecutor jse = (JavascriptExecutor)getWebDriver();
jse.executeScript("window.scrollBy(0,-250)");
}

Example 20
Project: yadaframework   File: YadaSeleniumUtil.java   View Source Code	Vote up	2 votes
/**
* Return a value calculated via javascript.
* @param javascriptCode Any valid javascript code with a return value
* @param webDriver
* @return
*/
public String getByJavascript(String javascriptCode, WebDriver webDriver) {
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
return (String) javascriptExecutor.executeScript(javascriptCode);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: