0

I really want to share constants with all my js files, background_serviceworker.js and popup.js.

const EXTENSION_MODE = {
    SEARCH_ONLY: "searchOnly",
    FILTER: "filter",
    OFF: "off"
}

Just putting vars in the background_serviceworker.js and using getBackgroundPage() seems a bit messy to me (can make the background file very big).

Yam Shargil
  • 445
  • 5
  • 9

1 Answers1

1

I created constants.js.

// constants.js
var EXTENSION_MODE = Object.freeze({
    SEARCH_ONLY: "searchOnly",
    FILTER: "filter",
    OFF: "off"
})

Inject it to the background-service-worker file (using an answer from here Service worker registration failed. Chrome extension to actually see the errors from the injected script. Without, you only see very general error)

// background.js
try { importScripts("constants.js"); } catch (e) { console.error(e); }

Now popup.js still don't have access to that, because it runs in isolated contexed. So I Also injected it to the popup.html (In the good old fashion way).

 <!-- popup.html -->
<body>
    <some-other-elements/>
    <script src="./constants.js"></script>
    <script src="./popup.js"></script>
</body>

And I can use it in popup.js

// popup.js
console.log("popup: " + EXTENSION_MODE.FILTER);

PS. on content scripts (injected using the chrome.scripting.executeScript), we won't use it. There we need to start using Storage and Messaging https://developer.chrome.com/docs/extensions/reference/storage/ https://developer.chrome.com/docs/extensions/mv3/messaging/

Yam Shargil
  • 445
  • 5
  • 9