Working on library, which executes differently in different contexts/pages i.e Popup, Options, Devtools, ContentScript & Windows for which we need to know which context the library is running in and execute accordinly.
So, something like this :..
const isOptionsPage = checkForOptionsPage();
const isPopupPage = checkForPopupPage();
const isContentScript = checkForContentScript();
const isDevtools = checkForDevtools();
function myLibrary() {
if (isOptionsPage) {
// execute code for options page
//
//
} else if (isPopupPage) {
// execute code for Popup page
//
//
} else if (isContentScript) {
// execute code for Content Script
//
//
} else if (isDevtools) {
// execute code for Devtools page
//
//
}
// Common Execution
}
You'll have to infer from availability of chrome
properties and compare location.href
to the values in manifest.json.
const m = chrome.runtime.getManifest();
const isContentScript = !!(!chrome.tabs && chrome.extension && chrome.runtime.getURL);
const isOffscreen = !!(!chrome.tabs && !chrome.extension && chrome.runtime.getURL);
const isOptionsPage = !!chrome.tabs &&
location.href === chrome.runtime.getURL(m.options_page || m.options_ui?.page || '');
// this will be wrong when using chrome.action.setPopup with a different path
const isPopupPage = !!chrome.tabs &&
location.href === chrome.runtime.getURL((m.action || m.browser_action)?.default_popup);
const isDevtools = !!chrome.devtools;