[JavaScriptExecutor] Storing a value in a global variable and retrieving it later

44 views
Skip to first unread message

Dumidu Handakumbura

unread,
Jan 13, 2023, 10:11:09 PM1/13/23
to Selenium Users
Hi All, 

Greetings from Sri Lanka!

I need to attach an event listener to an element and later read a property of the target upon the event trigger. I thought of saving the result in a global variable until my script is ready to read the value. But the return is empty. 

Web Page

Code
driver.switchTo().frame("iframeResult");

String SNIPPET_TO_GET_TARGET_VALUE = "var radio; document.querySelectorAll('[name=\"age\"]').forEach(elem => {elem.addEventListener('click',function(e){ radio = e.target.defaultValue})});";

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(SNIPPET_TO_GET_TARGET_VALUE);

(String) executor.executeScript("return window.radio");

Environment
-Selenium 4.7.2
-Chrome v.108
-Java 1.9 

Thanks,
Dumidu 

Dumidu Handakumbura

unread,
Jan 13, 2023, 10:52:52 PM1/13/23
to Selenium Users
Turns out you need to declare and call the variable with the window prefix. Let me know if anyone knows why var definition didn't create the variable in the window object?

Answer

driver.switchTo().frame("iframeResult");
String SNIPPET_TO_GET_TARGET_VALUE = "window.radio; document.querySelectorAll('[name=\"age\"]').forEach(elem => {elem.addEventListener('click',function(e){ window.radio = e.target.defaultValue})});"; 

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(SNIPPET_TO_GET_TARGET_VALUE);
return (String) executor.executeScript("return window.radio");

Thanks,
Dumidu

David

unread,
Jan 15, 2023, 8:14:39 PM1/15/23
to Selenium Users
It might have to do with variable scoping within the context of the browser, not just regarding the language itself (i.e. javascript usable in node.js, browser, and other types of runtimes in applications, etc.). See the blurb about global scope in HTML here: https://www.w3schools.com/js/js_scope.asp
Reply all
Reply to author
Forward
0 new messages