简体   繁体   中英

Display blank webpage before webpage loads

I am trying to create theme for one of the website using tampermonkey , So basically I want to remove everything from page and then add my custom HTML to the page.But there is actual webpage is displayed for few seconds before my theme appears.I want the website to be completely blank until my custom scripts adds some custom HTML.

I added following code to tampermonkey

// @run-at        document-start

And I added following code to empty a webpage first

document.body.innerHTML = '';
//my remaining custom codes to add few tables and stuffs

So I got this error

VM82 userscript.html:2 ERROR: Execution of script 'display none' failed! Cannot set property 'innerHTML' of null

To fix this I added settimeout of 100 ms and then

setTimeout(function(){
document.body.innerHTML = '';
}, 50);

But still for blink of a second actual webpage is being shown.

When the script runs at document-start there's no guarantee the body exists. Usually the opposite is expected: the document is completely empty and only document.documentElement is defined which is a DOM element for the <html> tag.

Simply stop the current loading progress and use document.open + document.write:

// ==UserScript==
// @name          blank out
// @match         *://*/*
// @run-at        document-start
// ==/UserScript==

stop();

document.open('text/html', 'replace');
document.write(`
<html>
  <body>foo</body>
</html>
`);

Note that it may not work if the site's CSP is particularly restrictive. In that case you'll have to use an extension that can relax the CSP (or you can write such an extension yourself).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM