I'm trying to add google analytics in a chrome extension and I'm not succeeding.
Most of the guides are for the v2 manifest and the extension I'm working on is v3.
I've already tried copying and pasting the scripts that analytics recommends to me.
I've tried to put the CSP in the manifest but it crashes when using the url in the script-src, I get an unsafe url error.
https://i.stack.imgur.com/NDvi5.png
I've tried copying the entire gtag.js code into a fullScript.js file and calling it through the analytics.js file but it didn't work either.
https://i.stack.imgur.com/ZrlOY.png
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script',chrome.runtime.getURL('fullScript.js'),'ga');
ga('create', 'G-XXXXXXXX', 'auto');
ga('send', 'pageview');
I've already tried using tb button click event script which tb didn't have any reaction.
function trackButton(e) {
_gaq.push(['_trackEvent', e.target.id, 'clicked']);
};
var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', trackButtonClick);
}
I tried to load the scripts from both the manifest and the popup.html and none of them worked:
popup.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TESTE</title>
<script src='analytics.js'></script>
</head>
<body>
<h1>TESTE</h1>
<button id="my-button">TESTE</button>
</body>
</html>
Manifest V3:
{
"manifest_version": 3,
"name": "Hello World",
"description": "Teste",
"version": "1.0",
"action": {
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["/analytics.js"]
}
],
"web_accessible_resources": [
{
"resources": ["analytics.js"],
"matches": ["<all_urls>"]
},
{
"resources": ["fullScript.js"],
"matches": ["<all_urls>"]
}
],
"content_security_policy": {
"extension_pages": "script-src 'self' https://www.googletagmanager.com/gtag/js; object-src 'self'; script-src-elem 'self'"
},
"permissions":["tabs", "scripting"]
}