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.
Yes, you can use a MessageEvent
or a CustomEvent
.
Example usage:
//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);