Trigger an analytics event from a background chrome extension

I've encountered a challenge with sending an event to Google Analytics from background.js, which is the background script of my Chrome extension.

This is the code snippet I added to my background.js file:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', _AnalyticsCode]);
_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';
  ga.checkProtocolTask = null;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
})();

In addition, I attempted to send this event:

 _gaq.push(['_trackEvent', 'event_send', 'event_label');

However, despite these actions, I cannot view the event on the Analytics dashboard. I've also included the following line in my manifest.json file:

"content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
What steps should I take to successfully execute this from the background?

Answer №1

Here is the code snippet I typically use. It's important to set the checkProtocolTask for a certain extension. Unsure about your usage of _gaq, but it seems like the _gaq.push line may be missing a closing bracket. Additionally, you appear to be utilizing an outdated version of analytics. Refer to this link for more information: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingOverview

    // Generic Google Universal Analytics script
    (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',
    'https://www.google-analytics.com/analytics.js', 'ga');
    ga('create', TRACKING_ID, 'auto');
    ga('set', 'checkProtocolTask', function() { });
    ga('set', 'appName', 'Photo Screensaver');
    ga('set', 'appId', 'photo-screen-saver');
    ga('set', 'appVersion', '<version here>');
    ga('require', 'displayfeatures');

Ensure to include https://www.google-analytics.com in the"content_security_policy" section within your manifest file.

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

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

Prevent a <span> element from affecting the linking functionality of an <a> tag

Is it possible to make a hyperlink clickable without including the <span> tags within it and instead attaching a jQuery event to those tags? This is the code I'm using. It utilizes bootstrap's list-group for a navigation element: <ul cl ...

Jasmine service mocking: provider not found

Having recently started with unit testing, I am currently working on a codebase that includes a js file as follows: app.service("appService", function($http) { this.getData = function(url) { return $http.get(url); } this.foo = function() { ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...

Utilizing Grunt to streamline a personalized project

I have set up Grunt as my "JS Task Runner". Node.js is installed in the directory "C:/Program Files". NPM has been installed in C:/users/Peterson/appdata/roaming/npm. Inside the npm folder, I have Grunt, Bower, and Grunt-cli. I am working on a pro ...

Get binary information without relying on the use of arraybuffer

I have a specific resource that I am utilizing: function _arrayBufferToBase64(buffer) { var binary = ''; var bytes = new Uint8Array(buffer); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String. ...

Take a look at the browser's view

Are there any methods to monitor changes in the browser window using an Observable, such as rxJS or a similar tool? I am interested in triggering an action whenever the browser window is resized. ...

"Unlocking the Power of Material UI withStyles() in React JS: Mixing and Matching Styles for Stunning

I am working with the following code snippets: const styles = theme => ({root: {backgroundColor: '#000000'}) const styles2 = theme => ({root: {backgroundColor: '#fff'}) In my React component, I am using export default compose( ...

What is the method for specifying the content type when generating a signed URL for an object in AWS S3?

I am trying to generate a signed URL with a custom content-type, but I am encountering an issue when attempting the following: s3.getSignedUrl('getObject', {Bucket: AWS_BUCKET_NAME, Key: 'myObjectsKey', ContentType: 'image/png&apos ...

### Setting Default String Values for Columns in TypeORM MigrationsDo you want to know how to

I'm working on setting the default value of a column to 'Canada/Eastern' and making it not nullable. This is the current setup for the column: queryRunner.addColumn('users', new TableColumn({ name: 'timezone_name', ...

Retrieving the request body in AWS Lambda

Within my AWS Lambda function running on NodeJs 8.0 and receiving requests from API Gateway, the code is structured as follows: const mysql = require('mysql'); exports.handler = (event, context, callback) => { console.log("event.body = " ...

Error: Unable to access the 'location' property because it is undefined

Having trouble uploading a product along with an image using AWS S3 (Multer and MulterS3). Every time I try it in Postman, I get the error message "TypeError: Cannot read property 'location' of undefined" specifically pointing to the line where t ...

Prevent unexpected page breaks in <tr> elements on Firefox (Could JavaScript be the solution?)

Wondering if there are any ways, possibly through JavaScript or CSS, to avoid having page breaks within <tr> elements specifically in Firefox. Given that FF does not yet fully support page-break-inside, I assume this might need to be addressed using ...

Hide Rows or Columns automatically in a Table based on the presence of a specific field in a MySQL Database by implementing it

Currently tackling a challenge in my Django project where I need to hide a table row if a specific entity exists in a column in the database. Using a MYSQL database, I am looking to automatically conceal the row without any user interaction. page.html: &l ...

What is the best way to include an image in front of a radio input using the jsonschema-form library?

I am currently utilizing the jsonschema-form library from Mozilla Services and I am seeking a way to include an image before a radio input. Here is an example of what the end result should look like: https://i.sstatic.net/glny8.png The JSONSchema I am w ...

After the form is submitted, attach a div containing the saved record

Once the form is submitted, I'd like to seamlessly add the newly saved record to my existing div that holds all the records. If there's a better method for accomplishing this, please let me know. I'm unsure of the correct approach to achiev ...

Encountering issues with tesseract callbacks in nodejs due to validation errors

I encountered the following error: fs.js:132 throw new ERR_INVALID_CALLBACK(); ^ TypeError [ERR_INVALID_CALLBACK]: Callback must be a function at makeCallback (fs.js:132:11) at Object.fs.unlink (fs.js:1002:14) at /home/bakedpanda/Documents/BTP/ ...

How can you effectively update the content of a Parent component in react-native by communicating with its child component?

In one of my child components, I have included a button for interaction. Now, within my Parent component, I have three of these child components arranged side by side. Whenever any of these child components are clicked/touched, I want to trigger changes ...

Developing a modification function using jQuery looping

In my quest to enhance a form I've developed, I aim to incorporate preferences. To achieve this, I have constructed an array of objects with specific fields as shown below: var userPreferences =[{ base_field:"field1", base_value:"1", preferen ...