webext-detect-page ![](https://img.shields.io/npm/v/webext-detect-page.svg)
Detects where the current browser extension code is being run. Chrome and Firefox.
Install
You can download the standalone bundle and include it in your manifest.json
.
Or use npm
:
npm install webext-detect-page
import {
isBackgroundPage,
isContentScript,
isOptionsPage
} from 'webext-detect-page';
Usage
import {isBackgroundPage} from 'webext-detect-page';
if (isBackgroundPage()) {
browser.runtime.onMessage.addListener(console.log);
} else if (isContentScript) {
browser.runtime.sendMessage('wow!');
}
API
The functions are only ever evaluated once. This protects from future "invalidated context" errors.Read the note about testing if you're running this code in a tester.
isWebPage()
Returns a boolean
that indicates whether the code is being run on http(s)://
pages (it could be in a content script or regular web context).
isExtensionContext()
Returns a boolean
that indicates whether the code is being run in extension contexts that have access to the chrome API.
isBackgroundPage()
Returns a boolean
that indicates whether the code is being run in a background page.
isContentScript()
Returns a boolean
that indicates whether the code is being run in a content script.
isOptionsPage()
Returns a boolean
that indicates whether the code is being run in an options page. This only works if the current page’s URL matches the one specified in the extension's manifest.json
.
Testing
The calls are automatically cached so, if you're using this in a test environment, import and call this function first to ensure that the environment is "detected" every time:
import {disableWebextDetectPageCache} from 'webext-detect-page';
disableWebextDetectPageCache();
Related
License
MIT © Federico Brigante