使用Firefox扩展中的属性触发自定义事件 [英] Triggering a custom event with attributes from a Firefox extension

查看:142
本文介绍了使用Firefox扩展中的属性触发自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Firefox扩展,可以修改用户正在查看的页面的内容。作为该过程的一部分,扩展需要触发扩展自身添加到页面源的自定义事件。我很难将参数传递给该自定义事件。我在做什么错了?

I have a Firefox extension that modifies the content of the page that the user is looking at. As part of that process the extension needs to trigger a custom event that the extension itself adds to the page source. I am having difficulties passing parameters to that custom event. What am I doing wrong?

将脚本块插入页面的 head 中:

Script block inserted into the head of the page:

document.addEventListener("show-my-overlay", EX_ShowOverlay, false, false, true);

function EX_ShowOverlay(e) {
    alert('Parameter: ' + e.index);
    // ...
}

扩展名中的代码:

var event = content.document.createEvent("Events");
event.initEvent("show-my-overlay", true, true);
event['index'] = 123;
content.document.dispatchEvent(event);

事件已成功触发,但 e.index 是未定义的。

The event gets triggered successfully, but e.index is undefined.

我设法通过在页面上创建一个元素,然后让事件处理程序找到该元素并读取其属性来使其正常工作,但是没有不觉得优雅。我想没有元素。

I managed to get it working by creating an element on the page and then having the event handler find the element and read its attributes, but it didn't feel elegant. I want to do it without the element.

编辑:

我也尝试使用 CustomEvent 触发事件,但会在处理程序中引发异常:

I also tried triggering the event with CustomEvent, but it throws an exception in the handler:

var event = new CustomEvent('show-my-overlay', { detail: { index: 123 } });
content.document.dispatchEvent(event);

function EX_ShowOverlay(e) {
    alert('Parameter: ' + e.detail.index);
    // ...
}




拒绝访问属性'detail'的权限

Permission denied to access property 'detail'


推荐答案

您无法访问 expandos(其他属性跨安全边界在本地原型对象上定义)。在这种情况下,安全边界位于完全特权的chrome(附加)代码和非特权的网站代码之间。

You cannot access "expandos" (additional properties defined on a native prototype object) across security boundaries. The security boundary in this case being between the fully privileged chrome (add-on) code and the non-privileged website code.

因此,您需要使用标准。 CustomEvent 可以,但是您的代码错误。您必须正确调用构造函数或 initCustomEvent()

So you need to pass data using something "standard". The CustomEvent stuff would do, however your code is wrong. You have to call the constructor or initCustomEvent() correctly:

var event = new CustomEvent('show-my-overlay', { detail: { index: 123 } });
content.document.dispatchEvent(event);

另一种替代方法是 postMessage API

Another alternative is the postMessage API.

这篇关于使用Firefox扩展中的属性触发自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆