Wednesday, April 5, 2017

Iframe communication or Accessing a cross-origin frame

Accessing a cross-origin frame.

window.postMessage allows you to send messages not only across frames (regular frame or iframe) but also across domains. This post showed interaction from parent to child. Even when we keep the iframe domain url is different for the main page url.
With out using the window.postMessage will gives us below error message in console

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

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 browsers block scripts trying to access a frame with a different origin.
Origin is considered different if at least one of the following parts of the address isn't maintained: ://:/path/to/page.html Protocol, hostname and port must be the same of your domain, if you want to access a frame.


Examples
Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL RESULT
http://www.example.com/home/other.html -> Success
http://www.example.com/dir/inner/another.php -> Success
http://www.example.com:80 -> Success (default port for HTTP)
http://www.example.com:2251 -> Failure: different port
http://data.example.com/dir/other.html -> Failure: different hostname
https://www.example.com/home/index.html.html -> Failure: different protocol
ftp://www.example.com:21 -> Failure: different protocol & port
https://google.com/search?q=james+bond -> Failure: different hostname & protocol
Workaround

No comments:

Post a Comment