> For the complete documentation index, see [llms.txt](https://docs.adpage.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.adpage.io/integrations-websites/custom/add-the-custom-user-data-script-to-your-website.md).

# Add the custom User Data Script to your website

This article explains how to add the AdPage User Data Script to a custom website or CMS. This script collects marketing and device data. It also pushes the trytagging\_user\_data event to the dataLayer.

{% hint style="info" %}
**Note:** Only use this script when the AdPage plugin or app is **NOT** installed. The AdPage plugin or app handles this automatically for Shopify, WooCommerce, WordPress, Magento, and Lightspeed.
{% endhint %}

### When should you use this script?

| Situation                              | Script required? |
| -------------------------------------- | ---------------- |
| Custom CMS without the AdPage plugin   | ✅ Yes            |
| Custom-built website                   | ✅ Yes            |
| Platform without an AdPage integration | ✅ Yes            |
| Shopify with the AdPage App            | ❌ No             |
| WooCommerce with the AdPage Plugin     | ❌ No             |
| WordPress with the AdPage Plugin       | ❌ No             |
| Magento with the AdPage Extension      | ❌ No             |
| Lightspeed with the AdPage Pixel       | ❌ No             |

***

### What does this script do?

The User Data Script automatically collects:

* **Device information:** Browser, operating system, and screen resolution.
* **Marketing data:** UTM parameters, referrers, campaign data, and session IDs.
* **User identification:** Client ID, session ID, and session count for accurate attribution.

This data becomes available in the dataLayer through `trytagging_user_data`. This event starts all other tracking. Without it, tracking data is not processed correctly.

#### Why is the load order important?

The `trytagging_user_data` event contains key identifiers. These include `client_id`, `session_id`, and `session_count`. All following events use them. Problems occur if other dataLayer events, such as `view_item` or `add_to_cart`, are pushed **before** this script loads:

* Google Tag misses required configuration parameters.
* Sessions cannot be attributed correctly.
* Webhooks do not work correctly because marketing data is missing.
* GA4 and advertising platforms receive incomplete data, or no data.

***

### Step 1: Find your linked domain

Before installing the script, you need your **linked domain**. You can find it in two ways.

#### Option A: Use the installation link

If you received an installation link from AdPage, the instructions include the domain.

#### Option B: Use the Trytagging dashboard

1. Go to the [adpage platform](https://data.adpage.io/) and sign in.
2. Select the correct container.
3. Go to **Implementation** → **Domain name**.
4. Copy your linked domain, for example `tagging.yourwebsite.com`.

{% hint style="info" %}
**Example:** If your linked domain is `tagging.webshop.nl`, use `https://tagging.webshop.nl/user-data-minified.js` as the script URL.
{% endhint %}

***

### Step 2: Install the script

{% hint style="warning" %}
**Important: The load order is critical.**

This script **MUST** load and run **BEFORE** other dataLayer events are pushed. The `trytagging_user_data` event starts your tracking setup. Without it, Google Tag Manager cannot process events such as `view_item`, `add_to_cart`, and `purchase` correctly.

**Place this script:**

* As early as possible in the `<head>` section.
* Before the Google Tag Manager script.
* Before any other tracking scripts.
  {% endhint %}

Copy the following script. **Replace** `[YOUR_LINKED_DOMAIN]` with the linked domain from Step 1.

```html
<script>
(function() {
  // Function to load external script with defer
  function loadScript(url) {
    return new Promise(function(resolve, reject) {
      var script = document.createElement('script');
      script.defer = true;
      script.src = url;
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
  }
  
  // Function to check if taggingHelpers is available
  function checkTaggingHelpers(timeout) {
    timeout = timeout || 10000;
    var startTime = Date.now();
    return new Promise(function(resolve, reject) {
      function check() {
        if (window.taggingHelpers && 
            typeof window.taggingHelpers.getMarketingObject === 'function' && 
            typeof window.taggingHelpers.getDeviceInfo === 'function') {
          resolve();
        } else if (Date.now() - startTime > timeout) {
          reject(new Error('Timeout waiting for taggingHelpers'));
        } else {
          setTimeout(check, 50);
        }
      }
      check();
    });
  }
  
  // Function to collect data from taggingHelpers
  function collectData() {
    try {
      return {
        event: 'trytagging_user_data',
        device: window.taggingHelpers.getDeviceInfo() || {},
        marketing: window.taggingHelpers.getMarketingObject() || {}
      };
    } catch (error) {
      console.error('Error collecting tagging data:', error);
      return null;
    }
  }
  
  // Function to push to dataLayer
  function pushToDataLayer(data) {
    if (!data) return;
    
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push(data);
  }
  
  // Main execution
  function init() {
    loadScript('https://[YOUR_LINKED_DOMAIN]/user-data-minified.js')
      .then(function() {
        return checkTaggingHelpers();
      })
      .then(function() {
        var data = collectData();
        pushToDataLayer(data);
      })
      .catch(function(error) {
        console.error('Error in tagging initialization:', error);
      });
  }
  
  // Start initialization when DOM is ready
  if (document.readyState !== 'loading') {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();
</script>
```

#### Example with a linked domain

If your linked domain is `tagging.webshop.nl`, replace line 42:

```javascript
// From:
loadScript('https://[YOUR_LINKED_DOMAIN]/user-data-minified.js')

// To:
loadScript('https://tagging.webshop.nl/user-data-minified.js')
```

***

### Step 3: Verify the installation

After adding the script, verify that it works correctly.

#### Check 1: Browser console

1. Open your website in Chrome or Firefox.
2. Open Developer Tools with `F12` or `Cmd` + `Option` + `I`.
3. Select the **Console** tab.
4. Confirm there are no red errors related to `tagging` or `user-data`.

#### Check 2: Verify the dataLayer

1. Enter `dataLayer` in the console.
2. Press Enter.
3. Find an object with `event: "trytagging_user_data"`.
4. Confirm the `marketing` and `device` objects contain data.

**Example of correct output:**

```javascript
{
  event: "trytagging_user_data",
  device: {
    browser: "Chrome",
    os: "Windows",
    // ... more device information
  },
  marketing: {
    user_id: "abc123...",
    session_id: "xyz789...",
    // ... more marketing information
  }
}
```

#### Check 3: Network tab

1. Select the **Network** tab in Developer Tools.
2. Refresh the page.
3. Filter for `user-data`.
4. Confirm `user-data-minified.js` loaded successfully with status `200`.

***

### Step 4: Configure Google Tag Manager (optional)

To manage the script through Google Tag Manager instead of your source code:

1. Create a **Custom HTML Tag** in GTM.
2. Paste the complete script, including the `<script>` tags.
3. Set the trigger to **All Pages** or **DOM Ready**.
4. Ensure this tag fires **first**. Use Tag Sequencing if needed.

{% hint style="info" %}
**Important:** Push `trytagging_user_data` before all other ecommerce events. Configure other tags to trigger **after** this event.
{% endhint %}

***

### Troubleshooting

#### The script does not load

**Possible causes:**

* The domain name is incorrect.
* The linked domain is not active in Trytagging.
* The URL contains a typo.

**Resolution:**

1. Confirm that you copied the correct domain from Trytagging.
2. Test `https://[your-domain]/user-data-minified.js` directly in your browser.
3. Contact AdPage support if you receive a `404` error.

#### No data in the dataLayer

**Possible causes:**

* The script appears after other tracking scripts.
* A JavaScript error occurs on the page.
* An ad blocker blocks the script.

**Resolution:**

1. Move the script to the start of the `<head>` section.
2. Check the console for JavaScript errors.
3. Test in an incognito window without extensions.

#### `taggingHelpers` is undefined

**Possible causes:**

* The external script has not loaded yet.
* A network problem occurred.

**Resolution:** The script waits up to 10 seconds for loading. If the issue continues, check:

1. Whether the URL is correct.
2. Whether the console shows CORS errors.
3. Whether a firewall blocks the script.

#### Console error: `Timeout waiting for taggingHelpers`

This means the script was still unavailable after 10 seconds.

**Resolution:**

1. Check your internet connection.
2. Confirm that the script URL is reachable.
3. Increase the timeout value if needed: `timeout = timeout || 10000;` on line 11.

***

### Frequently asked questions

#### Can I combine this with the full custom dataLayer?

Yes. This script only provides the `trytagging_user_data` event.

#### Do I need to add the script to every page?

Yes. The script must appear on **every page** of your website. Push `trytagging_user_data` on every page before other tracking events occur.

#### Does this script work with Consent Mode?

Yes. The script supports Google Consent Mode. When you use a CMP, data is collected only after the visitor gives consent.

#### Do I need this script for Data Assistant?

Yes. The Data Assistant Tag requires `trytagging_user_data` as its start event. Without this script, Data Assistant does not work correctly.

#### What if I have multiple domains?

Each domain needs a separate linked domain in Trytagging. Update the script for each domain with the correct URL.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.adpage.io/integrations-websites/custom/add-the-custom-user-data-script-to-your-website.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
