In a chrome extension you can use below to find the active tab in a window
chrome.tabs.query({
currentWindow: true,
active: true,
}
I have a below code which connects to existing browser and get all the pages. I am not able to make out if there is a way for me to know which tab/page is currently the active one and get its url (page.url()
, but which one from the the array to use?)
const puppeteer = require('puppeteer');
debuggerUrl = "http://127.0.0.1:9999/json/version"
const request = require('request');
request(debuggerUrl, function (error, response, body) {
data = JSON.parse(body);
webSocketDebuggerUrl = data["webSocketDebuggerUrl"];
console.log("Connecting to ", webSocketDebuggerUrl);
puppeteer.connect({browserWSEndpoint: webSocketDebuggerUrl}).then(async browser => {
var pages = await browser.pages();
console.log(pages);
console.log(await browser.targets())
await browser.disconnect();
})
});
document.hidden
is now deprecated. But we can use document.visibilityState
note that page
will always refer to the same tab even if you have change to different tab. So you have to change page
to the active tab manually.
const pages = await browser.pages();
// this will return list of active tab (which is pages object in puppeteer)
const visiblePages = pages.filter(async (p) => {
const state = await p.evaluate(() => document.visibilityState);
return state === 'visible';
});
const activeTab = visiblePages[0]; // since there should be only 1 active tab per window
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