Selenium-JavascriptExecutor - Notes By ShariqSP
JavascriptExecutor
What is JavaScript Executor in Selenium?
JavaScript Executor is a feature in Selenium WebDriver that allows executing JavaScript code within the context of the current browser window or frame.
Why do we need JavaScript Executor in Selenium?
- Handling Dynamic Elements
- Performance Testing
- Scrolling
- Debugging
How to use JavaScript Executor in Selenium?
- Create JavaScript Executor object
- Execute JavaScript code
- Interact with Web Elements
click here to practice JavascriptExecutor
try the below
//enable disabled buttondocument.getElementById('hbtn').disabled = false;
//disable enabled button
document.getElementById('hbtn').disabled = true;
//send text to disabled text box
document.getElementById("dtext").value='shariq s p';
//change squarebox color
document.getElementById('sbox').style.backgroundColor ='black'
// unhide hidden button
document.getElementById('hbtn').style.visibility='visible'
// hide visible button
document.getElementById('hbtn').style.visibility='hidden'
// scroll page horizontal
window.scrollBy(1000,0)
// scroll page veritcally
window.scrollBy(0,1000)
Tasks:
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
//scroll page in omayo blog spot vertically 100pxs
driver.get("https://omayo.blogspot.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(2000);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");
//scroll page in sixeastern blog spot horizontally 1000pxs
driver.get("https://sixeastern.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(6000);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(1000,0)");
Thread.sleep(5000);
driver.quit();
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
// scroll page in omayo blog spot where alert will be displayed at top
// scrollIntoView(true) for top
// scrollIntoView(false) for bottom
driver.get("https://omayo.blogspot.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(2000);
JavascriptExecutor js = (JavascriptExecutor) driver;
// js.executeScript("document.getElementById('alert1').scrollIntoView(true)");
WebElement confirm = driver.findElement(By.id("confirm"));
js.executeScript("document.getElementById('alert1').scrollIntoView(arguments[0])",true);
//or
//js.executeScript("arguments[0].scrollIntoView(true)", confirm);
Thread.sleep(5000);
driver.quit();
}
//javascriptExecutor for facebook to send data to hidden field (Custom gender)
//once you send data oyu'll not be able to see untill you click on customgender button
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
// scroll page in omayo blog spot where alert will be displayed at top
// scrollIntoView(true) for top
// scrollIntoView(false) for bottom
driver.get("https://facebook.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(2000);
WebElement create = driver.findElement(By.partialLinkText("Create new account"));
create.click();
Thread.sleep(2000);
WebElement custome_gender = driver.findElement(By.name("custom_gender"));
js.executeScript("arguments[0].value='male';", custome_gender);
Thread.sleep(5000);
driver.quit();
}
//javascriptExecutor for woodland to send data to search field
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.woodlandworldwide.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(2000);
WebElement search = driver.findElement(By.id("standard-bare"));
js.executeScript("document.getElementById('standard-bare').value='shariq';", search);
Thread.sleep(5000);
driver.quit();
}
// javascriptExecutor for downloading jdk for windows in oracle
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.oracle.com/in/java/technologies/downloads/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(2000);
driver.findElement(By.id("rt01tab6-java8-windows")).click();
Thread.sleep(2000);
driver.findElement(By.partialLinkText("jdk-8u401-windows-i586.exe")).click();
Thread.sleep(2000);
// js.executeScript("document.getElementById('rt01tab6-java8-windows').scrollIntoView(false)",
// search);
WebElement JDKdownload = driver.findElement(By.partialLinkText("Download jdk-8u401-windows-i586.exe"));
js.executeScript("arguments[0].click()", JDKdownload);
Thread.sleep(5000);
driver.quit();
}
// javascriptExecutor to send text you disabled seach in omayo webpage
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://omayo.blogspot.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(2000);
WebElement disabledseacrch = driver.findElement(By.id("tb2"));
Thread.sleep(2000);
js.executeScript("document.getElementById('tb2').value='shariq';", disabledseacrch);
Thread.sleep(5000);
driver.quit();
}
Few Other Examples of using JavaScript Executor in Selenium:
Example 1: Scrolling to an Element
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
Example 2: Changing Element Style
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].style.border='3px solid red'", element);
Example 3: Retrieving Page Title
JavascriptExecutor js = (JavascriptExecutor) driver;
String pageTitle = (String) js.executeScript("return document.title;");
System.out.println("Page Title: " + pageTitle);
Example 4: Clicking on a Hidden Element
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("hiddenButton"));
js.executeScript("arguments[0].click();", element);
Example 5: Returning Inner Text of an Element
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
String innerText = (String) js.executeScript("return arguments[0].innerText;", element);
Example 6: Performing a Mouse Hover
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));", element);
Example 7: Scrolling to the Bottom of the Page
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
Example 8: Setting Attribute Value
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].setAttribute('value', 'new value')", element);
Example 9: Focusing on an Element
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].focus();", element);
Example 10: Checking if an Element is Visible
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
boolean isVisible = (boolean) js.executeScript("return arguments[0].offsetWidth > 0 && arguments[0].offsetHeight > 0;", element);
Example 11: Extracting URLs of All Links on a Page
JavascriptExecutor js = (JavascriptExecutor) driver;
List links = (List) js.executeScript("return document.getElementsByTagName('a');");
for (WebElement link : links) {
System.out.println(link.getAttribute("href"));
}
Example 12: Making Element Visible
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].style.display = 'block';", element);
Example 13: Zooming In/Out of a Page
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.body.style.zoom = '80%';");
Example 14: Disabling Right-Click Context Menu
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.oncontextmenu = function(){return false;}");
Example 15: Checking if a Page is Fully Loaded
JavascriptExecutor js = (JavascriptExecutor) driver;
boolean isPageLoaded = (boolean) js.executeScript("return document.readyState").equals("complete");
Example 16: Generating a Custom Alert
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('This is a custom alert!');");
Example 17: Getting Current URL
JavascriptExecutor js = (JavascriptExecutor) driver;
String currentURL = (String) js.executeScript("return window.location.href;");
Example 18: Removing Element from DOM
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("elementId"));
js.executeScript("arguments[0].parentNode.removeChild(arguments[0]);", element);
Example 19: Disabling Input Fields
JavascriptExecutor js = (JavascriptExecutor) driver;
List inputFields = driver.findElements(By.tagName("input"));
for (WebElement inputField : inputFields) {
js.executeScript("arguments[0].setAttribute('disabled', 'true');", inputField);
}
Example 20: Resizing Browser Window
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.resizeTo(1024, 768);");
JavaScript Executor Interview Questions
- What is the JavaScript Executor in Selenium WebDriver?
- When would you use JavaScript Executor in your Selenium tests?
- How do you create an instance of the JavaScript Executor in Selenium WebDriver?
- Explain the executeScript() method in the JavaScript Executor.
- What are the advantages of using JavaScript Executor in Selenium WebDriver?
- How do you execute JavaScript commands using the JavaScript Executor?
- What is the difference between executeScript() and executeAsyncScript() methods?
- Explain some common use cases of JavaScript Executor in Selenium WebDriver.
- How do you return values from JavaScript code executed by the JavaScript Executor?
- How do you handle asynchronous JavaScript code execution using the JavaScript Executor?
- What exceptions can occur while using JavaScript Executor in Selenium WebDriver?
- Explain how you scroll to an element using JavaScript Executor.
- How do you highlight an element using JavaScript Executor?
- What is the purpose of injecting JavaScript code using the JavaScript Executor?
- Explain how you handle JavaScript alerts using the JavaScript Executor.
- How do you set attribute values of elements using JavaScript Executor?
- What is the role of the WebDriver's built-in JavaScript Executor in handling asynchronous JavaScript code?
- How do you perform JavaScript actions on hidden elements using the JavaScript Executor?
- Explain how you retrieve text from hidden elements using the JavaScript Executor.
- What are some limitations of using JavaScript Executor in Selenium WebDriver?
Multiple Choice Questions (MCQs)
- Which method is used to execute JavaScript code in Selenium WebDriver?
- executeScript()
- executeJavaScript()
- runScript()
- executeJS()
- What is the purpose of the executeAsyncScript() method in Selenium WebDriver?
- To execute asynchronous JavaScript code.
- To execute synchronous JavaScript code.
- To execute JavaScript alerts.
- To execute JavaScript code with a delay.
- How do you return values from JavaScript code executed by the JavaScript Executor?
- Using return statement
- Using executeAsyncScript()
- Using executeScript()
- Using waitUntil()
- What exceptions can occur while using JavaScript Executor in Selenium WebDriver?
- WebDriverException
- TimeoutException
- JavaScriptException
- All of the above
- How do you scroll to an element using JavaScript Executor?
- scrollToElement()
- scrollIntoView()
- scrollTo()
- scrollBy()
- What is the purpose of injecting JavaScript code using the JavaScript Executor?
- To interact with the web page directly using JavaScript
- To bypass WebDriver's limitations
- To improve performance of tests
- All of the above
- How do you handle JavaScript alerts using the JavaScript Executor?
- Using accept() and dismiss() methods
- Using executeScript() method
- Using switchTo() method
- Using getWindowHandles() method
- What is the role of the WebDriver's built-in JavaScript Executor in handling asynchronous JavaScript code?
- It ensures that the JavaScript code is executed asynchronously
- It waits for the JavaScript code to complete execution before continuing
- It has no role in handling asynchronous JavaScript code
- It executes JavaScript code with a delay
- What are some limitations of using JavaScript Executor in Selenium WebDriver?
- It may not work properly on certain browsers
- It may affect the performance of tests
- It may introduce security vulnerabilities
- All of the above