I'm writing a chrome extension about creating new tab from context menus in an incognito window. I'm using a script like this:
chrome.windows.create({url: "https://google.com", incognito: true});
The script works, but it always pops out a new window when it activates. Is there any way to open a new tab in an existing incognito window?
If you want to create a tab inside an existing window you can use chrome.tabs.create() specifying the windowId of an existing window. To know which one of the open windows is in incognito mode, you can use chrome.windows.getAll() to get an array of currently open windows and iterate through the results until you see one with incognito set to true.
Here's a working example:
chrome.windows.getAll({populate: false, windowTypes: ['normal']}, function(windows) {
for (let w of windows) {
if (w.incognito) {
// Use this window.
chrome.tabs.create({url: "https://google.com", windowId: w.id});
return;
}
}
// No incognito window found, open a new one.
chrome.windows.create({url: "https://google.com", incognito: true});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With