Version:

Use JavaScript SDK in Chrome Extensions


You can use the JavaScript SDK in Chrome extensions with the manifest v3 as:

See the JavaScript SDK GitHub repository for more information.

Background script

You can use the RudderStack service worker NPM package as a background script.

To do so, place it in your Chrome extension resources by following either of these approaches:

  • Copy the file from node_modules and place it as a part of resources.
  • Use a JS bundler and bundle it as a part of your service worker script.
warning

You need to enable relevant permissions in the manifest file according to the required capabilities and allowed connections.

Also, setting the background script type as a module is recommended, as it allows to import the script as ESM.

"permissions": ["storage", "tabs"],
"host_permissions": [
    "https://*.dataplane.rudderstack.com/*",
    "https://*.rudderlabs.com/*",
    "*://*/*"
],
"externally_connectable": {
    "matches": [
        "https://*.dataplane.rudderstack.com/*",
        "https://*.rudderlabs.com/*"
    ]
},
"background": {
    "service_worker": "service-worker.js",
    "type": "module"
},

Then, follow the Node.js SDK documentation for further usage as the API is identical to it.

See the sample application for more information on using the service worker NPM package as a background script.

Content script

To use the JavaScript SDK as a content script, place it in your Chrome extension resources by following either of these approaches:

  • Copy the index.js file from the node_modules folder after installing the package (node_modules/@rudderstack/analytics-js/dist/npm/modern/cjs/index.js) and place it as a part of the resources.
info

You can use the cjs bundle from legacy folder (node_modules/@rudderstack/analytics-js/dist/npm/legacy/cjs/index.js) as well, depending on your requirement.

Note that the modern folder is targeted for browsers that support the modern JavaScript syntax, especially dynamic imports, whereas the legacy folder is meant for the rest of the browsers.

  • Use a JS bundler and bundle it as part of your content script.
warning
You need to enable relevant permissions in the manifest file according to the required capabilities and allowed connections.
"permissions": ["storage", "tabs"],
"host_permissions": [
  "https://*.dataplane.rudderstack.com/*",
  "https://*.rudderlabs.com/*",
  "*://*/*"
],
"externally_connectable": {
  "matches": [
    "https://*.dataplane.rudderstack.com/*",
    "https://*.rudderlabs.com/*"
]},
"content_scripts": [{
  "js": ["foreground.js"],
  "matches": ["https://github.com/*"]
}]

Then, follow the SDK documentation for further usage.

You can also react to events available in both the content and background scripts by leveraging the Chrome API.

The following sample scripts help you track any URL changes:

See the sample application for more information on using the SDK as a content script.



Questions? Contact us by email or on Slack