Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message.

index.html:

<head>
    <title>Test 1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
        function popupResize() {
            var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
            // var popup = window.open('https://foo/index.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
            window.addEventListener(
                'message',
                function(event) {
                    console.log(event.data);
                },
                false
            );
        }
    </script>
</head>
<body>
    <a href='javascript:void(0)' onClick="popupResize(); return false;">Go!</a>
</body>

popup.html:

    <head>
    <title>Game history details</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script>
        function postSize() {
            var h = 100;
            var w = 200;
            opener.postMessage([h, w], '*');
        }
    </script>
</head>
<body onload="postSize();">
    test 1
</body>

Is there a way to make it work when using different servers?

Answer №1

Solution for Issue 1

popup.addEventListener(

To properly handle the event, you should listen on the original window instead of the popup. The popup is where the message originates, not where it should be received.

You can use window.addEventListener( or simply addEventListener(.

Solution for Issue 2

{h, w}

It's important to note that ES6 shorthand property names are not compatible with IE, Opera, Safari, or Android Mobile browsers. It's recommended to avoid using them.

Solution for Issue 3

parent.postMessage({h, w}, '*');

You are actually sending a message to the opening window, not the parent frame. Since there is no actual parent frame (and parent refers back to window), the correct syntax would be:

 opener.postMessage({h: h, w: w}, '*');

Solution for Issue 4

<script type="text/javascript">
   var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');

Your script lacks permission to open a new window except in response to a user event. To fix this, move the code into a function and call it from events like a click event.


If tested on the same server, there wouldn't be any issues - messages will be received successfully.

The root cause of the problem lies in issues 1 and 3. By binding an event handler to the popup and posting a message from the popup to itself (parent === window), the behavior is flawed.


A working code snippet (although not best practice) includes:

http://localhost:7007/index.html

<!DOCTYPE html>
<html>
<script>
addEventListener("message", function (event) {
    document.body.appendChild(document.createTextNode(event.data));
});
function pop() {
    window.open("http://127.0.0.1:7007/popup.html");
}
</script>
<input type="button" onclick="pop()">

http://127.0.0.1:7007/popup.html

<!DOCTYPE html>
<html>
<script>
opener.postMessage([123, 456], '*');
</script>
<h1>popup</h1>

Answer №2

The eventListener should be connected to window rather than popup:

window.addEventListener(
    'message',
    function (event) {
        console.log(event.data);
    },
    false
);

When you send a message from your child window (popup) to the parent window, make sure the eventListener is attached to the correct window.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

Not receiving connections on localhost port 3000

Our team has successfully created a basic Express Node website https://i.stack.imgur.com/5fwmC.png We attempted to run the app using DEBUG=express_example:* npm start https://i.stack.imgur.com/NI5lR.png We also tried running it with node DEBUG=express_ ...

Preventing Javascript array elements from being overwritten: Best practices

My challenge lies with the addToClients() function, which is designed to add a new value to the clients array whenever a button is pressed. The issue I am facing is that each time I press submit, the previous element in the array gets replaced by the new o ...

What is the method for writing to an HTML file with the use of expressjs?

Alright, I have an interesting idea here. I am looking for a way to allow users to push a button and have a new p element permanently added to the HTML file. This means that even after reloading the page, everyone should be able to see this new element. An ...

Consistently directing to a single page on the Node Js web server

I'm in the process of creating a website with multiple HTML pages. Currently, I have code that successfully links to the login page, but unfortunately, the localstores page also directs to the login page. const express = require('express') ...

Identify and sort JSON objects based on keys with multiple values

My JSON file contains objects structured like this: [ { "name" : "something", "brand": "x", "category" : "cars" }, { "name" : "something2 ...

What is the best way to apply lodash's max function to a jQuery array?

I'm having trouble extracting the maximum number of rows from two tables. My variable maxRows ends up being a tbody jQuery element instead of the actual maximum value. I've experimented with both the pluck syntax and the long form, but both metho ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

Troubleshooting: Unable to Sort Column in ngx-DataTable Angular 4

As a newcomer to Angular, I have been encountering some challenges while using ngx-DataTable. I am currently utilizing a simple ngx-DataTable for basic operations. The issue I am facing is that the sorting functionality is not working on a specific column, ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

Can I utilize p5.Vector.fromAngle() in Vue JS?

Incorporating P5 into a Vue application can be achieved using the following code snippet: let script = p5 => { p5.setup = _ => { this.setup(p5) } p5.draw = _ => { this.draw(p5) } } this.ps = new P5(script) While functions like ba ...

Prevent anchor link click and drag functionality on an HTML page / Swipe through a container containing links

Is there a way to prevent clicking and dragging on a link in a webpage? When you click the left mouse button on a link and drag it, you can unintentionally move the link or open a new tab. I am looking for a way to disable this behavior using JavaScript o ...

Tips for preventing a page refresh using HTML, JQuery, AJAX, and PHP

I need assistance with transferring the value of a selected radio button to a PHP session variable using Javascript/AJAX. Everything seems to be working fine, except that the page refreshes each time. Is there a way to prevent this from happening? Below i ...

Choose an image for a better view with the use of HTML and JavaScript/JQuery

Requesting assistance in creating a simple code using plain html5 and JavaScript/jQuery (without plugins) that will enlarge an image upon clicking on it from a list of images. Here is the HTML snippet provided: <!-- Large image holder --> & ...

Angular Leaflet area selection feature

Having an issue with the leaflet-area-select plugin in my Angular9 project. Whenever I try to call this.map.selectArea, VSCode gives me an error saying that property 'selectArea' does not exist on type 'Map'. How can I resolve this? I& ...

The page does not seem to be reloading properly due to a redirect issue

I am currently updating some data and then attempting to reload the current page. After discovering the status code that allows me to switch the redirect method from put to get (303), I noticed that it is functioning correctly. However, despite seeing "fi ...