【问题标题】:Calling a tampermonkey function from a link从链接调用 Tampermonkey 函数
【发布时间】:2013-03-18 05:43:31
【问题描述】:

如何从链接中调用 Tampermonkey 函数?

这是我尝试过的。使用 Tampermonkey,我可以插入如下链接:

var aNode = document.createElement('a'); 
var aText = document.createTextNode('will it run');
aNode.appendChild(aText);
aNode.href = 'javascript:runTest();';
document.body.insertBefore(aNode, document.body.firstChild);

function runTest() {
   alert('it ran!');
};

当调用链接时,应该调用函数 runTest()。它不是。而是出现以下错误消息:

Uncaught ReferenceError: runTest is not defined

【问题讨论】:

    标签: javascript function hyperlink call tampermonkey


    【解决方案1】:

    不要那样设置 javascript 处理程序。使用addEventListener(),像这样:

    var aNode   = document.createElement ('a');
    var aText   = document.createTextNode ('will it run');
    aNode.href  = '#';
    aNode.appendChild (aText);
    document.body.insertBefore (aNode, document.body.firstChild);
    
    aNode.addEventListener ("click", runTest, false);
    
    function runTest (zEvent) {
        zEvent.preventDefault ();
        zEvent.stopPropagation ();
    
        alert('it ran!');
    };
    

    【讨论】:

    • 谢谢!这正是我一直在寻找的,除了更简洁的代码。
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    相关资源
    最近更新 更多