从我的 greasemonkey 脚本中监听一个事件

Listening to an event from my greasemonkey script

我正在尝试找出如何从我的 greasemonkey 脚本中监听事件发射器,但我不断收到访问冲突错误 (Permission denied to access object)。

页数
该页面包含一个简单的事件发射器:

var emitter = function(){
    this.events = {};
}

emitter.prototype.on = function(eventName, closure){
    this.events[eventName] = this.events[eventName] || [];
    this.events[eventName].push(closure);
};

emitter.prototype.emit = function(eventName, data){
    if(this.events[eventName]){
        this.events[eventName].forEach(function(fn){
            return fn(data);
        });
    }
}

var test = new emitter();
test.emit('test', {data:'test'});

脚本
这会引发访问冲突错误(这曾经在一段时间前工作过,但我猜它已被修补或发生了什么):

unsafeWindow.test.on('test', function(data){
    console.log(data);
});

我设法让它工作了。解决方案是通过 exportFunction(myFunction, unsafeWindow)

将回调函数导出到不安全的上下文中

脚本部分应该是这样的:

unsafeWindow.test.on('test', exportFunction(function(data){
   console.log(data);
}, unsafeWindow));

非常感谢 wOxxOm 指出这一点。