Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to access a function on a parent page from an iframe that is on a different subdomain?

I am trying to access a function located on the parent page from an iframe. I get the following error since they're using different sub-domains:

Uncaught SecurityError: Blocked a frame with origin "http://subdomain.domain.com" from accessing a frame with origin "http://subdomain2.domain.com". Protocols, domains, and ports must match.

I am using:

window.parent.myFunction(); 

to access the function on the parent page.

Is there a workaround for this or will it simply not work because they're different sub-domains?

like image 923
user3499518 Avatar asked Apr 16 '14 03:04

user3499518


People also ask

Can an iframe get parent URL?

location. ancestorOrigins[0] will get the parent url, but this api only works in chromium browsers (see support). this also supports nested iframes, where the bottom most child has access to the urls of each parent iframe.

Does an iframe have its own window?

In action: iframeAn <iframe> tag hosts a separate embedded window, with its own separate document and window objects.

Why is it bad to set the document domain to a parent domain?

It undermines the security protections provided by the same origin policy, and complicates the origin model in browsers, leading to interoperability problems and security bugs. Attempting to set document. domain is dangerous.


2 Answers

Blocked a frame with origin "http://subdomain.domain.com" from accessing a frame with origin "http://subdomain2.domain.com"

If you add the line:

document.domain = 'domain.com';

to the scripts in both frames, they will be able to interact directly with each other's objects. See MDN for background.

However cross-frame scripting is strewn with nasty corner cases, where one frame executes something from another frame whilst that frame is busy doing something else, or isn't yet fully loaded. For anything non-trivial, I would avoid direct cross-frame scripting.

The more modern alternative is to keep execution within a single frame, and communicate across frames using postMessage. Support.

like image 161
bobince Avatar answered Nov 14 '22 23:11

bobince


This will only works if you have access to the parent domain (e.g. upload files there).

Inside your iframe page, create a second iframe with a source pointing to a page in the main domain.

The second iframe can call a function in the main page by using window.parent.parent.myFunction();

like image 30
NoGray Avatar answered Nov 14 '22 23:11

NoGray