无头谷歌浏览器:如何防止网站知道他们的窗口是否被聚焦 [英] Headless Google Chrome: How to prevent sites to know whether their window is focused or not

查看:49
本文介绍了无头谷歌浏览器:如何防止网站知道他们的窗口是否被聚焦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to prevent sites to know if they are visible or not?

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

Perhaps a command line flag? I checked here but I could not find anything suitable https://peter.sh/experiments/chromium-command-line-switches/.

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

I think they use the page visibility API: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

推荐答案

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

If your goal is to fool the visibility API, then inject this piece of script in the related page or frame:

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'));
`);

首先覆盖window.hidden,使其返回false.然后,它会触发 visibilitychange 事件以在页面已经隐藏的情况下通知文档.

It first overwrites window.hidden to make it return false. Then, it fires the visibilitychange event to notify the document in case the page is already hidden.

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

Or to override the API as soon as the document is created:

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});
`);

这篇关于无头谷歌浏览器:如何防止网站知道他们的窗口是否被聚焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆