Does Postmessage work between individual web pages under the same domain? If so, how?

StackOverflow https://stackoverflow.com/questions/20769445

  •  21-09-2022
  •  | 
  •  

سؤال

In my code, I have this:

<script>
var iframe = document.getElementById("some_iframe").contentWindow; //sending part
iframe.postMessage("X", 'http?://example.com');
</script>

On the receiving page, I have

<script>
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) { alert(e.data); } // no security concerns here, just the message is needed
</script>

When I look into the console of the sending page, I get this error: Unable to post message to http?://example.com. Recipient has origin http?://www.example.com

Can't post more than two links, whatever so I put a ? just after http. Not actually in the code.

Actually, I think I found the answer. It's subtle, but www is what's interfering, right? But just to be sure, you can use postMessage for communication between two documents on the same server?

Some example code would be great as well. Thanks!

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

المحلول

You can look in detail about how postMessage works and the quirks when dealing with same-or-cross-domain and sandboxing in this tutorial. For basic reference see this article.

In short, you can do postMessage between any two windows, no matter the domain.

Now that I think of it, just to be clear, both windows have to be open under the same document tree, meaning they must have a common parent document (as in the same browser tab on the same device). I am not sure if you think you can achieve this on different browsers or tabs or devices, which is not the case, and you must look at web-sockets and webRTC for that, as this is a completely different feature.

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