Execute Code
In this section, we will learn how to use the Execute Code block.
Use Cases
The Execute Code block allows you to run custom JavaScript code for tasks such as complex string manipulation, mathematical calculations, and data format conversion.
Code
You can simply input single-line code, and the result of the code execution will be returned by default. For example:
// Access the page title
document.title
// Access the page URL
location.href
// Ternary operation
$vars.hasMore ? true : false
// Mathematical operation
$vars.a + $vars.b
For more complex logic, you can define it as a function. For example:
function getFullName() {
const firstName = 'Foo'
const lastName = 'Bar'
const fullName = firstName + lastName
return fullName
}
If you need to return a result from the function, make sure to use the return
statement.
Context
The execution context of the code is always within the current tab page. You can access workflow variables:
$args
$vars
$loops
$tables
Important Note:
If the variable is extracted from a page element, it will actually be wrapped as:
{
value: 'Anythings',
target: { id: 'xxx', selector: 'div > p ...' },
__duck__: true
}
Therefore, if the variable name is title
and you want to access its actual value in the code, you need to reference the value
field:
$vars.title.value // Anythings
Variable
If you need to access the result of the code execution, you can assign it to a variable and access it using Template Syntax:
{{@vars.MyVar}}
FAQ
Why is my code not executing?
The code execution environment operates within the current tab. If the tab is a blank page, an extension page, or a page with strict CSP (Content Security Policy) restrictions, custom code cannot be executed.