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?
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.
In action: iframeAn <iframe> tag hosts a separate embedded window, with its own separate document and window objects.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With