Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  97] [ 2]  / answers: 1 / hits: 75631  / 13 Years ago, thu, february 23, 2012, 12:00:00

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.


More From » dom

 Answers
346

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

[#87261] Wednesday, February 22, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;