Reputation: 639
My friend asks me to do this.
He needs to prevent his children from going to certain websites.
He has tamper monkey installed with chrome. I have to make a script in tamper-monkey so that when it reaches the website it will change the web content.
The source code is:
// ==UserScript==
// @name My Fancy New Userscript
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match http://www.harmful-website.com/*
// @copyright 2012+, You
// ==/UserScript==
document.write("<b>You are not allowed to visit this site</b>");
This script works only after the web-site is loaded full. But his children stop the loading of website in the middle and they are able to view a part of it.
Even document.onload=function(){document.write("...");}
works after load. Are there any way to make the script run before the document is loaded i.e. Immediately after the web address is typed on the address bar or hyperlink is clicked.
Upvotes: 1
Views: 208
Reputation: 93643
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:
Upvotes: 1
Reputation: 1881
HTML file is parsed row by row. So if your write your < script > just after < html > tag it will be executed before anything else.
Upvotes: 0
Reputation: 3424
Just call the function right after you define it. Like in the header or somehwere.
However, you need to consider if the function has actually everything it requires, like HTML elements on the page if it access any of them, as those won't necessarily be loaded when calling your function.
Upvotes: 0