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

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

问题描述

我需要在两个自主用户脚本之间传递数据 - 理想情况下不接触 unsafeWindow 对象 - 我认为使用自定义事件将是可行的方法.我想到了这样的事情(让我们为了示例的目的而忽略 MSIE 模型):

I need to pass data between two autonomic user scripts - ideally without 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 环境和一个用户脚本中运行良好,但是当事件由用户脚本触发并在其外部或另一个用户脚本内部捕获时,data 属性为 未定义.我想我可以将传递的数据保存在 sessionStorage 中,但这远非无缝.还有其他优雅的解决方案吗?完美需要并且可以实现,我能感觉到.

This works nicely in the standard Javascript environment and within one user script, but when the event is fired by the user script and caught outside of it or inside another user script, 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? Perfection need and can be achieved, I can feel it.

推荐答案

是的,您可以使用 MessageEventCustomEvent.

Yes, you can use a MessageEvent or a CustomEvent.

示例用法:

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

//Dispatch an event
var evt = new CustomEvent("MyEventType", {detail: "Any Object Here"});
window.dispatchEvent(evt);

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

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