Skip to content

Instantly share code, notes, and snippets.

@jhildenbiddle
Last active April 29, 2023 04:22
Show Gist options
  • Save jhildenbiddle/d43b3dc2ae95e6e049a2c68d84e47920 to your computer and use it in GitHub Desktop.
Save jhildenbiddle/d43b3dc2ae95e6e049a2c68d84e47920 to your computer and use it in GitHub Desktop.
Chrome Extension (MV3): Read Google Tag Manager dataLayer
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
(async () => {
const { action } = request;
const { tab } = sender;
// Get global value(s) from main frame
if (action === 'get-datalayer') {
const injectionResults = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => window.dataLayer,
world: 'MAIN',
});
sendResponse(injectionResults[0].result);
}
})();
// Return true to indicate an async response
return true;
});
(async () => {
// If necessary, await document.readyState, document.visibilityState, etc.
const response = await browser.runtime.sendMessage({
action: 'get-datalayer',
});
console.log('content received a response:', response);
})();
{
"permissions": ["activeTab", "scripting"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment