The Singular Website SDK allows you to attribute website activities to marketing touchpoints and to track user events within your website. It is also a key component in Singular’s cross-device attribution solution, making it possible to analyze user journeys and calculate cross-platform LTV and ROAS.
To learn more, see our Cross-Device Attribution FAQ and Web Attribution FAQ.
Browser Compatibility:
Chrome: 15+ | Edge: 15+ | Internet Explorer: 10+ |
Safari: 5.1+ | Firefox: 6+ | Opera: 15+ |
This guide covers the implemenation of the Website SDK with Singular Web-to-App Banner support using the Google Tag Manager implementation method.
If you are not using Google Tag Manager, you may folow our How to Enable Singular Banners (Developers Guide) to add banners directly to you Native implementaion.
If you are not using Singular Banners you may follow our standard guides found here:
The Singular Website SDK is an Enterprise feature. If you're interested in using this feature, reach out to your Customer Success Manager.
Important
The Singular Banners feature requires special configurations that are incompatible with the Integrated Google Tag Manager (GTM) Templates. Due to this limitation, Singular GTM templates for all tag types cannot be used with this implementation.
If you have already implemented the Singular WebSDK using the GTM Singular templates, you will need to transition to Custom HTML templates. This transition ensures compatibility with the Singular platform and provides greater flexibility and control over your integration.
Prerequisites
Before you integrate the Singular Website SDK, make sure these prerequisites are satisfied:
- Google Tag Manager has been configured on your site.
- You have set up Google Tag Manager triggers as needed for the events that you want to send to Singular (your conversion event and any custom events).
- You have set up Google Tag Manager variables as needed for the events you want to send to Singular. For example, if you want to send transaction events and include the transaction revenue, you need to set up variables for the transaction sum and currency.
Tag 1 - Adding the SDK Library
The Singular JavaScript Library must be loaded or injected on the site before the Singular SDK is initialized or any Singular functions are triggered. To ensure this, the library will be injected using the Custom HTML tag option in Google Tag Manager (GTM).
To maintain proper functionality, the library must be included on all pages of the site. We will use the Window Loaded trigger in GTM to control the timing of the library injection, ensuring it loads after the page content is fully loaded.
- Create a Custom HTML tag to load the SDK Library and Add permission to fetch client hints data.
- Name the Tag "Singular - SDK Loader"
- Insert the following Code into the HTML window
<script> (function() { // Check if singularSdk is already loaded if (window.singularSdk) { return; // SDK already loaded, no need to load again } // Inject the meta tag for client hints delegation var metaTag = document.createElement('meta'); metaTag.setAttribute('http-equiv', 'delegate-ch'); metaTag.setAttribute('content', 'sec-ch-ua-model https://sdk-api-v1.singular.net; sec-ch-ua-platform-version https://sdk-api-v1.singular.net; sec-ch-ua-full-version-list https://sdk-api-v1.singular.net'); document.head.appendChild(metaTag); // Create and load the Singular SDK script var script = document.createElement('script'); script.src = 'https://web-sdk-cdn.singular.net/singular-sdk/latest/singular-sdk.js'; script.async = true; // Once the script is loaded, push to dataLayer script.addEventListener('load', function() { window.dataLayer = window.dataLayer || []; // Ensure dataLayer is initialized window.dataLayer.push({ event: 'singularSDKLibraryLoaded' }); }); // Append the script tag to the head of the document document.head.appendChild(script); })(); </script>
- Under Advanced Settings, set the Tag firing priority to 99
- Under the Triggering section, add a Firing Trigger for "Window Loaded"
- Save the Tag
Tag 2 - SDK Initialization Tag
The Singular SDK initialization code must be executed every time a page is loaded, but only after the Singular - SDK Loader tag has fired. To ensure this, we will use the Data Layer event created by the Singular - SDK Loader tag as the trigger.
Initializing the Singular SDK is a prerequisite for all Singular attribution functionality. It serves two critical purposes:
- Creating a new user session when a user enters the site with new advertising data or when the session timeout has elapsed.
- Sending a "page visit" event to Singular.
These "page visit" events and user sessions are essential for calculating user retention and enabling re-engagement attribution.
Configure GTM User-Defined Variables
To initialize the Singular SDK and enable it to send data to Singular, you must provide the SDK Key, SDK Secret, and Product ID to the SingularConfig object. The code snippet below is designed to retrieve these values from GTM User-Defined Variables. Ensure that you create these variables in Google Tag Manager and assign the correct values before implementing the code.
Retrieving Your SDK Key and SDK Secret
- Log in to your Singular account.
- Navigate to Developer Tools > SDK Integration > SDK Keys.
- Copy the SDK Key and SDK Secret for use in your configuration.
Defining the Product ID
- The Product ID represents your website in Singular. We recommend using the reverse DNS notation of your primary web domain, such as com.example.
- This value will identify your website throughout the Singular platform and must match the App Bundle ID defined on the Apps Page in Singular.
For Websites with Multiple Sub-Domains
If your website spans multiple sub-domains (e.g., www.example.com and shop.example.com), these will be treated as a single app in the Singular platform. In this case, use a unified Product ID like com.example for all sub-domains.
Adding GTM User-Defined Variables
In Google Tag Manager, you should create User-Defined variables to store these values, and then reference them in code snippets when needed:
To create the variables:
- Click on Variables
- Click "New" in the User-Defined Variables section
- Name the Variable and Click on the Variable Configuration box. Note: the Variable Name is how the value will be referenced in code snippets.
- Choose the "Constant" option under Utilities.
- In the Value form field, add the corresponding value for the variable.
Following the process above, create 3 User-defined variables: "Singular SDK Key", "Singular Secret Key", "Singular Product ID".
Build the Initialization Tag
- Create a Custom HTML tag to handle SDK Initialization
- Name the Tag "Singular - SDK Initialization"
- Insert the following Code into the HTML window
<script> (function() { // Check if singularSdk is available before proceeding if (window.singularSdk) { var sdkKey = {{Singular SDK Key}}; var secretKey = {{Singular Secret Key}}; var productId = {{Singular Product ID}}; // Create Singular Banners config object & enable web-to-app support var bannersOptions = new BannersOptions().withWebToAppSupport(); // Create SDK config object with Singular Banners support var config = new SingularConfig(sdkKey, secretKey, productId) .withBannersSupport(bannersOptions); //Add additional option here try { // Initialize the SDK singularSdk.init(config); // Display the banner singularSdk.showBanner(); // Push event to dataLayer after initialization window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'singularSDKInitialized' }); } catch (error) { console.error('Error initializing Singular SDK:', error); } } else { console.warn('Singular SDK not loaded or available.'); } })(); </script>
The code above is a basic example to activate Singular Banners on Initialization. Update the Singular Config Object Options for your needs.
- Under Advanced Settings, set the Tag firing priority to 98.
- Under the Triggering section, add a Firing Trigger for a Custom Event.
- Name the Trigger: "singularSDKLoaded"
- Specify the Trigger Event name: "singularSDKLibraryLoaded"
- Save the Tag
The Tag sequence should be as follows when testing in the GTM Preview:
- On the Window Loaded Event: Singular - SDK Loader Tag is fired.
- singularSDKLibraryLoaded Event is pushed to the datalayer.
- Singular - SDK Initialization Tag is fired
- singularSDKInitialized Event is pushed to the datalayer.
SingularConfig Options
You will probably want to add settings to enable various capabilities offered by Singular. To add settings, you will use the SingularConfig object's ".with" methods. For example:
// Configure the SDK to pass the user ID to Singular
const config = new SingularConfig(sdkKey, sdkSecret, productId)
.withCustomUserId(userId);
SingularConfig Method Reference
Here are all the available ".with" methods.
Method | Description | Learn More |
.withCustomUserId(customId) | Send the user ID to Singular | Setting the User ID |
.withProductName(productName) | An optional display name for the product | |
.withLogLevel(logLevel) | Configure the logging level: 0 - None (Default); 1 - Warn; 2 - Info; 3 - Debug. | |
.withSessionTimeoutInMinutes (timeout) | Set the session timeout in minutes (default: 30 minutes) |
|
.withAutoPersistentSingularDeviceId (domain) | Enable automatic cross-subdomain tracking | Auto-Persist using Cookies |
.withPersistentSingularDeviceId (singularDeviceId) |
Enable manual cross-subdomain tracking | Set Singular Device ID Manually |
.withInitFinishedCallback(callback) | Invoke a callback when SDK initialization is complete | Invoking a Callback Function when Initialization is Complete |
Supporting Single Page Applications (SPAs)
For Single Page Applications (SPAs), where the page content changes dynamically without a full page reload, the History Change trigger in Google Tag Manager (GTM) is an excellent option to detect route changes. Configure a 3rd Custom HTML Tag to ensure the appropriate Singular SDK methods, like pageVisit(), hideBanner(), and showBanner(), are called only on route changes and not on the initial page load.
GTM Configuration:
Create a History Change Trigger
- In GTM, create a new trigger
- Select Trigger Type: History Change
Create a Custom HTML tag for History Changes
- Name the Tag "Singular - SPA Route Change"
- Insert the following Code into the HTML window
<script> (function () { try { // Ensure Singular SDK is loaded if (window.singularSdk) { // Check if this is the first page load if (!window.singularFirstLoad) { // Mark the first page as processed window.singularFirstLoad = true; console.log('First page load detected. Singular pageVisit skipped.'); } else { // Call Singular's pageVisit for subsequent route changes singularSdk.pageVisit(); console.log('Singular pageVisit triggered for SPA route change.'); } // Hide the current banner singularSdk.hideBanner(); // Delay to ensure route change completion var delay = 200; // Delay in milliseconds setTimeout(function () { // Show the new banner for the current route singularSdk.showBanner(); console.log('Singular banner updated for new route.'); }, delay); } else { console.warn('Singular SDK is not defined. Ensure the SDK is loaded before using this script.'); } } catch (error) { console.error('Error during Singular SPA navigation:', error); } })(); </script>
- Assign the History Change trigger to the tag.
- Save and Test
Sending the User ID to Singular (Optional)
You may send your internal User ID to Singular using a Singular SDK method.
Note: If you use Singular's Cross-Device solution, you must collect the User ID across all platforms.
- The User ID can be any identifier and should not expose PII (Personally Identifiable Information). For example, you should not use a User's email address, username, or phone number. Singular recommends using a hashed value unique only to your first-party data.
- The User ID value passed to Singular should also be the same internal User ID you capture across all platforms (Web/Mobile/PC/Console/Offline).
- Singular will include the User ID in user-level exports, ETL, and Internal BI postbacks (if configured). The User ID is first-party data, and Singular does not share it with other parties.
- The User ID value, when set with the Singular SDK Method, will persist until it is unset using the logout() method or until the browser local storage is deleted. Closing or refreshing the website does not unset the User ID.
- In private/incognito mode, the SDK cannot persist the user ID because the browser automatically deletes the local storage when it is closed.
To set the User ID, use the login() method. To unset it (for example, if the User "logs out" of the account), call logout() method.
Note: If multiple Users use a single device, we recommend implementing a logout flow to set and unset the User ID for each login and logout.
If you already know the user ID when the Singular SDK is initialized on the website, set the User ID in the config object. This way, Singular can have the User ID from the first Session. However, the User ID is typically unavailable until the User registers or performs a login. In that case, call login() after the registration flow is complete. It is recommended to push a datalayer Event when a user performs an Authentication flow which can be used with a GTM Custom Event Trigger to fire the Singular Login function.
- Create a Custom HTML tag to handle Authentication
- Name the Tag "Singular - Authentication Tag"
- Insert the following Code into the HTML window
<script> (function() { // Ensure sessionStorage is available if (typeof sessionStorage === 'undefined') { console.warn('sessionStorage is not supported in this environment.'); return; } // Check if the event has already been triggered in this session if (sessionStorage.getItem('sng_login_triggered')) { console.log('Singular SDK event already triggered this session.'); return; // Exit if the event was triggered before in this session } // Check if singularSdk is available and initialized if (window.singularSdk && typeof singularSdk.login === 'function' && typeof singularSdk.event === 'function') { // Dynamically fetch UserID if available (replace with actual method if applicable) var userID = window.userID || "User123456789"; // Example fallback value for userID try { // After Authentication, Pass the UserID as the Singular Custom User ID Value singularSdk.login(userID); // Send the Registration_Completed event (or similar event) singularSdk.event("sng_login"); // Set a flag in sessionStorage to indicate that the event was triggered sessionStorage.setItem('sng_login_triggered', 'true'); console.log('Singular SDK event triggered successfully.'); } catch (error) { console.error('Error triggering Singular SDK event:', error); } } else { console.warn('Singular SDK is not loaded or required methods are unavailable.'); } })(); </script>
- Under the Triggering section, add a Firing Trigger for a Custom Event.
- Name the Trigger: "singularAuthentication"
- Specify the Trigger Event name corresponding to the datalayer Event name available after a user Authenticates on your website.
- Save the Tag
The code snippets above demonstrate how to implement the Singular Native JavaScript WebSDK using GTM Custom HTML Tags to support Banners. For further customization, such as sending events and tracking revenue, refer to the Native SDK documentation for detailed function definitions. You can then build additional Custom HTML Tags as needed to extend your implementation.