Is there any way of passing additional data via custom events?

JavascriptDomGoogle Chrome-ExtensionDom EventsUserscripts

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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

Solution 3 - Javascript

new CustomEvent is not supported in IE https://caniuse.com/#search=CustomEvent

Here is a version which also works on IE9+:

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

 //Dispatch an event
 var evt = document.createEvent('CustomEvent');
 evt.initCustomEvent('MyEventType', false, false, { test: "Any Object Here" });
 window.dispatchEvent(evt);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWitikoView Question on Stackoverflow
Solution 1 - JavascriptDigital PlaneView Answer on Stackoverflow
Solution 2 - JavascriptAmit GView Answer on Stackoverflow
Solution 3 - JavascriptGeorge ChondrompilasView Answer on Stackoverflow