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

时间:2017-12-05 18:46:46

标签: javascript jquery html5 google-chrome google-chrome-extension

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

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

请注意! 4年前的答案中有一个解决方案,在较新版本的Chrome中不再生效: Spoof or disable the 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浏览器代码?

1 个答案:

答案 0 :(得分:9)

这是我的解决方案:

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

我添加了blur事件,因为我想跳过的视频(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