Challenge - 5 Problems
JavaScript Execution Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this JavaScript execution in Selenium?
Consider the following Selenium Java code snippet that executes JavaScript to get the page title. What will be the value of
pageTitle after execution?Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
String pageTitle = (String) js.executeScript("return document.title;");Attempts:
2 left
💡 Hint
Remember that executeScript returns an Object that you can cast to the expected type.
✗ Incorrect
The JavaScript executed returns the document's title as a string. Selenium's executeScript returns an Object, which can be cast to String safely here.
❓ assertion
intermediate2:00remaining
Which assertion correctly verifies JavaScript execution result?
You execute JavaScript to get the number of links on a page. Which assertion correctly checks that the number is 10?
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
Long linkCount = (Long) js.executeScript("return document.getElementsByTagName('a').length;");Attempts:
2 left
💡 Hint
Check the type returned by executeScript for numeric values.
✗ Incorrect
executeScript returns a Long for numeric JavaScript values. So comparing with 10L (long literal) is correct.
🔧 Debug
advanced2:00remaining
Why does this JavaScript execution throw an exception?
This Selenium Java code throws a ClassCastException. What is the cause?
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
String result = (String) js.executeScript("return 5 + 5;");Attempts:
2 left
💡 Hint
Check the Java type returned for JavaScript numeric results.
✗ Incorrect
JavaScript numeric results are returned as Long in Java, so casting to String causes ClassCastException.
🧠 Conceptual
advanced2:00remaining
What is the best way to scroll to an element using JavaScript in Selenium?
You want to scroll the page so a specific WebElement is visible. Which JavaScript snippet executed via Selenium is best?
Selenium Java
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.id("myElement"));Attempts:
2 left
💡 Hint
Use arguments to pass WebElement safely to JavaScript.
✗ Incorrect
Passing the element as an argument and calling scrollIntoView on it is the correct and reliable way.
❓ framework
expert3:00remaining
How to safely execute asynchronous JavaScript and get result in Selenium Java?
You want to execute asynchronous JavaScript that calls a callback when done. Which Selenium method and approach is correct?
Attempts:
2 left
💡 Hint
Asynchronous JS requires a callback to signal completion.
✗ Incorrect
executeAsyncScript waits until the JS calls the last argument as a callback to return the result.