Interacting with an iframe within the same domain

I'm currently working on an application in Angular 6 that requires communication with an iframe on the same origin. I'm exploring alternative methods to communicate with the iframe without relying on the global window object. Is there a more efficient way to achieve this, perhaps through a wrapper or using RxJS?

P.S.: I have already looked into storage examples, but I would like to hear your thoughts on achieving the same goal in a cleaner way without cluttering the window object.

Thank you!

Answer №1

If you want to establish communication between two <iframe> elements, you can utilize the postMessage method.

Whenever a message is received, a message event is triggered. This allows you to create an observable using fromEvent, if desired.

Here's a simple example scenario:

Suppose there are two HTML files - ping.html and pong.html. Both are hosted on http://localhost:8000.

  1. ping.html sends the initial message to pong.html
  2. Upon receiving the message, pong.html displays '👆' and replies back
  3. When ping.html receives this response, it displays '👇' and sends another message in return
  4. And so forth...

Below is the content of ping.html:

<html>
  <head>
    <meta charset="utf8">
  </head>
  <body>
    <div id="msg_from_pong"></div>
    <iframe id="pong" src="pong.html" style="width:100%;border-style:none"></iframe>

    <script>

      // Wait for the pong iframe to load
      document.querySelector('#pong').addEventListener('load', ({target}) => {
        target.contentWindow.postMessage('initial ping', 'http://localhost:8000');
      });

      // Listen for messages from the pong iframe
      window.addEventListener('message', ({data, source, origin}) => {
        if (data !== 'pong') {
          return;
        }

        document.querySelector('#msg_from_pong')
          .appendChild(document.createTextNode('👇'));

        setTimeout(() => {
          source.postMessage('ping', origin);
        }, 300);
      });

    </script>
  </body>
</html>

Here is the content of pong.html:

<html>
  <body>
    <div id="msg_from_ping"></div>
    <script>
      window.addEventListener('message', ({data, source, origin}) => {

        document.querySelector('#msg_from_ping')
          .appendChild(document.createTextNode('👆'));

        setTimeout(() => {
          source.postMessage('pong', origin);
        }, 300);
      });
    </script>
  </body>
</html>

Watch the complete interaction here:

https://i.stack.imgur.com/iP06A.gif

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

Create an HTML table row that includes a value along with its related sibling and parent values

I need to create an HTML table that compares segments in a JSON object. The format should display the segments along with their measures organized by domain group and vertical: ------------------------------------------------------------------------------ ...

Avoid unnecessary re-renders in React Redux by ensuring that components do not update when properties are not utilized in their

I'm encountering an issue with a component that keeps re-rendering. I've implemented Redux to handle my states. Within a component, I access a property (isPlaying: bool) from the state using mapStateToProps in various methods of the component, ex ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

Is there a way to access the active request being processed in a node.js environment?

I am currently working with express.js and I have a requirement to log certain request data whenever someone attempts to log a message. To accomplish this, I aim to create a helper function as follows: function logMessage(level, message){ winston.log(le ...

Why is it not possible for me to choose an element after it has been placed within a grid component?

Struggling to eliminate the blur effect on an image inside a grid element? It seems modifying the properties of an element within a grid class is causing some issues. To simplify, I conducted a basic test: I managed to change the ppp2 class when hovering ...

What is the root cause behind the recurring appearance of this line in Angular/D3.js?

I recently came across an excellent tutorial on integrating the D3.js library with AngularJS by following this link: . The guide provided has been extremely helpful in getting me started (big thanks to Brian!) However, I'm eager to delve deeper into ...

Encountering issues with running npm install on a local Angular project

Whenever I try to execute npm install on my local Angular project, I encounter the following errors: C:\Projects\Angular>npm install npm ERR! code ENOENT npm ERR! syscall spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent Error ...

The ajax POST method fails to trigger in a Node.js environment

Having an issue with the POST request. It's necessary for updating info without page reload. Below is my pug code: .tinder--buttons form(id="form1") button#love(type="submit") i.fa.fa ...

Ways to stop a ng-click event on a child div controller from activating an ng-click in the parent controller?

http://plnkr.co/edit/gB7MtVOOHH0FBJYa6P8t?p=preview The example above demonstrates a parent-child controller setup. In the child controller, when a button is clicked, it displays the div showPop and emits an event to the $rootScope. Upon receiving this e ...

Steps to load data using ajax-php with specific parameters

I have a situation where I need to trigger a JavaScript function when a link is clicked. <input type='hidden' id='name'> <a href='#' onclick='getUsers(1)'>Click here</a> function getUsers(id){ $( ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

Listener of events calculates the outcome

In need of help with retrieving the current coordinates of a clicked point on Google Maps. Here is my code snippet: let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); getCoords() { google.maps.event.addListener ...

Unlocking the Count of ng-repeat Elements in Angular JS 1

I'm curious about how to obtain the count of items in ng-repeat using AngularJS. In this particular code, I'm interested in finding out the count of "skill" because I want to set a limit on it. If the count of skills exceeds 5, I only want to dis ...

German-formatted jQuery datepicker

Need help in changing jQuery datepicker formatting from MM/DD/YYYY to German style as d MMMM yyyy. Tried implementing the following code but encountering issues. <script type="text/javascript"> $(function () { $('.datepicker&ap ...