每次打开页面时如何自动触发我的greasemonkey脚本

时间:2013-12-22 13:22:01

标签: javascript greasemonkey userscripts vote-up-buttons

这是我的油脂脚本。我想在每次打开reddit页面时自动触发它。 我想要     function up_vote_all(){       vote_all('向上箭头');     }

在没有我点击菜单项的情况下自动触发每个页面。 感谢

   // ==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');
  }
}

1 个答案:

答案 0 :(得分:-1)

我找到了,我需要在开头插入此命令

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

很容易。