Chrome扩展程序:如何禁用页面可见性API

我正在编写一个Chrome扩展程序,需要阻止网页触发文档可见性更改事件。 至少我需要能够覆盖document.visibilityState(即使它是一个只读属性)。 如果不可能,因为此扩展程序仅用于我的目的而不会在Chrome扩展程序商店中,是否有一种方法可以配置我的Chrome浏览器以达到我想要的效果? 我只需要在Chrome“开发者模式”启用时使用此扩展程序,而不是其他时间。

我希望有人能想出一种创造性的方法来实现这一目标。 谢谢。

请注意! 4年前的答案中有一个解决方案,在较新版本的Chrome中不再生效: 欺骗或禁用Page Visibility API

自己测试一下:

// This codes worked 4 years ago but not anymore var c='(function(){var a=Node.prototype.addEventListener;Node.prototype.addEventListener=function(e){if(e=="visibilitychange"||e=="webkitvisibilitychange"){}else a.apply(this,arguments)}})()' , E=document.documentElement; E.setAttribute('onreset', c); E.dispatchEvent(new CustomEvent('reset')); E.removeAttribute('onreset'); // THIS WILL STILL LOG THE STATES EVEN WITH THE ABOVE CODE RUNNING document.addEventListener("visibilitychange", function() { console.log( document.visibilityState ); }); 

如果在Chrome中无法实现,那么Firefox / Safari / Opera浏览器代码是否可以实现这一目标?

这是我的解决方案:

 for (event_name of ["visibilitychange", "webkitvisibilitychange", "blur"]) { window.addEventListener(event_name, function(event) { event.stopImmediatePropagation(); }, true); } 

我添加了blur事件,因为我想跳过的video(everfi.net)使用它来检测我何时切换窗口。 阻止该事件以及visibilitychangewebkitvisibilitychange做了诀窍:)

我还修改了扩展程序的清单,以便它可以在iframe中运行。

完整代码(chrome扩展名): https : //github.com/NavinF/dont

确认使用以下狗牌:

 Google Chrome 63.0.3239.132 (Official Build) (64-bit) Revision 2e6edcfee630baa3775f37cb11796b1603a64360-refs/branch-heads/3239@{#709} OS Mac OS X JavaScript V8 6.3.292.49 Command Line /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --flag-switches-begin --flag-switches-end