Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer chrome get active/visible tab

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();
  })
});
like image 285
Tarun Lalwani Avatar asked Jun 26 '18 09:06

Tarun Lalwani


1 Answers

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
like image 110
Alexander Dischberg Avatar answered Sep 26 '22 02:09

Alexander Dischberg