There seems to be an issue with receiving the message sent through postMessage()

I seem to be encountering an issue with my syntax while attempting to pass a variable to an iframe (for colorbox integration). Currently, I've allowed all domains on both ends for testing purposes. Here is the JavaScript code for the sender page:

$(document).ready(function() {
 if(window.location.hash) {
  var urlimage = window.location.hash.substring(1);
  targetiframe = document.getElementById('wbgallery').contentWindow;
  targetiframe.postMessage(urlimage, "*");
  console.log(urlimage);
 }
});

Here is the code for the receiver page:

$(document).ready(function() {    
 window.addEventListener('message',receiveMessage);
 console.log(event);
 function receiveMessage(event) {
   if (origin !== "*")
   return;
   inbound = event.data;
   console.log(inbound);
 }
});

While I can see the console log for urlimage and observe an event, there seems to be no output for inbound. I'm referring to Mozilla's documentation to troubleshoot this.

Answer №1

Before the iframe page fully loads, ensure that you wait for the message listener to be established.

To overcome this issue, have the iframe send a message to the parent once it's prepared, and then proceed with sending the message.

Below is the code for both Parent and Iframe:

// Parent Code
$(document).ready(function() {
  if (window.location.hash) {
    var urlimage = window.location.hash.substring(1);
    var targetiframe = document.getElementById('wbgallery').contentWindow;
    $(window).on("message", function(e) {
      targetiframe.postMessage(urlimage, "*");
      console.log(urlimage);
    });
  }
});
// Iframe Code
$(document).ready(function() {
  $(window).on('message', function(event) {
    inbound = event.data;
    console.log(inbound);
  });
  window.parent.postMessage("ready", "*");
});

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

Encountering a RangeError in FusionCharts with VueJS, I faced the issue of exceeding the maximum call stack size while trying to

After inserting a clip array into xAxis, I encountered a RangeError. Has anyone else experienced this issue? I have set up a repository to demonstrate the bug: https://github.com/Ic3m4n34/fusioncharts-bug (App.vue) Does anyone have suggestions on how to ...

What is the best way to establish communication between a server and client using sockets in Node.js?

Presently, I am in the process of developing a JavaScript application using AppJS. I'm encountering some difficulties understanding the communication between the client and server. Issue with Menu Bar and Socket Interaction The main challenge lies ...

Switch between Bootstrap Chevron

I need assistance with toggling a chevron in a bootstrap dropdown menu. Currently, the chevron only changes when clicked directly, but I want it to change whenever the dropdown is toggled open or closed. This way, if another part of the menu is clicked, th ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

What are some strategies for preloading a webpage to improve loading times?

My webpage contains multiple images, but the browser loads them one by one when a user visits the page. I would like to display a "loading" gif in the center of the page first and only show the entire webpage once all the images have been downloaded. Is ...

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

I am attempting to draw a correlation between two numerical variables

I'm struggling to compare two scores in my game. When they match, I want it to display "You won", but I can't get it to work. I've attempted using the parseInt method and .val method, but no luck so far. var numberFour = Math.floor(Math.ra ...

Experiencing variations in value with the MUI date picker

I encountered an issue with the Mui 5 date picker. When I change the date using the calendar, I get the expected result. For example, if I select the 26th, I get the following timestamp: "2022-01-26T09:16:10.000Z". However, when I directly edit ...

Enhancing Filtering Capabilities with Multiple ng-Model in AngularJS

I am facing an issue with filtering a form based on user input in a text box or selection from a dropdown list. The text box filter works fine individually, but when I try to combine it with the dropdown list selection, neither filter seems to work. Below ...

Adjusting a Vue Slider with a changing value

Currently, I am utilizing the Vue Slider component from this source. My goal is to enhance the functionality of the slider by increasing it to the next index and beyond. The issue lies in the fact that the current implementation increments by 1, as the val ...

Deactivate the AJAX button after the specified number of clicks

Imagine I have a model called Post, and it can be associated with up to n Comments (where the number is determined by the backend). Now, let's say I have a view that allows users to add a Comment through an AJAX request. What would be the most effecti ...

Displaying a timer output in an HTML div every second using PHP

I created a custom PHP countdown timer that displays the remaining time in hours, minutes, and seconds (specifically 3 hours) - named countdown.php. The timer output is displayed within a <div> tag on another page called index.html. Now, I am lookin ...

Error message in Angular 2, Problem found in inline template while utilizing eval() function

<li *ngFor="let pdfifRecord of pdf.ifRecord;let i=index"> <p>{{eval(pdfifRecord.labelMsg)}}</p> </li> I need to show the output of the eval function. Encountering an error message: Error in inline template c ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

Introduction to Angular controller binding for beginners

I'm currently going through this tutorial : http://www.youtube.com/watch?v=i9MHigUZKEM At 46:32 minutes into the tutorial, this is the code I have implemented so far : <html data-ng-app="demoApp"> <body data-ng-controller="SimpleControlle ...

Exploring the Power of an Enumerator in JavaScript

I'm in the process of converting the following VBScript code to JavaScript: Sub GxUIProxyVB_OnLogon Dim EntityProxy For Each EntityProxy In GxUIProxyVB.ListEntityProxy MsgBox EntityProxy.Name Next End Sub This code is an e ...

An incessant stream of onclick events is being triggered

My HTML code consists of a jQuery script and a button that triggers a function to display random answers. However, after clicking the button once, the answers cycle automatically without any input. I want each click to show a different answer. What could ...

What steps can I take to avoid unintentionally populating this object with undefined values?

This issue occurs when the variable level is initialized with the value 'undefined'. Although this code functions correctly in JavaScript, it encounters problems when using TypeScript. interface Find { level?: string; } let find: Find = {}; ...

What is the best way to replace HttpClient in Aurelia?

I am completely new to Aurelia. How can I modify the code below in order to implement a dummy HttpClient, such as a json reader, that will provide a static set of json data without the need for a server during development? import {inject} from 'aure ...