I use this script to block access to a one or more websites with vanilla JavaScript. I find that it helps me avoid some addictive news websites that make me depressed. (Credit to Marat Tanalin for helping me with the event handling.)
The script is aimed to be an all vanilla JavaScript imperative small script for personal usage, hence it's not modular (there isn't a HTML/CSS/JS file distribution on purpose).
To use the script please change news_website_1.com
to a given news website you hate.
My personal main problem with the script is that it doesn't block websites right away or almost right away such as happens with BlockSite Google Chrome extension:
For example, the script first loads a website, then about 5 seconds pass, then it gets blocked; for some reason, listening to the sooner DOMContentLoaded
event sometimes works and sometimes doesn't and a reviewed version might show an improvement in that point.
How would you revise this script?
// ==UserScript==
// @name New Userscript
// @match *
// ==/UserScript==
window.addEventListener('load', ()=> {
let sitesToBlock = [
'news_website_1.com'
];
let regexToMatchTLD = /\..+/;
let href = window.location.href;
for (let i = 0; i < sitesToBlock.length; i++) {
if (href.includes(sitesToBlock[i])) {
let domain = sitesToBlock[i].replace(regexToMatchTLD, '');
document.body.innerHTML =`
<div style="direction: ltr; position: fixed; top: 0; z-index: 999999; display: block; width: 100%; height: 100%; background: red">
<p style="position: relative; top: 40%; display: block; font-size: 66px; font-weight: bold; color: #fff; margin: 0 auto; text-align: center">
The website ${domain} successfully blocked !
</p>
</div>
`;
}
}
}, false);