Search code examples
google-chrome-extensionchrome-extension-manifest-v3

How to import jsrsasign module in the background of a Chrome Extension using Manifest V3?


I want to import jsrsasign-all-min.js library to parse JWT tokens after login with Google OAuth2 in the Extension I am developing.

The problem I have is that I am getting the following error:

Uncaught ReferenceError: window is not defined

I supposed this comes up because this library is meant to run in the front-end and the background.js is not exactly that.

This is my manifest.json file:

{
    "manifest_version": 3,
    "name": "Reputation System",
    "version": "1.0.0",
    "key": "xxx",
    "background": {
        "service_worker": "background.js",
        "type": "module"
    },
    "action": {
        "default_title": "Reputation System"
    },
    "permissions": [
        "identity",
        "scripting"
    ],
    "oauth2": {
        "client_id": "xxx",
        "scopes": [
          "openid"
        ]
    }
}

I am importing the library like this in my background.js:

import { KJUR } from "./jsrsasign-all-min.js";

And trying to use this function:

const user_info = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(id_token.split(".")[1]));

What I am doing wrong?


Solution

    1. This library is not a module, it simply declares a bunch of global var, so you can't use the import statement because these variables won't be accessible from outside the script.

    2. This library is not worker-friendly and it mistakenly uses window to access the global namespace.

    Solution:

    1. remove "type": "module" from manifest.json - this will enable importScripts.
    2. change background.js to this:
    self.window = self;
    importScripts('./jsrsasign-all-min.js');
    // now you can use KJUR and other globals vars
    

    Alternative solutions:

    • use a different library that's worker-friendly and can be imported
    • use a build system that allows shimming module globals
    • manually build the library to produce a proper module