在加载网页之前显示空白网页

问题描述 投票:0回答:1

我正在尝试使用tampermonkey为其中一个网站创建主题,所以基本上我想从页面中删除所有内容然后将我的自定义HTML添加到页面。但是在我的主题出现之前,实际的网页会显示几秒钟。我想要在我的自定义脚本添加一些自定义HTML之前,网站是完全空白的。

我将以下代码添加到tampermonkey中

// @run-at        document-start

我首先添加了以下代码来清空网页

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

所以我收到了这个错误

VM82 userscript.html:2错误:执行脚本'display none'失败!无法设置null的属性'innerHTML'

为了解决这个问题,我添加了100毫秒的settimeout然后

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

但仍然显示第二个实际网页的眨眼。

javascript greasemonkey tampermonkey
1个回答
1
投票

当脚本在document-start运行时,无法保证正文存在。通常情况正好相反:文档完全为空,只定义了document.documentElement,它是<html>标记的DOM元素。

只需stop the current loading progress并使用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>
`);

请注意,如果站点的CSP特别限制,它可能无法工作。在这种情况下,您将不得不使用可以放松CSP的扩展(或者您可以自己编写这样的扩展)。

© www.soinside.com 2019 - 2024. All rights reserved.