oddworks blog

How to disable the Page Visibility API: 3 ways, with code

On this page
  1. What a page can see
  2. Option 1: uBlock Origin filters
  3. Option 2: a Tampermonkey userscript
  4. Option 3: an extension
  5. Check that it worked
  6. FAQ

You can't switch the Page Visibility API off in browser settings, but you can lie to the page. Three ways work: uBlock Origin filters that defuse visibilitychange listeners and set document.hidden to false, a userscript that redefines the properties on Document.prototype before the page loads, or an extension that does both plus the timing signals. The filters are quickest, the userscript is the most transparent, and the extension covers the most.

What a page can see

The Page Visibility API is only one of the signals a site uses to tell you left. Blocking one and not the others often isn't enough:

Signal uBO filters Userscript below Focus Spoofer
visibilitychange event yes yes yes
document.hidden, visibilityState yes yes yes
Window blur yes (with elements) yes yes
document.hasFocus() yes yes yes
pagehide no no yes
requestAnimationFrame pause no no yes

The last row matters more than it looks. A paused rAF leaves a gap a page can measure with no events at all. requestAnimationFrame in background tabs shows the code.

Option 1: uBlock Origin filters

uBlock Origin has scriptlets that run in the page before its own scripts. The relevant ones, from the uBO Resources Library:

  • aeld (addEventListener-defuser) blocks calls to addEventListener whose event type matches. The first parameter is the event type (a string or a regex literal), and the optional second parameter narrows it to handlers whose source matches a pattern.
  • set (set-constant) defines a property with a value from a fixed list: false, true, trueFunc and a few others.
  • trusted-set does the same with any value, but runs only from trusted lists, or from your own filters if you allow it.

The filters

Replace example.com with the site:

example.com##+js(aeld, /^(?:visibilitychange|webkitvisibilitychange)$/)
example.com##+js(set, document.hidden, false)
example.com##+js(set, document.hasFocus, trueFunc)
example.com##+js(trusted-set, document.visibilityState, visible)
example.com##+js(aeld, blur, , elements, window)

Line by line:

  1. Drops any visibilitychange listener the page tries to add. The regex is anchored, so it matches those two event names exactly.
  2. Makes document.hidden read false.
  3. Replaces document.hasFocus with a function that returns true.
  4. Makes document.visibilityState read "visible". trusted-set treats the value as a string by default.
  5. Drops blur listeners added to window only. The empty second parameter means "any handler", and the elements token limits defusing to targets matching the selector, which can be window or document. Element-level blur used by forms keeps working.

Add them

  1. Open the uBlock Origin dashboard and go to My filters.
  2. Tick Allow custom filters requiring trust (needed for line 4).
  3. Paste the filters and click Apply changes, then reload the site.

Limits

  • aeld only intercepts addEventListener. A page that assigns document.onvisibilitychange = fn isn't affected, although with lines 2 and 4 in place the handler only ever sees visible.
  • Nothing here touches rAF or pagehide.
  • Full uBlock Origin is a Manifest V2 extension. Chrome has phased MV2 extensions out (uBO's notes on this), so these filters run reliably in uBlock Origin on Firefox. uBlock Origin Lite, the Chrome version, added custom filters more recently and is built around declarative rules. Check whether it accepts the scriptlet lines in your version before relying on them, or use the userscript.

Option 2: a Tampermonkey userscript

A userscript gives you exact control and works in Chrome, Edge, Brave and Firefox. Two header lines do the important work:

  • @run-at document-start runs the script before the page's own scripts, so your definitions are in place before anything reads them.
  • @grant none runs it in the page's own JavaScript context instead of a sandbox, so changes to Document.prototype are the ones the page sees.
// ==UserScript==
// @name         Always visible
// @namespace    https://blog.oddworks.us/
// @version      1.0.0
// @description  Report the page as visible and focused; hide visibilitychange and window blur
// @match        https://example.com/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  const proto = Document.prototype;

  // 1. Redefine the getters on the prototype, not just on `document`.
  //    Then a page reading the original getter, e.g.
  //    Object.getOwnPropertyDescriptor(Document.prototype, 'hidden').get.call(document),
  //    gets the spoofed value too.
  const values = {
    hidden: false,
    visibilityState: 'visible',
    webkitHidden: false,
    webkitVisibilityState: 'visible',
  };

  for (const [name, value] of Object.entries(values)) {
    if (!(name in proto)) continue; // skip prefixed names this browser lacks
    Object.defineProperty(proto, name, {
      get() { return value; },
      configurable: true,
      enumerable: true,
    });
  }

  // 2. Always report focus.
  proto.hasFocus = function hasFocus() { return true; };

  // 3. visibilitychange is fired at document and bubbles, and window is on
  //    its event path. A capturing listener on window, added before the page
  //    runs, sees it first and stops it from reaching any page listener,
  //    including document.onvisibilitychange.
  const stop = (event) => event.stopImmediatePropagation();
  for (const type of ['visibilitychange', 'webkitvisibilitychange']) {
    window.addEventListener(type, stop, true);
  }

  // 4. Stop blur aimed at the window itself. Element blur (form
  //    validation, React onBlur) still passes through.
  window.addEventListener('blur', (event) => {
    if (event.target === window) event.stopImmediatePropagation();
  }, true);
})();

A few notes on why it's written this way:

  • hidden and visibilityState are accessor properties on Document.prototype and they're configurable, so Object.defineProperty can replace them.
  • Blocking events with a capture listener on window handles listeners added with addEventListener and on... handler properties alike, without patching addEventListener itself.
  • The blur filter checks event.target === window. A blanket block would also kill blur on inputs and break forms.

Install it

  1. Install Tampermonkey, click its icon and choose Create a new script.
  2. Replace the template with the script, change the @match line to your site, and save.
  3. In Chrome and other Chromium browsers, Tampermonkey needs permission to run userscripts. Open chrome://extensions, click Details on Tampermonkey and turn on Allow User Scripts. Older browser versions use Developer mode instead (Tampermonkey FAQ).
  4. Reload the site.

Limits

It doesn't keep rAF running, and a page that grabs a clean Document.prototype from a fresh about:blank iframe can still read the real value. For most sites that's not a concern; for the timing gap it is.

Option 3: an extension

Focus Spoofer (which we make) is a free, open-source extension for Chrome, Edge and Brave that does everything in the table above. It keeps document.hidden false and visibilityState "visible", blocks visibilitychange, pagehide and window-level blur and mouseleave, keeps document.hasFocus() true, and keeps requestAnimationFrame and requestVideoFrameCallback firing in hidden tabs. Element-level focus, blur and hover events inside the page keep working.

It's off until you want it. Click the icon to protect the current tab, or mark a site "Always protect". There's no account, and browsing data never leaves the browser. It can also randomize canvas, WebGL and audio fingerprints; that's on by default and you can switch it off.

What it can't do: it doesn't stop Memory Saver or sleeping tabs from discarding a tab, it doesn't run on Firefox, Safari or mobile, and it can't run on chrome:// pages, the Chrome Web Store or the PDF viewer. Get it from the product page or the source on GitHub.

Check that it worked

Whichever option you pick, open the console on the site and paste:

document.addEventListener('visibilitychange', () => {
  console.log('visibilitychange fired:', document.visibilityState);
});
setInterval(() => console.log('hidden =', document.hidden), 2000);

Switch tabs for a few seconds and come back. If the block works, visibilitychange fired never prints and every line reads hidden = false. For the full picture, including focus and rAF gaps, open the Page Visibility API test page or go straight to focus.oddworks.us/test.

FAQ

Can I disable the Page Visibility API in Chrome settings or flags?

No. There's no setting or flag that stops a page reading document.hidden or receiving visibilitychange. You need a filter, a userscript or an extension.

Does the uBlock Origin aeld filter work on its own?

It stops visibilitychange listeners added with addEventListener, which is how most sites listen. Pages that read document.hidden directly or use onvisibilitychange need the set lines too.

Why patch Document.prototype instead of document?

Because the getters live on the prototype. Defining a property only on document leaves the original getter reachable through Document.prototype, and some scripts read it that way.

Will this keep a video playing in a background tab?

It stops the page from pausing it on purpose. It doesn't stop the browser from discarding the tab to save memory. Why videos pause when you switch tabs covers the other causes.

Does blocking blur break forms?

Not if you only block blur on window, as all three options here do. Blur on inputs and other elements keeps firing.

Keep reading

Start with the overview: Page Visibility API explained: document.hidden vs visibilityState