Use Snapshots to execute JavaScript
Overview
Snapshots are typically used by non-devs to capture additional metadata as an event property that’s not automatically captured by Heap. They can also be used by developers to trigger custom JavaScript on your website without capturing any event properties.
We can leverage snapshots to trigger client-side APIs whenever an event is triggered. This doc covers use cases where snapshots are used to trigger JavaScript without returning an event property.
For a general overview of how snapshots work and use cases for non-devs, see the Snapshots guide in our Help Center. To set up a JavaScript Snapshot from the event definition page, click the Add Snapshot button and select to value of javascript in the drop-down.
Implementation
When working with custom JavaScript, choose between two formatting options. Use the IIFE (Immediately Invoked Function Expression) pattern for scoped encapsulation, or opt for a simpler structure without wrapping the code in any function. Tailor your approach based on the project's requirements for clarity and efficiency. Examples for each option are provided below for easy implementation.
Option 1: IIFE (Immediately Invoked Function Expression)
If you prefer to encapsulate your code within a function for scoping purposes, use the IIFE (Immediately Invoked Function Expression) pattern. Example:
(function() {
// Your code here
})();
Option 2: No Wrapping Function
If you prefer not to wrap your code in any function, simply write your code without any surrounding function. Example:
// Your code here
Some of these use cases are not capturing any metadata, so the events with those Snapshots will not return any event properties for the Snapshot.
Use Cases
For a full set of use cases, see the docs directly below this one as listed on the sidebar.
- Find the Index Position of a Selected Element in a List via Snapshots
- Call APIs via Snapshots
- Add Timezone as a Heap User Property via Snapshots
- Capture User State (Tealium) via Snapshots
- Analyze Image Types via Snapshots
- Capture Page Load Time via Snapshots
- Check if Users Have Enabled Browser Push Notifications via Snapshots
- Scroll Tracking via Snapshots
- Capturing Data from the Data Layer via Snapshots
Disabling JavaScript Snapshots (Admins only)
Admins can disable JavaScript snapshots by navigating to Account > Manage > Privacy & Security and clicking the JavaScript Snapshots toggle.
Updated 8 months ago