Executing JavaScript using Snapshots

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.

Note: Since we’re not capturing any metadata with these use cases, the events with these Snapshots will not return any event properties for the Snapshot.

Use Cases

Call APIs

Since Snapshots can trigger JavaScript on your page, Snapshots can be used to call 3rd party APIs, including Heap’s API. As an example, the snippet below adds your users’ most current timezone as a property.

Name: Add timezone as user property

JavaScript Snapshot:

(function() { var tz = Intl.DateTimeFormat().resolvedOptions().timeZone; heap.addUserProperties({ "Timezone": tz }); })();

The Snapshot above is used to trigger Heap’s client-side user property API, and it doesn’t return any data for the Snapshot property. The “Add timezone as user property” name is used simply to let us know what the Snapshot does for this example.

Once captured, you can use this data in your analysis to understand how well your geographically targeted ads are performing.

Check if Users Have Enabled Browser Push Notifications

On modern browsers, you can check how many of your users have enabled your browser push notifications. You can do something similar for checking location permissions if your app depends on it. (This is only supported in select modern browsers.)

Name: Add push notification status as user property

JavaScript Snapshot:

navigator.permissions.query({ name: 'notifications' }).then(function(result) { heap.addUserProperties({"Notifications Permission": result.state }); })

Add Timezone as a Heap User Property

To further enrich your Heap user data, you can capture users’ timezones. The Snapshot below adds the user’s current timezone as a Heap user property by triggering Heap’s client-side [heap.addUserProperties()](https://developers.heap.io/reference#adduserproperties) API. You can have this attached to any event that triggers at least once for users, like a pageview.

JavaScript Snapshot:

(function() {
    var tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
    heap.addUserProperties({
        "Timezone": tz
    });
})();

Capture User State (Tealium)

📘

This example is for customers using our Tealium integration.

This example captures the logged-in user state from a site using Tealium. Other common examples include page_type, site_section, or visitor_type. Use this type of data for high-level content analysis, or to understand how user state affects key behaviors.

Name: Logged In

JavaScript Snapshot

utag_data.customer_logged_in

Analyze Image Types

eCommerce companies often AB test their images. But how can you tell which type of photography converts best: a lifestyle action shot vs a standard product shot? This example captures the name of the image file when clicked. Assuming you have some semantic data in the title that denotes the shot type, you can use this data within a Defined Property to analyze the effectiveness of different image types.

Name: Image

JavaScript Snapshot:

$(event.target).attr('src').split('/').pop()

📘

This example requires jQuery to execute correctly.

Capture Page Load Time

This snapshot is used to trigger custom JavaScript by calling our heap.track() API. Snapshots can be used to run custom Javascript without actually having to return a value, and as such, this example is used to track a completely new event. Note that it does not actually record a snapshot property.

📘

The performance.timing object can be unreliable. For this reason, we recommend excluding all negative values returned by the browser. For more details, see Mozilla’s documentation on this object.

Due to DOM event timing, this can’t be added as an event property, though you can write code similar to the Call APIs use case and fire a track call with the property.

Name: Page load

JavaScript Snapshot:

(function() { var interval = setInterval(sendTrack, 200); function sendTrack() { if (performance.timing.domComplete != 0){ var loadTime = (performance.timing.domComplete - performance.timing.navigationStart) / 1000; heap.track('Page Load', { 'Load Time': loadTime }); clearInterval(interval); } } })();

See how page load time affects your key funnels by starting your analysis with this event and grouping by load time!

📘

Navigation timing events do not update after changes to the History API. The above method will not work on Single Page Applications.

Check if Users Have Enabled Browser Push Notifications

On modern browsers, you can check how many of your users have enabled your browser push notifications. You can do something similar for checking location permissions if your app depends on it (not compatible with all browsers).

The Snapshot below adds whether the user has enabled push notifications or not as a Heap user property by triggering Heap’s client-side [heap.addUserProperties()](https://developers.heap.io/reference#adduserproperties) API.

navigator.permissions.query({
    name: 'notifications'
}).then(function(result) {
    heap.addUserProperties({
        "Notifications Permission": result.state
    });
})

Capture Page Load Time

It may be important for you to know how long it takes for your page to finish loading and how that affects user behavior. We are unable to capture page load time as an event property on a default pageview event because Heap captures a pageview event before the page finishes loading.

The Snapshot below calculates how long it takes for your page to completely load, and it captures a custom Page Load event with a Load Time event property by triggering Heap’s client-side heap.track() API. You can attach this to a View Any Page pageview event to trigger this JavaScript whenever a user views a page on your website.

📘

The performance.timing object can be unreliable. For this reason, we recommend excluding all negative values returned by the browser. For more details, see Mozilla’s documentation on this object.

JavaScript Snapshot:

(function() {
    var interval = setInterval(sendTrack, 200);

    function sendTrack() {
        if (performance.timing.domComplete != 0) {
            var loadTime = (performance.timing.domComplete - performance.timing.navigationStart) / 1000;
            heap.track('Page Load', {
                'Load Time': loadTime
            });
            clearInterval(interval);
        }
    }
})();

📘

Navigation timing events do not update after changes to the History API. The above method will not work on Single Page Applications.

Scroll Tracking

Capturing how far users scroll on your website is important to see if users are viewing all of the content on a page. The Snapshot below measures the full length of a page, and it captures a custom Scroll Depth event by triggering Heap’s client-side heap.track() API every time a user scrolls a 25% of the full length (25%, 50%, 75%, 100%).

On infinite scroll sites, the snippet will continue to capture past the initial 100% mark and be sent over in increments of 25, 125%, 150%, 175%, 200%, and so on based on how much further the user scrolls. This may also happen if the content on your page loads slowly; Heap would capture the length of your page to be something relatively small and this will throw off the percentages since the Snapshot triggers every time a user scrolls 25% of the calculated length.

📘

Scroll depth is calculated on the scroll location within the body element. If the content on your website is contained within a container element, then this Snapshot will not function as expected.

(function() {
    var scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
    var quarterHeight = scrollHeight / 4;
    var quarters = 0;
    var scrollDistance, divisible, scrollPercent;
    document.addEventListener("scroll", function() {
        scrollDistance = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
        divisible = Math.trunc(scrollDistance / quarterHeight);
        if (quarters < divisible && divisible !== Infinity) {
            scrollPercent = divisible * 25;
            heap.track('Scroll Depth', {
                percent: scrollPercent
            });
            quarters++;
        }
    });
}());

Disabling JavaScript Snapshots (Admins only)

Admins can disable JavaScript Snapshots by navigating to Account > Manage > Privacy & Security and clicking the JavaScript Snapshots toggle.

Updated 6 days ago

Executing JavaScript using Snapshots


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.