JIRA.bind() 在 Greasemonkey 中不起作用

JIRA.bind() is not working in Greasemonkey

正如标题所说,我无法从我的 Greasemonkey 脚本中调用 JIRA.bind(),而且我 运行 不知道为什么要尝试其他方法。

我是 运行 JIRA 6.4.14 和 Firefox 50.1.0 中的 Greasemonkey 3.9。

如果我打开 JIRA 并在 Firefox built-in 控制台中执行此行,它会工作并且在提交内联更改后显示 "GO":

JIRA.bind(JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(e, context, reason){alert("GO");})

因此,我认为将此命令移植到 Greasemonkey 中应该没问题:

unsafeWindow.JIRA.bind(unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(e, context, reason){alert("GO");})

但是当我进行完全相同的内联编辑时,什么也没有发生。 该行本身被执行,我在前后 "alerted" 出现了两个弹出窗口。

我尝试了调用的其他变体,但都没有成功

unsafeWindow.JIRA.bind(unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(e, context, reason){ unsafeWindow.alert("GO");})
unsafeWindow.AJS.$(unsafeWindow.JIRA.bind(unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(e, context, reason){alert("GO");}))
unsafeWindow.JIRA.bind(unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(){ alert("GO");})
// While 'fooBar' is a simple function doing the alert("go")
unsafeWindow.JIRA.bind(unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(){ fooBar })

有谁知道如何使绑定生效?


尝试 exportFunction 没有解决问题:

$(document).ready(function() {

    unsafeWindow.JIRA.bind(unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE, function(e, context, reason){ foobar });

});

function foobar()
{
    alert("GO");
}

exportFunction(foobar, unsafeWindow);

解决方案:

感谢 Brock Adams 和 wOxxOm 的帮助!

这个片段工作正常,打印了消息 "Binding" 和 "Go"。

$(document).ready(function() {

    // Write a log message from inside of the GM script
    anotherMethod("Binding");

    // Bind the exported foobar to the JIRA event
    unsafeWindow.JIRA.bind(
        unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE,
        unsafeWindow.foobar
    );

});

// Implementation of the foobar function
function foobar(e, context, reason)
{
    anotherMethod("Go");
}

// Another method, that will get called from the GM script and the exported foobar
function anotherMethod(msg)
{
    console.log(msg);
}

// Export foobar to the unsafeWindow to make it accessible for JIRA
unsafeWindow.foobar = exportFunction(foobar, unsafeWindow);

参考How to access `window` (Target page) objects when @grant values are set?

.bind() 调用中的所有内容都必须驻留在目标页面范围内,因此您不能像那样使用动态 function () {...} 代码。

像这样绑定你的回调:

function mySaveComplete (e, context, reason) {
    //alert ("GO");
    console.log ("Go");
}
unsafeWindow.mySaveComplete = exportFunction (mySaveComplete, unsafeWindow);

unsafeWindow.JIRA.bind (
    unsafeWindow.JIRA.Events.INLINE_EDIT_SAVE_COMPLETE,
    unsafeWindow.mySaveComplete
);

但是,我无法访问 JIRA 测试平台。在某些情况下,您可能必须注入代码,如链接的答案所述。
在这种情况下,另请参阅:How to call Greasemonkey's GM_ functions from code that must run in the target page scope?