有没有办法通过自定义事件传递附加数据?
我需要在两个自主用户脚本之间传递数据 - 理想情况下不接触 unsafeWindow
对象 - 而且我认为使用自定义事件是可行的方法。我想到了这样的事情(为了示例的目的,让我们忽略 MSIE 模型):
addEventListener("customEvent", function(e) {
alert(e.data);
});
var custom = document.createEvent("HTMLEvents");
custom.initEvent("customEvent", true, true);
custom.data = "Some data...";
dispatchEvent(custom);
这在标准 Javascript 环境和一个用户脚本内运行良好,但是当事件由用户脚本触发并在其外部捕获时或者在另一个用户脚本中,Chromium 中的 data
属性是 undefined
。我想我可以将传递的数据保存在 sessionStorage
中,但这远非无缝。还有其他优雅的解决方案吗?完美需要并且可以实现,我能感觉到。
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);
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以使用
MessageEvent
或 <代码>自定义事件。用法示例:
Yes, you can use a
MessageEvent
or aCustomEvent
.Example usage:
传递包含更多详细信息作为属性的对象:
https://developer.mozilla .org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
pass object with more details as attributes:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
IE 不支持
新的 CustomEvent
https://caniuse.com/#search=CustomEvent这是一个也适用于 IE9+ 的版本:
new CustomEvent
is not supported in IE https://caniuse.com/#search=CustomEventHere is a version which also works on IE9+: