有没有办法通过自定义事件传递附加数据? [英] Is there any way of passing additional data via custom events?

查看:111
本文介绍了有没有办法通过自定义事件传递附加数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在两个自主用户脚本之间传递数据 - 理想的情况是触摸 unsafeWindow 对象 - 我认为使用自定义事件将会是这样。我想到了这样的事情(让我们忽略了这个例子的MSIE模型):

I need to pass data between two autonomic userscripts - ideally w/o touching the unsafeWindow object - and I thought using custom events would be the way to go. I thought of something like this (let us disregard the MSIE model for the purpose of the example):

addEventListener("customEvent", function(e) {
  alert(e.data);
});

var custom = document.createEvent("HTMLEvents");
custom.initEvent("customEvent", true, true);
custom.data = "Some data...";
dispatchEvent(custom);

这在标准的JavaScript环境和一个用户脚本中很好地工作,但是当事件被用户脚本并在其外部或另一个用户脚本内部,数据属性是铬中的 undefined 。我想我可以将传递的数据保存在 sessionStorage 中,但是远远没有实现。任何其他优雅的解决方案,先生们和女士?

This works nicely in the standard javascript environment and within one userscript, but when the event is fired by the userscript and caught outside of it or inside another userscript, the data property is undefined in chromium. I suppose I could just save the passed data in the sessionStorage, but it is far from seamless. Any other elegant solutions, gentlemen and gentlewomen? Perfection need and can be achieved, I can feel it.

推荐答案

是的,您可以使用 MessageEvent CustomEvent

使用示例:

//Listen for the event
window.addEventListener("MyEventType", function(evt) {
    alert(evt.detail);
}, false);

//Dispatch an event
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("MyEventType", true, true, "Any Object Here");
window.dispatchEvent(evt);

这篇关于有没有办法通过自定义事件传递附加数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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