我已经设置了这样的事件侦听器...
window.addEventListener('message', parseMessage, false);
var parseMessage = function(rawMessage) {
console.log(rawMessage.cmd);
};
然后我像这样触发事件:
var event = new Event('message', {'cmd':"blerg!"});
window.dispatchEvent(event);
问题是当我期望注销“blerg!”时,解析消息中的console.log注销未定义
我在事件中做错了什么,如何将“cmd”消息传递给事件?
CustomEvent
代替 Event
创建自定义事件。
message
也用于postMessage API。在 Chrome 中运行时没有出现问题,但我不会使用它。
var parseMessage = function(rawMessage) {
console.log(rawMessage);
console.log(rawMessage.detail.cmd);
};
// changed event name
window.addEventListener('myMessage', parseMessage, false);
// data should be in a 'detail' object
var evt = new CustomEvent('myMessage', {
detail: {
'cmd' : "blerg!"
}
});
window.dispatchEvent(evt);
这里是针对 IE >= 9 兼容性的调整(使用 和 CustomEvent::initCustomEvent()
):
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent('myMessage', false, false, {
'cmd': "blerg!"
});
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
(function () {
if (
typeof window.CustomEvent === "function" ||
// In Safari, typeof CustomEvent == 'object' but it otherwise works fine
this.CustomEvent.toString().indexOf('CustomEventConstructor')>-1
) { return; }
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
此处也有描述,但 URL 错误: