我创建了一个小的命令式香草 JavaScript 脚本来阻止分散注意力的新闻网站,我觉得这是一种类似上瘾的行为:
// ==UserScript==
// @name blocksite
// @match *://*.news_site_1.com/*
// @match *://*.news_site_2.com/*
// ==/UserScript==
function blocksite () {
document.body.innerHTML =`<div dir="ltr"; style="font-size:100px; font-weight: bold; text-align: center">Blocked !</div>`;
}
setTimeout( blocksite(), 1000)
setTimeout( blocksite(), 5000) // Block possible later DOM mutations;
setTimeout( blocksite(), 10000) // Block possible later DOM mutations;
该脚本基本上可以工作(弹出窗口接管 DOM),但我的问题是它只在所有 DOM 内容都被解析和呈现后才阻止站点,而我有兴趣阻止解析。
虽然收听load
事件为时已晚,但收听较早的DOMContentLoaded
事件可能比收听load
或收听更好的结果setTimeout()
,因为阻塞可能在内容被解析后立即发生,而不是呈现。
然而,我需要一种方法来完全阻止解析相关网站的任何网页(或者,在解析第一个 DOM HTML 元素节点后阻止任何进一步的解析)。
我试过的
根据评论,我在 Google Chrome 中尝试过:
window.stop();
我不记得有任何重大变化
window.close();
它仅在 devtool 控制台
window.location.replace("about:blank");
中对我有用 它仅在load
事件完成后才对我有用,而不是在解析开始时
我的问题
我需要的操作是否可以使用最新的 ECMAScript (10) 进行,如果可以,应该使用什么命令?
Sxribe 更新:
亲爱的 Sxribe,我使用以下代码创建了以下文件。
该文件确实由 Tampermonkey 加载(使用正确的@match
列表),但在加载匹配的网站时我没有看到浏览器的变化(这些网站没有被阻止并正常加载)。
文件中的代码
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Tampermonkey 中的文件调用
window.open("C:\Users\MY_USER_NAME\Desktop\blocksite.html");