executeScript (JS code, variable) - Selenium IDE command

executeScript

The executeScript command executes a snippet of JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. To store the return value, use the 'return' keyword and provide a variable name in the value input field.

executeScript_Sandbox

The executeScript_Sandbox works exactly as executeScript but runs the Javascript in a sandbox. In other words, the code runs not in the website. The advantage of using the sandbox is that the website can not influence or block the Javascript execution. So unless you want to access elements of the website, better use the sandbox. The new versions of the flow control commands (if_v2, while_v2, GotoIf_v2) use executeScript_Sandbox internally to evaluate the expression.

A good example is the Github.com website. If that website is loaded, executeScript (without sandbox) fails with errors such as "Call to eval() blocked by CSP". CSP stands for (Chrome) Content Security Policy error. The website blocks the Javascript execution. But executeScript_Sandbox works just fine, as the Javascript is not executed inside the website.

Useful Javascript snippets for use with executeScript

Use them like executeScript | Javascript here | VarWithResult. Then later in the macro, you can use the result with the ${VarWithResult} variable.

All example snippets in the first table work fine in the sandbox. We recommend to use executeScript_Sandbox, but executeScript will work as well.

Javascript (executeScript_Sandbox recommended) Result
return Math.floor(Math.random()*11) Random number between 0 and 10
return Number (${i}) + 1; Increase the value of i by one (very useful inside loops)
var x="abc"; return x.length; Returns the length of the string (here 3).
x="${myvar}"; return x.length; Same as above but with variable as input.
var audio = new Audio('http://www.storiesinflight.com/html5/audio/shimmer.wav');audio.play(); Play sound!
var d=new Date(); return d.getDate()+'-'+((d.getMonth()+1))+'-'+d.getFullYear(); Get todays date
var d= new Date(); var m=((d.getMonth()+1)<10)?'0'+(d.getMonth()+1):(d.getMonth()+1); return d.getFullYear()+"-"+m+"-"+d.getDate(); Get todays date in YYYY-MM-DD format
var d= new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 5); var m=((d.getMonth()+1)<10)?'0'+(d.getMonth()+1):(d.getMonth()+1); m=d.getFullYear()+"-"+m+"-"+d.getDate(); return m Get yesterday's date (-1), tomorrows date (1) or the date in 5 days (5) => Just change the number 5 in the code snippet.
return parseFloat("${!runtime}")-parseFloat("${starttime}") Calculate the difference between the current runtime and the start time. Very useful for measuring website performance
var x = parseInt((new Date('2018-03-20T12:00:00') - new Date()) / 1000); return Math.max(0, x); Countdown to specific date and time. Use the result as input for PAUSE

The examples below all interact with the website, that is why we need to use executeScript.

Javascript (executeScript only) Result
return window.document.getSelection().toString() Copy selected text (e. g. text marked with Ctrl+A)
alert("Hello World!") Show an alert box. [Needs website] Note: Since Chrome 64 the prompt box is only shown (by Chrome) if the tab has the focus. This is a change in Chrome, not Kantu. Better use PAUSE | 0
return prompt("Please enter a value") Ask user for input and store it in a variable. Note: Since Chrome 64 the prompt box is only shown (by Chrome) if the tab has the focus. This is a change in Chrome, not Kantu. Better use the internal PROMPT command of Kantu.
return window.document.getElementsByName('Phone')[0].value; Retrieve the field value an input box. This is also a replacement for storeValue from the old IDE. storeAttribute does not work with input boxes.
return document.getElementByClassName(“label-bold”)[0].innerHTML; Extract some data, in this case from "<div class=“label-bold”> Order Number# 123456 </div>"
window.history.go(-1); Simulate BACK button click

execute Script Example

This example calculates 100-20, and then sets the page title to the result (80).

Command Target Pattern/Text
open https://ui.vision/
store 100 Var1
store 20 Var2
executeScript_Sandbox return Number (${Var1}) - Number (${Var2}) Var3
executeScript document.title = ${Var3};
assertTitle 80

Works in

Kantu for Chrome Selenium IDE, Kantu for Firefox Selenium IDE, Firefox IDE Classic

Related Demo Macros

DemoStoreEval

The ready-to-import-and-run source code of all demo macros can be found in the Github repository testmacros folder.

See also

storetext, storetitle, Web Automation Extension User Manual, Selenium IDE commands, Classic Firefox Selenium IDE.

Anything wrong or missing on this page? Suggestions?

...then please contact us.

Kantu Selenium IDE for Chrome and Firefox - Web Test Automation
Subscribe to the a9t9 automation software newsletter . We'll send you updates on new releases that we're working on.