Last active
April 29, 2023 04:22
-
-
Save jhildenbiddle/d43b3dc2ae95e6e049a2c68d84e47920 to your computer and use it in GitHub Desktop.
Chrome Extension (MV3): Read Google Tag Manager dataLayer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"permissions": ["activeTab", "scripting"] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment