-3

this is my greasemonkey script. I want to auto-trigger it every time I open a reddit page. I want function up_vote_all() { vote_all('arrow up'); }

to trigger on every page automatically without me click on the menu item. thanks

   // ==UserScript==
// @name          Reddit Mass Vote
// @namespace     http://reddit.com
// @description   You can up vote or down vote all comments on any page instantly without having to click each arrow. This is mainly to be used against spammers and trolls.
// @include       http://www.reddit.com/*
// @include       http://reddit.com/*
// ==/UserScript==


GM_registerMenuCommand('Up Vote All', up_vote_all);


// From http://snipplr.com/view/1696/get-elements-by-class-name/
function getElementsByClassName(classname, node)  {
  if(!node) node = document.getElementsByTagName("body")[0];
  var a = [];
  var re = new RegExp('\\b' + classname + '\\b');
  var els = node.getElementsByTagName("*");
  for(var i=0,j=els.length; i<j; i++)
    if(re.test(els[i].className))a.push(els[i]);
  return a;
}

// From http://jehiah.cz/archive/firing-javascript-events-properly
function fireEvent(element,event){
  if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt);
  }
  else {
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); 
    return !element.dispatchEvent(evt);
  }
}


function up_vote_all() {
  vote_all('arrow up');
}


function vote_all(class_name) {
  arrows = getElementsByClassName(class_name);
  for (var i = 0; i < arrows.length; i++) {
      fireEvent(arrows[i], 'click');
  }
}
SMH_TBZ
  • 103
  • 1
  • 15

1 Answers1

0

i found it, i need to insert this command in the beginning

document.addEventListener("DOMContentLoaded", function() {
  up_vote_all();
});

it was easy.

SMH_TBZ
  • 103
  • 1
  • 15
  • From the GreaseMonkey wiki: "The code in a Greasemonkey user script gets invoked when the DOMContentLoaded event fires (during event capture as of GM 0.8.6). It is a DOM event implemented by Mozilla, similar to window.onload. However, since it waits only for the DOM to load, instead of the entire page (including images, style sheets, and etc.) it happens sooner." In other words, the proposed solution seems to either not help at all or actually prevent anything from executing, since you're basically saying onPageLoaded ( addEventListener("onPageLoad")) - which will never run. – Tomislav Nakic-Alfirevic Apr 13 '16 at 13:59