0

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.

SameerShaik
  • 422
  • 1
  • 7
  • 19
  • Possible duplicate of [Console displays Uncaught SecurityError](http://stackoverflow.com/questions/24900897/console-displays-uncaught-securityerror) – PseudoAj May 15 '16 at 08:43

1 Answers1

1

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.

Community
  • 1
  • 1
Dmitriy Nevzorov
  • 5,697
  • 1
  • 18
  • 28