If your website is a single-page application (SPA), includes functionality that the standard page-view tracking cannot catch or you wish to do more advanced tracking, Leadfeeder’s JavaScript API is useful to you.

Examples where the JavaScript API can be used:

  • Track transitions/virtual page views in single-page apps.
  • Track non-page view events, such as in-page dialogs or video/media playback.

API usage

The Leadfeeder tracker script exposes a set of methods for the web page to call if needed. All these methods exist under the window.ldfdr -object in the page.

NOTE: When using the Leadfeeder JavaScript API it is good to keep in mind that Leadfeeder Tracker supports multiple trackers on one page. The methods in the JavaScript API are designed so that, by default, the behavior is applied to all trackers. However, you can call them for specific tracker instances only. As an example, if you have two different Leadfeeder tracker scripts on the web page, calling window.ldfdr.track() will send a tracking event for both.

pageview()

Sends a page view event. It supports arguments as an object.

window.ldfdr.pageview({ 
pageUrl: "https://www.example.com",
pageTitle: "Example page"
});

If the arguments are not present, it will default to window.location.href for pageUrl and document.title for pageTitle.

For SPA tracking, calling window.ldfdr.pageview()without arguments after a state change is usually enough as new pageUrl and pageTitle will be automatically picked up.

getAll()

Returns an array of all tracker instances on the page. See getTracker() below for details on how to interact with the tracker instances.

getTracker(trackerId)

Get a tracker instance by trackerId. For the tracker instance following methods are supported:

var tracker = window.ldfdr.getTracker("abcdef");
// Sends a pageview to specific tracker, supports
//same arguments as pageview() above
tracker.pageview();

getClientId()

You can obtain the Leadfeeder clientId with the following call:

window.ldfdr.getTracker("abcdef").getClientId()

ClientID is the visitor ID that is stored in the Leadfeeder cookie. It matches to the lf_client_id field that is returned from the Leadfeeder API's visits end-point.

Sample use case: SPA tracking with Google Tag Manager

STEP 1: Add a new Custom HTML tag in your Google Tag Manager.

STEP 2: Name as appropriate.

STEP 3: Add the following code to HTML section:

<script>
window.ldfdr.pageview();
</script>

STEP 4: Configure a trigger for "History change".

STEP 5: Test in Google Tag Manager’s Debug mode.

NOTE: This approach relies on your SPA firing a History change/push state change event on transitions, or changes the URL fragment. If neither of these happens, you can consider alternative triggers such as pushing an event from site JavaScript to GTM DataLayer.

Did this answer your question?