seleniumselenium-webdriverpuppeteergoogle-chrome-headlesssymfony-panther

Headless Google Chrome: How to prevent sites to know whether their window is focused or not


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

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

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


Solution

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

    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.

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