How to obtain the tab ID when Puppeteer creates a new tab?

I’m working on a project that involves testing Chrome extensions. I need to find out the tab ID when a new tab is opened. Here’s what I’ve tried so far:

const browser = await launchBrowser({ /* options */ });

const mainPage = await browser.createNewTab();
await mainPage.navigate(websiteUrl, { waitFor: 'pageLoad' });

// How do I get the tab ID here?

I’ve looked through the Puppeteer docs for the Page object, but couldn’t find anything about tab IDs. Is there a way to get this information using Puppeteer? Any help would be great!

As someone who’s worked extensively with Puppeteer for browser automation and testing, I can share a workaround I’ve used to get the tab ID. While Puppeteer doesn’t directly expose the tab ID, you can use the Chrome DevTools Protocol (CDP) to retrieve it.

Here’s what I’ve found to work:

const target = mainPage.target();
const cdpSession = await target.createCDPSession();
const {targetInfo} = await cdpSession.send('Target.getTargetInfo');
const tabId = targetInfo.tabId;

This method leverages the CDP to get the target info, which includes the tab ID. It’s not the most straightforward approach, but it’s reliable in my experience. Just remember to close the CDP session when you’re done to avoid memory leaks.

Hope this helps with your Chrome extension testing project!

hey mate, i’ve dealt with this before. try using the _target property of the Page object. it’s not official but works:

const tabId = mainPage._target._targetId;

just remember this might change in future puppeteer versions. good luck with ur extension testing!

While Puppeteer doesn’t provide direct access to tab IDs, there’s a method I’ve found effective for this situation. You can utilize the _client property of the Page object, which gives you access to the underlying CDP (Chrome DevTools Protocol) client.

Here’s a code snippet that should work:

const tabId = await mainPage.evaluate(() => window.chrome.tabs.getCurrent(tab => tab.id));

This approach injects a script into the page to use the Chrome extension API, which can retrieve the current tab’s ID. It’s worth noting that this method assumes you’re working in the context of a Chrome extension. If you’re not, you might need to adjust your approach or consider using a different method to identify tabs.

Nothing from here seems to work for me, because everything seems to be using that mainPage’s type:

const mainPage = await browser.createNewTab();

By the way, that createNewTab() function does not exist. Puppeteer uses newPage() method on the docs.

target() as of now is also deprecated

What works is running:

const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});

inside the browser context with mainPage.evaluate()