JavaScript
Zuar Portal provides a means for adding custom JavaScript code to any Page.
Creating Snippets
Snippets can be created in two places:
- Admin Console - Navigate to the JavaScript section of the Admin panel. Add your code as a Snippet, rename it, and click Save.
- Sidebar Editor - When editing a page, open the Page section of the sidebar. The JavaScript Snippets area allows you to add, remove, and reorder snippets for that page.
Snippets are edited using the Code Editor, which provides syntax highlighting and code completion for JavaScript. You can use the inline editor in the sidebar or open the full external Code Editor window for a larger editing surface.
Adding Snippets to Pages
Snippets can be added to one or more Pages and will be run once the page loads. Multiple Snippets can be added and loaded in the desired order by dragging and dropping.
You can use JavaScript Snippets to perform tasks such as pulling data from a 3rd party API and displaying it in an HTML block. You can utilize the System JavaScript API to access data about the Page, Blocks, and more from your Snippet.
Unloading of JavaScript
When using JavaScript on Pages to add event handlers, it is important to properly unload it. Let's imagine that we want to track a global click event using Page JavaScript with next the following Snippet.
let clickListener = function () {
console.log('document click', new Date().toISOString());
}
document.addEventListener('click',clickListener);
Navigating through Portal pages will create and register new event listener every time the JavaScript Snippet is called. To avoid such behaviour, we need to properly clean up all side affects of our Page JavaScript. To do so, we can modify the snippet above.
let clickListener = function () {
console.log('document click', new Date().toISOString());
}
document.addEventListener('click',clickListener);
return {
onDestroy:function() {
document.removeEventListener('click',clickListener)
}
}
The function returned in the onDestroy key in our new snippet will be be called when the user leaves the page.