Denied the execution of the inline script due to a violation of the CSP by the Chrome extension

We've been working on integrating Google Analytics into our Chrome extension, and here are the steps we've taken:

We updated our manifest.json with the following line:

"Content-Security-Policy": "default-src 'self'; script-src 'nonce-4AEemGb0xJptoIGFP3Nd'",

Then, in our index.html:

<head>

  <meta charset="utf-8">
  <script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'XXXXX', 'auto');
    ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js' nonce="4AEemGb0xJptoIGFP3Nd"></script>

<!-- End Google Analytics -->
</head>

We attempted using hash, nonce, and unsafe inline, but encountered the same error message in all cases:

https://i.sstatic.net/PeUbW.png

At this point, I'm running out of ideas.

Answer №1

Google offers a guide on integrating GA into Chrome extensions:

Setting up the tracking code

The usual Google Analytics tracking code snippet retrieves a file called ga.js from a secure SSL URL when the page is loaded using the https:// protocol. Chrome extensions and applications are required to use the SSL-protected version of ga.js. Chrome's default Content Security Policy prohibits loading ga.js over insecure HTTP. Due to the fact that Chrome extensions are hosted under the chrome-extension:// schema, a slight adjustment is necessary in the tracking snippet to fetch ga.js directly from instead of the default location.

Here is a modified snippet for the asynchronous tracking API (the modification is highlighted):

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = 'https://ssl.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

You will also need to adjust your extension to allow loading the resource by adjusting the default content security policy. The policy definition in your manifest.json file might appear as follows:

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

Below is an example of a popup page (popup.html) that loads the asynchronous tracking code through an external JavaScript file (popup.js) and tracks a single page view:

<!DOCTYPE html>
<html>
  <head>
    ...
    <script src="popup.js"></script>
  </head>
  <body>
    ...
  </body>
</html>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = 'https://ssl.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to dynamically set the maximumSelectionLength in a select2 dropdown?

In my HTML, I have two select elements. One is for multiple selection of items in a dropdown and the other is for adding tags. If the number of selected items is 3, then users should only be allowed to add 3 tags - no more and no less. $(".js-example-b ...

Sending postMessage during the beforeunload event does not work as expected

When postMessage() is triggered within the beforeunload window event in an Ionic 2 browser, I've noticed that the message doesn't make it to the parent. However, if the same message is sent during the unload or load event, it is received successf ...

Redux Persist causes the redux state to become undefined

I recently added redux-persist to my project and now I am facing an issue where all of my Redux states are returning undefined. Previously, all the Redux states were functioning properly. However, after incorporating redux-persist, they are no longer work ...

Unable to adjust metadata titles while utilizing the 'use client' function in Next.js

I have a /demo route in my Next.js 13 application, and it is using the App Router. However, I am facing an issue with changing the title of the page (currently displaying as localhost:3000/demo). The code snippet for this issue is shown below: /demo/page ...

Steps for accessing the files uploaded in a React application

Looking to implement an upload button using material UI that allows users to upload multiple files, with the goal of saving their paths into an array for future use. However, I'm unsure about where these uploaded files are stored. The code snippet be ...

Looping through objects within objects using .map in React can be done by iterating over

This is the information I have export const courses = [ { id: 0, title: "first year", subjects: [ { id: 0, class: "french" }, { id: 1, class: "history" }, { id: 2, class: "geometry" } ...

The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error. Here's the code snippet (./src/utils/secureLocalStorage.js): import SecureStorage from 'secure-web-storage' import ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...

Redirecting CORS in Cordova: A Comprehensive Guide

My Cordova/Phonegap app is encountering an issue while trying to retrieve certain files using AJAX. The specific error message that I receive states: XMLHttpRequest cannot load https://docs.google.com/uc?export=open&id=.... Redirect from 'https ...

Include a fresh attribute in the Interface

How can I include a boolean property isPhotoSelected: boolean = false; in an API interface that I cannot modify? The current interface looks like this: export interface LibraryItem { id: string; photoURL: string; thumbnailURL: string; fi ...

Using JavaScript to eliminate brackets

When a map is clicked, I have a function that retrieves GPS coordinates. However, the result is currently displayed in brackets (). It is necessary to eliminate the brackets. function onClickCallback(event){ var str = event.latLng var Gpps = str / ...

Looking to extract, interpret, and display PDF documents using React?

I'm working on displaying a PDF file from an external URL. My goal is to extract text from the PDF for analysis, and then present a specific section of a page to users in my React application. This will involve cropping the content using coordinates o ...

Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive. <table> <thead> <tr> <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name&apo ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

Steps to forward a restricted user to a specific webpage

I am currently utilizing NextJs and am in the process of creating a redirecting function for users who have been banned or blocked from accessing the DB/session. My attempt at this involved: redirect.js, where I created a custom redirect function. impo ...

Having trouble getting the navigation function to work correctly for my ReactJS image slider

I am looking to create a simple image slider that contains 3 images in an array. I want to be able to navigate through the slider using just one function that can move back and forth between images. If you click "next" on the last image, it should bring ...

The inner workings of JavaScript functions

I am curious about how JavaScript functions are executed and in what order. Let's consider a scenario with the following JavaScript functions: <span id=indicator></span> function BlockOne(){ var textToWrite = document.createTextNode ...

Extracting data from XPath results reveals information beyond just the elements themselves

Having trouble using the getElementsByXPath function in CasperJS to return a specific string from an xpath I determined. Despite my efforts, it seems like the function is only returning data for the entire webpage instead of the desired string. var casper ...