Javascript 在DOM中运行Greasemonkey创建的代码?

Javascript 在DOM中运行Greasemonkey创建的代码?,javascript,jquery,greasemonkey,Javascript,Jquery,Greasemonkey,我对用户脚本一无所知。我编写了一个小程序来添加一个调用javascript函数的链接: ... // @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.3 // ==UserScript== //define functions $k = jQuery.noConflict(); function testFn() { alert("Successful test!");

我对用户脚本一无所知。我编写了一个小程序来添加一个调用javascript函数的链接:

...
// @require     https://ajax.googleapis.com/ajax/libs/jquery/2.1.3
// ==UserScript==  

    //define functions
    $k = jQuery.noConflict();
    function testFn() {
        alert("Successful test!");
    }

    //add a test link to the DOM
    var testLink = "<a href=\"javascript:testFn()\">TEST LINK</a></div>";
    $k("body").prepend(testLink);

    //add custom functions to the DOM
    var scr = document.createElement("script");
    scr.type = "text/javascript";
    scr.textContent = "$k = jQuery.noConflict();\n" + testFn;    
    $k("body").prepend(scr);

    //add jQuery to the DOM
    var jQueryAdd = document.createElement("script");    
    jQueryAdd.type = "text/javascript";
    jQueryAdd.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"; 
    $k("body").prepend(jQueryAdd);
我做了大量的谷歌搜索,从我读到的来看,这应该是可能的。另外,当我简单地将编辑过的页面保存为自己的HTML文件时,链接工作正常。我是否遗漏了一些非常明显的东西


旁注:我还尝试将jQuery源代码放在同一个域上。没有骰子。

您必须附加HTML元素,而不是jQuery对象

$k("body").prepend(jQueryAdd[0]);

由于您已经在使用jQuery,因此更好的方法是将事件侦听器附加到链接

下面是代码的更好实现:

// create a closure and define jQuery as $ inside it
(function($) {

  // create the anchor element, add the `href` attr and a text
  var $testLink = $('<a>', {href: '#0', text: 'click me'});
  // attach an event listener to the generated anchor
  $testLink.on('click', function() {
    alert('hey');
  });
  // append the generated anchor to the body
  $testLink.appendTo('body');

})(jQuery) // calling `(jQuery)` will automatically run this closure
//创建一个闭包,并在其中将jQuery定义为$
(函数($){
//创建锚元素,添加`href`attr和文本
var$testLink=$('',{href:'#0',文本:'单击我'});
//将事件侦听器附加到生成的锚
$testLink.on('click',function()){
警惕(‘嘿’);
});
//将生成的锚点附加到主体
$testLink.appendTo('body');
})(jQuery)//调用`(jQuery)`将自动运行此闭包

如果您查看DOM,它实际上是在那里定义的——由Bleed monkey在第三个代码块中添加。这还不够?更新了我的答案解释了为什么你的代码不起作用。顺便说一句,我建议你使用一种类似于我在解释之后发布的方法。JQueryAddd是一个HTML元素,更容易维护(更快):
var jQueryAdd=document.createElement(“脚本”)还是我完全遗漏了什么?jquery将其元素包装在由jquery自身管理的数组中,使用
[0]
调用它将只选择真正的html元素
$k("body").prepend(jQueryAdd[0]);
// create a closure and define jQuery as $ inside it
(function($) {

  // create the anchor element, add the `href` attr and a text
  var $testLink = $('<a>', {href: '#0', text: 'click me'});
  // attach an event listener to the generated anchor
  $testLink.on('click', function() {
    alert('hey');
  });
  // append the generated anchor to the body
  $testLink.appendTo('body');

})(jQuery) // calling `(jQuery)` will automatically run this closure