有没有通过自定义事件传递额外数据的方法?

我需要在两个自主用户脚本之间传递数据——理想情况下不需要接触 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 环境和一个用户脚本中可以很好地工作,但是当用户脚本触发事件并在其外部或另一个用户脚本中捕获时,data属性是 Chromium 中的 undefined。我想我可以只保存在 sessionStorage中传递的数据,但它远非无缝。还有别的好办法吗?完美的需求是可以实现的,我能感觉到。

69980 次浏览

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

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