运行Greasemonkey在DOM中创建代码

running Greasemonkey-created code in DOM?

本文关键字:创建 代码 DOM Greasemonkey 运行      更新时间:2023-09-26

我对用户脚本完全陌生。我写了一个小的,用来添加一个调用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);

脚本按预期填充我的DOM:

<script type="text/javascript">
    $k = jQuery.noConflict();
    function testFn() {
        alert("Testing");
    }
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<a href="javascript:testFn()">TEST LINK</a>

但是,每当我点击测试链接时,该函数都不会执行,控制台会抛出一个错误:

ReferenceError: testFn is not defined

我在谷歌上搜索了很多,从我读到的内容来看,这应该是可能的。另外,当我简单地将编辑后的页面保存为自己的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