Reputation: 526
I have an iframe in which src is different domain, and I am trying to call a method in iframe from parent window. Then it is giving below:
Uncaught SecurityError: Blocked a frame with origin "http://localhost:8080" from accessing a frame with origin "http://stage.xyz.com". Protocols, domains, and ports must match.
On main window I have this:
launchUPwidget(widgetParams);
function launchUPwidget(widgetParams){
document.getElementById('iframe').contentWindow.invokeUPWidget(widgetParams);
}
On iframe:
window.invokeUPWidget = invokeWidget;
So how can I call a function in child iframe form parent window where iframe src is different domain?
here protocals are same but the domains are different.
Upvotes: 0
Views: 2080
Reputation: 6078
You can't access an <iframe>
with Javascript, it would be a huge security flaw if you could do it.
For the same-origin policy every browser blocks any script trying to access a frame with a different origin.
Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:
In your main page:
var frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, '*');
In your (contained in the main page):
window.addEventListener('message', function(event) {
// IMPORTANT: Check the origin of the data!
if (event.origin.indexOf('http://yoursite.com')) {
// The data has been sent from your site
// The data sent with postMessage is stored in event.data
console.log(event.data);
} else {
// The data hasn't been sent from your site!
// Be careful! Do not use it.
return;
}
});
There is a similar question. You can read about it more there.
Upvotes: 1