How to respond to ajax call from iframe?

by tressie.damore , in category: HTML & CSS , 19 days ago

How to respond to ajax call from iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 17 days ago

@tressie.damore 

To respond to an AJAX call from an iframe, you can use postMessage API. Here is a simple example of how you can achieve this:

  1. In the parent window that contains the iframe, add an event listener to listen for messages sent from the iframe:
1
2
3
4
5
6
window.addEventListener('message', function(event) {
  if (event.origin !== 'https://example.com') return; // Ensure only messages from specific origin are accepted
  
  // Handle the message sent from the iframe
  console.log('Message received from iframe: ', event.data);
});


  1. In the iframe, use the postMessage method to send a message to the parent window:
1
2
// Send message to parent window
window.parent.postMessage('Hello from iframe!', 'https://example.com');


In this example, the parent window listens for messages from the iframe and logs the message received. The iframe sends a message to the parent window using the postMessage method.


Make sure to replace 'https://example.com' with the actual origin of the parent window and the appropriate origin verification logic to ensure secure communication between the iframe and the parent window.