Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to retrieve an ajax response sent from an iframe?

I was wondering if there is any way to retrieve the response of an ajax request sent from an iframe.

The iframe does something like the following:

  1. script in iframe sends an ajax request
  2. iframe gets a response, and updates content within iframe

What I would like to do is to intercept that request outside of the iframe, and use that information to update the page.

If you go into chrome's dev tools, and go to the network tab, you can see the request/response that the iframe makes. It would be nice if there is a window event or something similar that triggers everytime a response comes in on the page.

NOTE: the iframe is a page that is not in the same domain.

like image 771
kennypu Avatar asked Dec 27 '22 00:12

kennypu


2 Answers

If the child iframe is in a different domain to the parent, you can't really do anything that's going to work across browsers. See jasonjifly's answer below for techniques that will work on some browsers assuming you have control over the client scripts on both frames.

If the parent and child are on the same domain, then you can achieve what you are looking for.

For example, assuming you're using jquery, you could have this code in your iframe:

$.ajax(function() {
   .....
   complete: function() {
       window.parent.onAjaxComplete('Hi there');
   }
});

Along with this code in your parent frame:

function onAjaxComplete(msg)
{
    alert(msg);
}

To achieve similar results in a cross-domain scenario you could have the parent frame poll the server. When the server receives an ajax request from the child iframe it could then alert the parent page via the polling service. Obviously this would only be suitable if you have control over the services called by the child iframe.

like image 66
cbp Avatar answered Jan 13 '23 18:01

cbp


In theory, it's forbidden to communicate between two cross domain iframe, due to the same-origin policy, please refer to this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript

Before HTML5, we have some workarounds:

  1. If you just want to use iframe to get cross domain data, you can use JQuery:JSONP, the essence is using . "" allows executing a cross domain javascript.

  2. Another way is "An iframe in an iframe in an iframe", you can refer to this page: http://blog.cakemail.com/the-iframe-cross-domain-policy-problem/

HTML5:

  1. window.postMessage, refer to this page: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

  2. HTML5 CORS, you need to configure server, refer to this page: http://www.html5rocks.com/en/tutorials/cors/

My recommendation is using solution 1, it can work on almost all mainstream browsers.

like image 28
jasonjifly Avatar answered Jan 13 '23 16:01

jasonjifly