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.

有帮助吗?

解决方案

Your code will work, you just need to set @run-at document-startDoc, 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:

  1. 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.)

  2. 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.

其他提示

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.

HTML file is parsed row by row. So if your write your < script > just after < html > tag it will be executed before anything else.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top