简体   繁体   中英

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?

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});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM