JavaScript Executor
Execute JavaScript directly from Selenium to interact with elements, scroll pages, modify content and handle situations where normal WebDriver commands are difficult.
What You Will Practice
- Execute JavaScript through Selenium.
- Click elements using JavaScript.
- Enter values using JavaScript.
- Scroll to an element.
- Scroll to the top and bottom.
- Highlight elements.
- Retrieve page information.
- Show and hide elements.
JavaScript Click
Click an element using JavaScript instead of Selenium click().
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
JavaScript Set Value
Enter text into an input using JavaScript.
js.executeScript(
"arguments[0].value='Selenium Automation';",
element
);
Highlight Element
Change an element's style using JavaScript.
js.executeScript(
"arguments[0].style.border='3px solid red';",
element
);
Scroll to Element
Scroll the browser until a specific element becomes visible.
js.executeScript(
"arguments[0].scrollIntoView(true);",
element
);
Scroll Top & Bottom
Move the browser viewport to the top or bottom of the page.
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
Page Information
Retrieve browser page information using JavaScript.
js.executeScript("return document.title;");
Hide & Show Element
Modify DOM element visibility using JavaScript.
js.executeScript(
"arguments[0].style.display='none';",
element
);
JavaScriptExecutor Cheat Sheet
js.executeScript(
"arguments[0].click();",
element
);
js.executeScript(
"arguments[0].value='Text';",
element
);
js.executeScript(
"arguments[0].scrollIntoView(true);",
element
);
js.executeScript(
"arguments[0].style.border='3px solid red';",
element
);
String title =
(String) js.executeScript(
"return document.title;"
);
js.executeScript(
"window.scrollTo(
0,
document.body.scrollHeight
);"
);