Reputation:
Is there a way to use an env variable in a background script of a Chrome extension?
I need to conditionally take an action depending on whether we are in development/production environment.
Upvotes: 18
Views: 14298
Reputation: 1
Unlike other environments such as that of NodeJS using a .env file or using the dotenv module, in a chrome extension environment, we can simply achieve this without any permissions using the manifest file itself, like :
{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0",
"background": {
"service_worker": "background.js"
},
"host_permissions": [
"https://www.googleapis.com/*"
],
"action": {
"default_popup": "popup.html"
},
"externally_connectable": {
"matches": ["*://*.yourwebsite.com/*"]
},
"env": {
"API_KEY": "your-api-key",
"ENVIRONMENT": "development"
}
}
and to make use of the variables, you simply add this line of code :
// Accessing environment variables from manifest.json
const apiKey = chrome.runtime.getManifest().env.API_KEY;
console.log('API Key:', apiKey);
I hope this is useful.
Upvotes: -3
Reputation: 5051
You can get the installType
without the need to add management permissions if you use the .getSelf()
method (documentation):
chrome.management.getSelf((self) => {
console.log(self.installType)
})
Upvotes: 6
Reputation: 3050
You can get the ExtensionInstallType of a Chrome Extension which will be one of "admin", "development", "normal", "sideload", or "other."
To do this, first add "permissions": {"management"}
to manifest.json
to enable management.
Then in your background.js
file, add the following code:
chrome.management.get(chrome.runtime.id, function (extensionInfo) {
if (extensionInfo.installType === 'development') {
// perform dev mode action here
}
});
Upvotes: 10