سؤال

So, I have some code for postMessage, which apparently works fine, just not the way I want it: On the sending side:

<!DOCTYPE html>
<html>
<body>
<head>
<title>Posting.html</title>
</head>
<button onclick = "reset()">RESET</button>
<script>
// create popup window
var targetOrigin = 'http://www.examplemsg.com';
var myPopup = window.open("http://www.examplemsg.com/destination.html", 'myWindow');

// periodical message sender
var matrix = setInterval(function(){
   var message = 'Hello! The time is: ' + (new Date().getTime());
   console.log('blog local: sending message: ' + message);

   myPopup.postMessage(message, targetOrigin); // send the message & target URI
 }, 6000);

function reset() { clearInterval(matrix);}

// listen to holla back
window.addEventListener('message', function(event){ 

if(event.origin !== 'http://www.examplemsg.com';) return;
console.log('received response: '+event.data);
}, false);
<script></body></html>

And on the receiving side, /destination.html...

<!DOCTYPE html>
<html>
<body>
<head>
<title>Receiving end</title>
</head>
<script>
window.addEventListener('message',function(event) {
console.log('message received: '+event.data);
event.source.postMessage('holla back youngin!',event.origin);
}, false);
</script>
</body>
</html>

When I use another browser, such as Google Chrome, to load /destination.html, then look at Chrome's console (CTRL-Shift-I) it is blank. This makes me think that I am only sending messages to the popup itself, and not to the actual document residing on my website. A similar thing happened when I tried this with iframes. How do I change this?

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

المحلول

Your code can't be correctly executed, you have syntax error in this line:

if(event.origin !== 'http://www.examplemsg.com';) return;

In destination.html you have syntax problem also: Take a look:

<body>
<head>
<title>Receiving end</title>
</head>
<script>

Remove extra semicolon, format your html documents as expected, try again and your example will work as expected

نصائح أخرى

When I use another browser, such as Google Chrome, to load /destination.html

This makes me think that I am only sending messages to the popup itself, and not to the actual document residing on my website.

If you want to modify a document as it exists on the server (and not the one that exists in browser memory after being loaded into a window) then you will need to make an HTTP request to the server and have a server side process make the change.

This typically isn't done by making the change directly, but by storing data in a database and then using a server side process to generate the HTML dynamically when it is requested.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top