【问题标题】:How to set, change or block timezone(systemtime) with Puppeteer?如何使用 Puppeteer 设置、更改或阻止时区(系统时间)?
【发布时间】:2023-11-22 10:59:02
【问题描述】:
  • 操作系统:基于 Windows 10 Pro x64 的 PC
  • 节点-v:v8.12.0
  • npm list puppeteer: `-- puppeteer@1.9.0

我试过这个:

puppeteer.launch({
  env: {
    TZ: 'Australia/Melbourne',
    ...process.env
  }
});

不要为我工作。 whoer.net 看到我的实际系统时间。

编辑:关于https://github.com/nodejs/node/issues/4230的一些信息

此代码在 Linux 上运行良好,但在 Windows 上无法运行:

process.env.TZ = 'UTC';

console.log(new Date());

在 Windows 上,我从我的操作系统中看到时区。

【问题讨论】:

标签: javascript node.js google-chrome google-chrome-devtools puppeteer


【解决方案1】:

根据Puppeteer documentation,可以使用page.emulateTimezone()

page.emulateTimezone()

timezoneId string> 更改页面的时区。有关支持的时区 ID 列表,请参阅 ICU’s metaZones.txt。传递 null 会禁用时区模拟。

返回:Promise>

例如:

await page.emulateTimezone('America/Chicago');

【讨论】:

  • 如何将它与打字稿一起使用?我无法使用此功能
【解决方案2】:

要为所有网站隐藏该信息,您必须使用不同设置的组合。这不仅限于,

  • 代理
  • 位置
  • 时区
  • WebRTC 泄漏

因为每个网站都有自己的查找方法。只是更改时区并不意味着网站会认为您来自其他地方。

但是,以下代码对我来说非常有效。

const puppeteer = require('puppeteer');

async function timeZoneChecker({ timeZone }) {
  // all kind of config to pass to browser
  const launchConfig = {};

  if (timeZone) {
    launchConfig.env = {
      TZ: timeZone,
      ...process.env,
    };
  }
  const browser = await puppeteer.launch(launchConfig);
  const page = await browser.newPage();

  await page.goto('https://whoer.net/');
  const detectedTimezone = await page.$eval('.ico-timesystem', e => e.parentNode.innerText);
  await page.screenshot({ path: `screenshots/timeZone_${timeZone.replace('/', '-')}.png`, fullPage: true });

  await browser.close();

  return { timeZone, detectedTimezone };
}

Promise.all([
  timeZoneChecker({ timeZone: 'Australia/Melbourne' }),
  timeZoneChecker({ timeZone: 'Asia/Singapore' }),
]).then(console.log);

结果:

➜  change-timezone node app/timezone.js
[ { timeZone: 'Australia/Melbourne',
    detectedTimezone: 'Sun Oct 28 2018 22:44:35 GMT+1100 (Australian Eastern Daylight Time)' },
  { timeZone: 'Asia/Singapore',
    detectedTimezone: 'Sun Oct 28 2018 19:44:36 GMT+0800 (Singapore Standard Time)' } ]

【讨论】:

  • 谢谢!但它不起作用。 Mayby 因为我的操作系统是 Win 10?我找到了一些关于问题 github.com/nodejs/node/issues/4230 的信息,但它仍然开放 =( 抱歉,我的问题再次没有提供足够的细节。
最近更新 更多