I have this chrome extension with a browser_action button. When this browser action is clicked, the background script opens a popup as follows
const popup = window.open('popup.html', tab.id, 'menubar=0,innerWidth=900,innerHeight=800');
When the user clicks the browser action multiple times, the popup is recreated each time (I don't get multiple popup windows)
However, now I would like to replace this code with browser.windows.create which as far as I know, is more the extension-way. So I created
browser.windows.create({url: 'popup.html', height: 800, width: 900, type: 'popup'});
This works almost identical, except, when the user clicks the browser action button multiple times I get multiple popup windows, which is not what I want. Is there a way to get same behaviour as `window.open?
Here's my suggestion (in typescript):
function findTab(tab: chrome.tabs.Tab) {
return tab.url == "popup.html";
}
// first get all open chrome windows
let windows = await chrome.windows.getAll({populate: true, windowTypes: ["popup"]});
// find a window that has a tab with the url "popup.html"
let myWindow = windows.find(window => window.tabs.some(tab => findTab(tab)));
// find a tab that has the url "popup.html"
let myTab = myWindow?.tabs.find(tab => findTab(tab));
if (myWindow && myTab) {
// if such tab exists, focus the parent window and the tab
await chrome.windows.update(myWindow.id, {focused: true});
await chrome.tabs.update(myTab.id, {active: true});
}
else {
// open the window and the tab
await chrome.windows.create({url: "popup.html", type: "popup"});
}