سؤال

The following JavaScript code uses the HTML5 postMessage / addEventListener functions to send a message to itself:

window.addEventListener('testMsg', function(event) {
   alert('got a message');   /* Never happens. Why? */
}, false );

window.addEventListener('load', function(event) {
   alert('sending message');    
   window.postMessage('testMsg', '*');
}, false);

A corresponding fiddle:

http://jsfiddle.net/ZGvLg/3/

The message is never received. What is the reason?

هل كانت مفيدة؟

المحلول

I have modified the fiddle. You were listening to the wrong event.

FIDDLE

Should be

window.addEventListener('message', function(event) {
    alert('got a message');   /* Never happens. Why? */
}, false );

window.addEventListener('load', function(event) {
    alert('sending message');    
    window.postMessage('message', '*');
}, false);

نصائح أخرى

You are listening for a testMsg event, but postMessage will trigger a message event.

Like others have said, you need to listen for the "message" event, not "testMsg". Here's a clearer code sample of working code

window.addEventListener('message', function(event) {
    alert('got a message'); // event.data == "hello world"
}, false );

window.addEventListener('load', function(event) {
    alert('sending message');
    window.postMessage('hello world!', '*');
}, false);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top