我可以使用puppeteer api和node.js设置地理定位(devtools> sensors)

时间:2019-08-15 12:47:26

标签: node.js puppeteer

我需要在devtools>带有木偶API的铬传感器中设置设置地理位置(lat,lng)

如果我将其设置为:

    // enable geolocation
    const context = browser.defaultBrowserContext();
    await context.overridePermissions(url, ['geolocation']);
    // set current location to Tokyo Station
    const client = await page.target().createCDPSession();
    await client.send('Emulation.setGeolocationOverride', {
        latitude: 43.0642,
        longitude: 141.347,
        accuracy: 100
    });

see bottom-right: devtools geolocation

此代码可在页面Navigation.geolocation(但在devtools中除外)中设置地理位置,并且可用于某些网站,例如https://map.ultra-zone.net/g/, 但是,如果我尝试“谷歌搜索”,则结果不正确。 换句话说,如果我在devtools> sensors中手动设置地理位置,那么结果是正确的

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        slowMo: 250,
        devtools: true
    })
    const page = await browser.newPage();
    const url = 'https://map.ultra-zone.net/g/';
    // enable geolocation
    const context = browser.defaultBrowserContext();
    await context.overridePermissions(url, ['geolocation']);
    // set current location to Tokyo Station
    const client = await page.target().createCDPSession();
    await client.send('Emulation.setGeolocationOverride', {
        latitude: 43.0642,
        longitude: 141.347,
        accuracy: 100
    });
    await page.goto(url);
    await page.screenshot({
        path: 'example.png'
    });
    const result = await page.evaluate(() => {
        return new Promise(resolve => {
            navigator.geolocation.getCurrentPosition(position => {
                resolve({ lat: position.coords.latitude, lng: position.coords.longitude });
            });
        });
    });
    console.log(result);

    await browser.close();
})();

有人可以用puppeteer api或通过'userDataDir'launchPuppeteerOptions来描述我如何在devtools>传感器中设置地理位置吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

我在页面加载后设置了await page.setGeolocation({latitude: X, longitude: Y});。最初设置时没有用。