How to hide everything before page load with Chrome Extension

后端 未结 3 2123
夕颜
夕颜 2021-01-14 22:32

I tried using content scripts

manifest

\"content_scripts\": [
    {
        \"matches\": [\"*://*/*\"],
        \"js\": [\"js/content_sc         


        
3条回答
  •  被撕碎了的回忆
    2021-01-14 23:06

    The existing answers are correct in most cases, but I want to give more context about the implications of the used methods. The recommended method to hide the page until you are ready is:

    manifest.json:

    {
        ...
        "content_scripts": [{
            "matches": ["*://*/*"],
            "js": ["contentscript.js"],
            "run_at": "document_start"
        }],
        ...
    }
    

    contentscript.js

    document.documentElement.style.visibility = 'hidden';
    document.addEventListener('DOMContentLoaded', function() {
        // ... do something ... and then show the document:
        document.documentElement.style.visibility = '';
    });
    

    visibility:hidden vs display:none

    You should not use display = 'none', but visibility = 'hidden', as suggested by Parag Gangli for. The reason for preferring visibility:hidden over display:none is that visibility does not affect any dimensional properties of an element. When an element is set to display:none, then the element and all of its descendant nods will have a width and height of 0. This could break several pages that rely on calculations involving the dimensions of an element in the document tree.

    Another consequence of toggling display:none is that scroll positions and anchors (#id-of-something) are broken. The browser will no longer jump to the anchor or previous scroll position, but show the page at scroll position (0,0). This is highly undesirable.

    document.body vs ... vs document.documentElement

    document.body does not exist when "run_at": "document_start" is set, so it cannot be used. document.getElementsByTagName('html')[0] works, but can more concisely be written as document.documentElement (= the root of the document).

    window.onload vs DOMContentLoaded

    window.onload will only be triggered when all resources (images, frames, etc.) are fully loaded. This can take a while, so it is a bad idea to hide the whole page until the window.onload event is triggered.

    In most cases, your extension only depends on the document structure, so modifying the document and showing the document at the DOMContentLoaded event suffices.

提交回复
热议问题