0

I'm building a chrome extension and I'm trying to access the DataLayer, from within one of my Chrome Extension JS files. However, I'm returned the following error: dataLayer undefined

And if I try and access a specific node in the dataLayer... window.dataLayer.Test: Uncaught TypeError: Cannot read property 'Test' of undefined

If I console.log directly in console chrome dev tools, I can access the dataLayer and specific nodes within fine.

It's the first time I'm building a chrome extension... What am I missing?

This is what I'm trying to loop through a node in the dataLayer and print it's values, in my chrome extension. Here are key files:

INJECT.JS - Where I am trying to access the dataLayer:

function createDiv() {
  var div = document.createElement('div');
  div.classList.add('CRO-toolBar-Container');
    div.style.position = 'fixed';
    document.body.appendChild(div);
}

function updateDataLayer() {
  var dataLayer = window.dataLayer;
  console.log('WINDOW', window.dataLayer);
  console.log('DATALAYER', dataLayer);

  if (dataLayer.Test) {
    if (dataLayer.Test.Opp) {
      for (let [key, value] of Object.entries(dataLayer.Test.Opp)) {
        console.log(`${key}: ${value}`);
      }
    }
  }
}
createDiv();
updateDataLayer();

BACKGROUND.JS

document.addEventListener('DOMContentLoaded', function() {
 console.log('DOM loaded');

 chrome.browserAction.onClicked.addListener(function (tab) {
     // for the current tab, inject the "inject.js" file & execute it
    chrome.tabs.executeScript(tab.id, {
        file: 'inject.js',
    });
  })
});

MANIFEST.JS

{
  "manifest_version": 2,

  "name": "Chrome Extension (CRO)",
  "description": "xxx",
  "version": "2.0",
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": false
  },
  "content_scripts": [
        {
      "matches": ["<all_urls>"],
     "css": ["style.css"]
        }
    ],
  "browser_action": {
   "default_icon": "logo.png"
  },
  "permissions": [
   "activeTab"
   ]
}
Reena Verma
  • 1,617
  • 2
  • 20
  • 47
  • To access variables in `window` of the page you need to do it in [page context](/a/9517879). – wOxxOm Jun 05 '20 at 09:38
  • @wOxxOm- so I gotta do something like this: ```var actualCode = '(' + function() { // All code is executed in a local scope. // For example, the following does NOT overwrite the global `alert` method var alert = null; // To overwrite a global variable, prefix `window`: window.alert = null; } + ')();'; var script = document.createElement('script'); script.textContent = actualCode; (document.head||document.documentElement).appendChild(script); script.remove();``` – Reena Verma Jun 05 '20 at 10:14
  • And then something like this: ```document.addEventListener('yourCustomEvent', function (e) { var data = e.detail; console.log('received', data); });``` – Reena Verma Jun 05 '20 at 10:15

0 Answers0