'Add google analytics into a chrome extension using manifest v3

Is it possible to add google analytics into a chrome extension using manifest v3 ? How can i do that ?

I found this post from stackoverflow : Add Google Analytics to a Chrome Extension so i tried the code into the accepted answer, with

"content_security_policy": {
   "extension_pages": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'"
}

into my manifest.json, but when i load my extension i got this error : 'content_security_policy.extension_pages': Insecure CSP value "https://ssl.google-analytics.com" in directive 'script-src'.

I feel like it's not possible to use google analytics with chrome extension right now, but it's weird because into the chrome web store dashboard, we can see this field : https://imgur.com/a/PBHGOvu

Did i miss something ?



Solution 1:[1]

I used this way to add google analytics to override.html(chrome_url_overrides) or popup.html in manifest V3:

override.html:

<head>

  // 1- Download from 'https://ssl.google-analytics.com/ga.js' and use locally
  <script src="./ga.js"></script>

  // 2- Instead of use 'content_security_policy' property in 'manifest.json' add this:
  <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-eval' http://www.google-analytics.com https://example.com ;style-src 'self' 'unsafe-inline' http://www.google-analytics.com https://example.com; media-src *;img-src *">
  // or
  <meta http-equiv="Content-Security-Policy" content="default-src *;img-src * 'self' data: https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' *;style-src  'self' 'unsafe-inline' *">

</head>

3- Create analytics-override.js:

var _gaq = _gaq || [];
_gaq.push(["_setAccount", "UA-01234567-89"]);
_gaq.push(["_trackPageview", "/override.html"]);

4- In override.js:

window.onload = function(){    
    const scriptTag = document.createElement("script");
    scriptTag.src = chrome.runtime.getURL("./analytics-override.js");
    scriptTag.type = "text/javascript";
    document.head.appendChild(scriptTag);
}

I hope it helps you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1