'Why can't I receive messages from another website using the window.postMessage method?

I run an HTML file using WebStorm 2022.1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Window.postMessage</title>
</head>
<body>
    <script>
        let time = 0;
        
        setInterval
        (
            function ()
            {
                window.top.postMessage("Source01", "*");
                
                console.log(`Time: ${++time}`);
            },
            2000,
            time
        )
    </script>
</body>
</html>

And it's at the address : http://localhost:63342/XXX .Then I open any website, let's say https://stackoverflow.com/ .In the console, I write the following code

    window.addEventListener("message", function (event)
    {
        console.log(event);
    })

I observed that no messages were sent. Did I forget something?



Solution 1:[1]

window.top.postMessage sends the message to the document in the current window, at the top of any stack of frames. Let's call this Page A.

If the URL for Page A appears in the browser's address bar, it will send a message to itself.

If the URL in the address bar is Page B and it includes an iframe which loads Page A, then it will send the message through the frames to Page B. (Stackoverflow doesn't have <iframe src="http://localhost:63342/XXX"></iframe> so this isn't the case for you).

If you load Page C in a new window, then Page A won't send a message to it, because is in a window.

If you navigate from Page A to Page D in the same window, then Page A won't send a message to Page D because navigating away from Page A will stop the JS program.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin