javascriptpuppeteer

Puppeteer: Close geolocation permission request


How do I use Puppeteer to close Chrome's geolocation permission request? I've placed page.on everywhere, and tried using confirm, dialog, alert and prompt. I've also read the following links, but couldn't find a solution:

My script:

console.log("\nProcess Started");
//sample webpage
let webPage = "https://www.mta.org.nz/find-an-mta/?location=us";

const puppeteer = require("puppeteer");

async function main() {
  const browser = await puppeteer.launch({
    headless: false
  });
  const page = await browser.newPage();
  await page.setViewport({
    width: 1600,
    height: 900
  });

  try {
    await page.goto(webPage);
    await page.waitForSelector("body");
    await console.log("Loaded: " + webPage);
  } catch (err) {
    console.log("Error: " + webPage + "\n" + err);
  }

  await page.waitFor(10000);

  browser.close();
  await console.log("Process Ended \n");
};
main();

Solution

  • The Puppeteer API (v1.5.0) currently does not support catching permission requests (which would've allowed granting/denying the geolocation permission), but as a workaround, you could patch navigator.geolocation in page.evaluateOnNewDocument():

    await page.evaluateOnNewDocument(function() {
      navigator.geolocation.getCurrentPosition = function (cb) {
        setTimeout(() => {
          cb({
            'coords': {
              accuracy: 21,
              altitude: null,
              altitudeAccuracy: null,
              heading: null,
              latitude: 23.129163,
              longitude: 113.264435,
              speed: null
            }
          })
        }, 1000)
      }
    });
    
    await page.goto('https://www.mta.org.nz/find-an-mta/?location=us')
    

    demo