调用dispatchEvent的附加SDK不会将事件从内容脚本发送到页面
我有一个带有 pageMod
的简单 Firefox 扩展(基于附加 SDK)。 pageMod
向页面注入一些脚本,该脚本调用一个函数:
function dispatchEvent(name, data){
try {
data = data || {};
// passing some data through html element
document.getElementById('MyDiv').innerText = JSON.stringify(data);
var evt = document.createEvent('Event');
evt.initEvent(name.toString(), true, true);
if(document.getElementById('MyDiv').dispatchEvent(evt))
console.log("Dispatch event: "+name+" data: "+JSON.stringify(data));
} catch (e) {
console.log("Error:" + e);
}
}
dispatchEvent("MyEvent", {});
在网页上,我有事件侦听器,通过 MyDiv.addEventListener(...)
添加。 问题是注入的脚本不会将任何事件分派到页面。 dispatchEvent
函数返回 true,但没有任何反应。 这是我的 pageMod
代码:
var myMod = pageMod.PageMod({
include: ["http://localhost/mysite/*"],
contentScriptFile: [data.url("js/script.js")],
contentScriptWhen: "end",
onAttach: function onAttach(worker) {
console.log("CS injected");
}
});
如果我通过 Firebug 控制台运行 contentScript
代码,它可以工作,但我需要从 contentScript
分派事件。
PS 我还尝试使用 unsafeWindow.document
而不是 document,并使用 jQuery 事件/事件侦听器,但它也不起作用。
I have simple Firefox extension (based on Add-on SDK) with pageMod
.pageMod
injects some script to a page, which calls one function:
function dispatchEvent(name, data){
try {
data = data || {};
// passing some data through html element
document.getElementById('MyDiv').innerText = JSON.stringify(data);
var evt = document.createEvent('Event');
evt.initEvent(name.toString(), true, true);
if(document.getElementById('MyDiv').dispatchEvent(evt))
console.log("Dispatch event: "+name+" data: "+JSON.stringify(data));
} catch (e) {
console.log("Error:" + e);
}
}
dispatchEvent("MyEvent", {});
On the web page I have event listener, added through MyDiv.addEventListener(...)
.
Problem is the injected script does not dispatch any event to a page. The dispatchEvent
function returns true, but nothing happens.
Here is my pageMod
code:
var myMod = pageMod.PageMod({
include: ["http://localhost/mysite/*"],
contentScriptFile: [data.url("js/script.js")],
contentScriptWhen: "end",
onAttach: function onAttach(worker) {
console.log("CS injected");
}
});
If I run contentScript
code through Firebug console, it works, but I need to dispatch events from contentScript
.
P.S. I also tried to use unsafeWindow.document
instead of document, and use jQuery events/event listeners and it's not working either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我花了一些时间将您的问题转换为测试用例,它对我有用: https ://builder.addons.mozilla.org/addon/1018586/revision/13/
请下次提供完整的测试用例,因为问题往往不在于代码片段你认为确实如此。
I took time to convert your question into a testcase, and it works for me: https://builder.addons.mozilla.org/addon/1018586/revision/13/
Please provide the complete testcase the next time, as the problem often lies not in the piece of code you think it does.