2023-12-22 09:13:53 +01:00
|
|
|
---
|
|
|
|
title: Script block
|
|
|
|
icon: code
|
|
|
|
---
|
2022-05-17 13:48:56 -07:00
|
|
|
|
2024-01-22 09:22:28 +01:00
|
|
|
The "Script" block allows you to execute Javascript code.
|
2022-05-17 13:48:56 -07:00
|
|
|
|
2024-01-22 09:22:28 +01:00
|
|
|
<Info>This block doesn't allow you to create a custom visual block</Info>
|
2022-05-17 13:48:56 -07:00
|
|
|
|
2023-12-22 09:13:53 +01:00
|
|
|
<Frame>
|
|
|
|
<img src="/images/blocks/logic/code.png" width="600" alt="Code block" />
|
|
|
|
</Frame>
|
2022-05-17 13:48:56 -07:00
|
|
|
|
2023-12-22 09:13:53 +01:00
|
|
|
<Info>
|
2023-03-23 10:47:34 +01:00
|
|
|
Variables in script are not parsed, they are evaluated. So it should be treated as if it were real javascript variables.
|
|
|
|
|
|
|
|
You need to write `console.log({{My variable}})` instead of `console.log("{{My variable}}")`
|
2023-12-22 09:13:53 +01:00
|
|
|
|
|
|
|
</Info>
|
2023-03-23 10:47:34 +01:00
|
|
|
|
2024-01-22 09:22:28 +01:00
|
|
|
## `setVariable` function
|
|
|
|
|
|
|
|
If you want to set a variable value with Javascript, the [Set variable block](./set-variable) is more appropriate for most cases.
|
|
|
|
|
|
|
|
However, if you'd like to set variables with the script blocks, you can use the `setVariable` function in your script:
|
|
|
|
|
|
|
|
```js
|
|
|
|
if({{My variable}} === 'foo') {
|
|
|
|
setVariable('My variable', 'bar')
|
|
|
|
} else {
|
|
|
|
setVariable('My variable', 'other')
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
The `setVariable` function is only available in script executed on the server, so it won't work if the `Execute on client?` is checked.
|
|
|
|
|
2022-05-17 13:48:56 -07:00
|
|
|
## Examples
|
|
|
|
|
|
|
|
### Reload page
|
|
|
|
|
|
|
|
```js
|
|
|
|
window.location.reload()
|
|
|
|
```
|
|
|
|
|
2023-03-23 10:47:34 +01:00
|
|
|
### Redirect if a variable has a specific value
|
2022-05-17 13:48:56 -07:00
|
|
|
|
|
|
|
```js
|
2023-03-23 10:47:34 +01:00
|
|
|
if({{Category}} === 'qualified') {
|
|
|
|
window.location.href = 'https://my-site.com'
|
|
|
|
}
|
2022-05-17 13:48:56 -07:00
|
|
|
```
|
|
|
|
|
2023-11-14 08:41:46 +01:00
|
|
|
Do you need to do something but you're not sure how to? [Join the Discord server](https://typebot.io/discord) and get instant help!
|