Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open new tab in an existing incognito window?

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?

like image 749
Edward Tu Avatar asked Nov 15 '25 04:11

Edward Tu


1 Answers

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});
});
like image 156
Marco Bonelli Avatar answered Nov 17 '25 18:11

Marco Bonelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!