Your code will work, you just need to set @run-at document-start
Doc, like so:
// ==UserScript==
// @name site blocker
// @match http://www.harmful-website.com/*
// @run-at document-start
// ==/UserScript==
document.write ("<b>You are not allowed to visit this site</b>");
Important:
This will work, for now, on Chrome and with Tampermonkey, but it does not work on other browsers. For example, on Firefox, the
document.write
call will throw the error:Error: The operation is insecure.
(But the page will still be completely blank.)
Although a userscript like this will work (mostly); it is a klugey, brittle, low performance approach and is easily defeated. Here are just a few ways that are better, faster, easier, and harder for savvy kids to kibosh:
- Use your home router's siteblock and/or parental controls. Almost every router and/or modem has this feature, these days.
- Install one of the many extensions that do this kind of blocking.
- Block the site with an Adblock rule.
- Block the site with the machine's hosts file.
- Use a proxy server.
- Search on Super User for more options.