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 structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

Is it necessary for the scope to be separated?

In the document object model (DOM), I have two straightforward directives that are responsible for creating similar elements. Both directives have an isolated scope. Each directive has an ng-click attribute that calls a method to display a message. One d ...

The error message encountered is: "TypeError: Unable to access the 'apply' property of an undefined object within the

Currently in the process of developing a node js application with the integration of DHTMLX Scheduler feature on one of the pages. However, my progress is hindered by a recurring issue upon loading the page, resulting in the following error message: TypeE ...

Stop the page from automatically scrolling to the top when the background changes

Recently, I've been experimenting with multiple div layers that have background images. I figured out a way to change the background image using the following code snippet: $("#button").click(function() { $('#div1').css("background-image ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

What is the best way to obtain a unique dynamic id?

This is the unique identifier retrieved from the database. <input type="hidden" name="getID" value="<?php echo $row['ID']; ?>"> <input type="submit" name="getbtn" value="Get ID"> How can I fetch and display the specific dynami ...

Encountering a problem with Nginx and WordPress where the admin-ajax.php is causing an issue when returning an AJAX result, leading to an error of Un

Currently, the issue is that everything runs smoothly on my Apache server, but when I switch to Nginx, an error is triggered with Uncaught SyntaxError: Unexpected token < Below is the function extracted from Functions.php function searchranges() { ...

How to target child <div> elements within a parent <div> using jQuery

I am facing an issue with my parent <div> named #amwcontentwrapper. It contains a series of child divs with their own classes and ids. My goal is to utilize jQuery to select these child divs, and if they have the class .amwhidden, I want to leave th ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

Utilizing ReactJS to fetch data from Material-UI's <TableRow/> component upon selection - a comprehensive guide

I've integrated Material-UI's <Table/> (http://www.material-ui.com/#/components/table) component with <TableRow/> containing checkboxes in a ReactJS project. While I can successfully select rows by checking the boxes, I am struggling ...

What is the process for including a custom Jasmine matcher definition in Typescript?

I've been searching around for information on creating custom Jasmine matchers using TypeScript and it seems like a common issue. However, none of the solutions I've come across have worked for me. My setup includes: { "typescript": "2.3.2", ...

Encountering issues with generating image files using createObjectURL after transitioning to NextJS 13 from version 10

I'm currently working on a website with the following functionality: Client side: making an API call to retrieve an image from a URL Server side: fetching the image data by URL and returning it as an arrayBuffer Client side: extracting the arrayBuffe ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

Are third-party scripts and HTML widgets able to replicate your website's data, including cookies, HTML, and other elements?

Currently, I am in the process of constructing a website that incorporates a third-party weather HTML widget. The widget is sourced from a trusted and reliable source on the web. It consists of a link and small JavaScript tags that are executed once loaded ...

The wait function does not pause execution until the element is found within the DOM

Upon clicking the Next button to proceed with my test, I encountered a transition on the page that prevented me from inputting the password. To solve this issue, I implemented the wait method to pause for 1 second until the element is located. The error ...

When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away. Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if i ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

Error in ReactJS: Trying to access property 'items' of an undefined object

I've been diving into ReactJS, but I've hit a roadblock with this perplexing error. My goal is to update the parent's items array state from its child component. To achieve this, I attempted to pass the addItem function as a prop to the chi ...