During the development of a chrome extension you can execute the content of “popup.html” inside the popup, or open the content in a new tab. Sometimes you need to know where the user is, so you can handle different actions for different contexts. How to determine it?
Manifest V3 (recommended)
With the newer Manifest V3 extensions, you can use chrome.action API:
const isInPopup = function() {
return window.location.href === chrome.runtime.getURL('popup.html') &&
window.innerWidth < 800; // popups are typically narrow
}
if(isInPopup()){
// Open the popup content in a new tab
chrome.tabs.create({url: chrome.runtime.getURL('popup.html')});
} else {
// If you are already in the tab, do something else
}
Manifest V2 (legacy)
Note: Manifest V2 is deprecated. Chrome is phasing out support for it. Migrate to Manifest V3 when possible.
This simple function returns true if you are inside the popup otherwise false:
const isInPopup = function() {
return (typeof chrome != undefined && chrome.extension) ?
chrome.extension.getViews({ type: "popup" }).length > 0 : null;
}
if(isInPopup()){
//Open the popup content in a new tab
chrome.tabs.create({url: chrome.extension.getURL('popup.html')});
} else {
//If you are already in the tab, do something else
...
}