Tamper monkey script not running jquery

时间:2018-03-09 19:06:18

标签: javascript jquery tampermonkey

I am trying to execute a script with tamper monkey which adds an icon and does the task of opening all the links within a web page on click and here is the source for the script https://gist.github.com/jameshibbard/3831983#file-gistfile1-js .

The icon gets added on the page on enabling the script but clicking on the link does not work.

I figured out that it may be related to jquery compatibility issues and tried below changes in loading jquery

// ==UserScript==
// @name       Open CodeProject Links
// @namespace  http://hibbard.eu/
// @version    0.1
// @description  Opens all of the links from the CodeProject newsletter in one go
// @match *://www.codeproject.com/script/Mailouts/*
// @copyright  2012+, hibbard.eu
// @require https://code.jquery.com/jquery-latest.js
// @grant GM_log
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.
// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
    var script = document.createElement("script");
    script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
    script.addEventListener('load', function() {
        var script = document.createElement("script");
        script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
        document.body.appendChild(script);
    }, false);
    document.body.appendChild(script);
}
function main(){
$(document).ready(function() {
  //var my_jquery = jQuery;
  //jQuery.noConflict(true);
  //var $ = my_jquery, jQuery = my_jquery;
  var hrefs = new Array();
  var elements = $('.headline > a');
  elements.each(function() {
    hrefs.push($(this).attr('href'));
  });

  $('body').append('<input type="button" value="Open Links" id="CP">');
  $("#CP").css("position", "fixed").css("top", 0).css("left", 0);
  $('#CP').click(function(){
    $.each(hrefs, function(index, value) {
      setTimeout(function(){
       window.open(value, '_blank');
      },1000);
    });
  });
});
}
// load jQuery and execute the main function
addJQuery(main);

But this also does not work. Can someone help me solving issue with executing the button click with tamper monkey ?

1 个答案:

答案 0 :(得分:1)

这是因为没有为输入元素的css定义z-index元素,因为输入按钮被div覆盖并使其无法点击

以下是工作代码

$(document).ready(function() {
var hrefs = new Array();
var elements = $('.headline > a');
elements.each(function() {
hrefs.push($(this).attr('href'));
});
$('body').append('<input type="button" value="Open Links" id="CP">');
$("#CP").css("position", "fixed").css("top", 0).css("left", 0).css("z-index", 1000);
$('#CP').click(function(){
$.each(hrefs, function(index, value) {
setTimeout(function(){
window.open(value, '_blank');
},1000);
});
});
});