Frage

On a certain homepage I visit I want to hide all links that I click. My idea was to use a Greasemonkey script like this:

var blocklist = JSON.parse(GM_getValue("blocklist"));
var as = document.getElementsByTagName('a');
var alength = as.length;   
for(var i=0; i<alength; i++) {
    var a = as[i];
    if(blocklist.indexOf(a.href) >= 0) {
        a.style.display='none';
    } else {
        a.setAttribute('onclick', 'alert("HELP"); return true;');
    }
}

Inside the script I can call this, no problem:

blocklist = blocklist.concat('http://someurl');
GM_setValue("blocklist", JSON.stringify(blocklist));

But in the website itself (read where it says alert("HELP");) I cannot call this function because neither the function nor the blocklist do exist.

Is there a way to access the function from the website? (probably not?) Where else could I store the values to get them back on the next load of the website? The firefox browser is set to sanitize on shutdown, so can't use a:visited or similar.

War es hilfreich?

Lösung

  1. Don't try to call GM_ functions from a webpage. (1) It's not directly possible, (2) it's a security risk, (3) it's almost never really necessary.

  2. Never use onclick in a Greasemonkey script (or at all, really). A simple alert("HELP"); return true; might work, but anything more will crash and it's bad form anyway.

  3. Also, if you use querySelectorAll versus getElementsByTagName, you can fine-tune what links you process, EG: document.querySelectorAll ("div.main a.user") -- which would get only those links with the CSS class user that were inside the <div> with the class main.

In this case, use addEventListener (or use jQuery) to handle the links so your script code would become like:

var blocklist = JSON.parse (GM_getValue ("blocklist") );
var targlinks = document.querySelectorAll ('a');
for (var J = targlinks.length - 1;  J >= 0;  --J) {
    var targlink = targlinks[J];

    if (blocklist.indexOf (targlink.href) >= 0) {
        targlink.style.display = 'none';
    } else {
        targlink.addEventListener ('click', virginLinkHandler, false);
    }
}

function virginLinkHandler (zEvent) {
    var newURL  = zEvent.target.href;
    blocklist   = blocklist.concat (newURL);
    GM_setValue ("blocklist", JSON.stringify (blocklist) );
}

Andere Tipps

You should use localStorage so that you can retain your list on subsequent page loads. It's really not too different from GM_setValue.

localStorage.setItem("blocklist", JSON.stringify(blocklist));

var blocklist = JSON.parse(localStorage.getItem("blocklist"));

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top