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"
]
}