无头谷歌浏览器:如何阻止网站知道其窗口是否聚焦

Wes*_*Wes 6 selenium selenium-webdriver google-chrome-headless puppeteer symfony-panther

有没有办法阻止网站知道它们是否可见?

也许是命令行标志?我在这里检查过,但找不到任何合适的https://peter.sh/experiments/chromium-command-line-switches/

我认为他们使用页面可见性 API:https ://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

Flo*_* B. 6

如果您的目标是欺骗可见性 API,请在相关页面或框架中注入这段脚本:

await page.evaluate(`
    Object.defineProperty(window.document,'hidden',{get:function(){return false;},configurable:true});
    Object.defineProperty(window.document,'visibilityState',{get:function(){return 'visible';},configurable:true});
    window.document.dispatchEvent(new Event('visibilitychange'));
`);
Run Code Online (Sandbox Code Playgroud)

它首先进行覆盖window.hidden以使其返回false。然后,visibilitychange如果页面已隐藏,它会触发事件来通知文档。

或者在创建文档后立即覆盖 API:

await page.evaluateOnNewDocument(`
    Object.defineProperty(window.document,'hidden',{get:function(){return false;},configurable:true});
    Object.defineProperty(window.document,'visibilityState',{get:function(){return 'visible';},configurable:true});
`);
Run Code Online (Sandbox Code Playgroud)