Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross domain issue with iframes

I know the solutions for cross browser domain calls. Either use JSONP, do a proxy call, or accept domains on server. I found 1 more strange way today at my company.

Method:

They are changing the host to match the host of second server by using this -

window.location.host = "xyz.com";
          or
document.domain = "xyz.com";

Then they are creating a hidden iframe and getting contents in iframe and replacing contents to visible element.

Problem:

It works with iframe but if I do ajax call, it doesn't work. Any words on this?

like image 618
emphaticsunshine Avatar asked Oct 24 '22 10:10

emphaticsunshine


1 Answers

i'm not a fan of jsonp, it creates coupling between data and presentation, and so i researched this issue before, and well, there's a trick that you can use, follow this:

let's say we have the main window named A and the "child" window in the iframe named B. A and B must be served from the same host, but can have different subdomains, something like:

A is served from sub1.example.com

B is served from sub2.example.com

browsers will let you change the domain of the document, but still restrict you on that, so you can only change the domain by removing subdomains until you reach the host, and so in A you change the domain, like so:

document.domain = "example.com";

in B you first make an ajax call to its domain (sub2.example.com), then after the first request was sent you change the domain just like in A, so that both documents have the same domain. since you made a request to the original domain in B the browser will allow you to keep sending requests to it, but since you also changed its domain, and now A and B have the same domain they can communicate with each other.

it's important that you first make at least one request in B to its original domain, before you change the domain. also, it won't work if both pages are not served from the same host, so in most cases it does not solve the problem, but it does allow you a bit more room to maneuver.

i used this trick more than once and haven't came across any problems, as far as i'm aware, it works in all browsers, let me know if it doesn't in some cases.

here's a pseudo example:

in A
==================
document.domain = "example.com";
var child; // keep reference to B
function setChild(win) {
    childDocument = win;
}

function handleMessage(message) {
    do what ever it is you need to
}

in B
==================
make ajax request
document.domain = "example.com";
parent.setChild(this);

function ajaxCallback(message) {
    parent.handleMessage(message);
}
like image 91
Nitzan Tomer Avatar answered Oct 27 '22 10:10

Nitzan Tomer