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.
Why using custom events. The custom events allow you to decouple the code that you want to execute after another piece of code completes. For example, you can separate the event listeners in a separate script. In addition, you can have multiple event listeners to the same custom event.
Custom events allow us to run the function outside of the script. It is possible to attach events in other file or script and run them. It is possible to attach multiple listeners to the same event.
Custom events can be created in two ways: Using the Event constructor. Using the CustomEvent constructor.
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);
pass object with more details as attributes:
var event = new CustomEvent('build', { detail: { 'detail1': "something", detail2: "something else" }}); function eventHandler(e) { log('detail1: ' + e.detail.detail1); log('detail2: ' + e.detail.detail2); }
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With