Understanding and imbibing knowledge of cross windows and cross-origin resource sharing access (CORS).

Photo by Sergio Badillo on Unsplash

You most probably have used Iframe and wanted to exchange data between the parent window and the Iframe OR you have encountered some problem when you wanted to get API response from the backend or third-party backend.

First of all cross window access (Iframe..mostly happens on the browser) and CORS (mostly happens between server and client ) are slightly different conceptually.

we need to understand what exactly cross-origin and same-origin stand for.

Lets suppose site you are visiting is "http://site.com"
same-origin correspond to http://site.com:
http://site.com
http://site.com/my/page.html

iFrame window and current windows properties and communication

<iframe src="URL-OF-IFRAME" id="iframe" name="example"></iframe>
<script>
//CODE BLOCK FOR CROSS-ORIGIN START
//URL-OF-IFRAME = https://example.com
let iframeWindow = iframe.contentWindow; // OK
let iframedoc = iframe.contentDocument; // ERROR, not to the document inside it
iframe.contentWindow.location = '/'; // OK
iframe.onload = null; // clear the handler, not to run it after the location change
//CODE BLOCK FOR CROSS-ORIGIN END
  1. To access all iframe in the currently open window use `window.frames`
  2. To access named Iframe use `window.frames.example`
  3. window.frames – the collection of “children” windows (as frames can have another iframe ie. nested iframe).
  4. window.parent – the reference to the “parent” (outer) window.
  5. window.top – the reference to the topmost parent window. This is useful in the scenario in which you want to check if the current window is the topmost window.
  6. The current document of the iframe is defined inside the `iframe.onload`, all other is a stale version of the document.
  7. In the case of cross-origin, one can change the iframe’s window location by `iframe.contentWindow.location = ‘/’;`
  8. But if windows share the same second-level domain, for instance john.example.com, peter.example.com and example.com (so that their common second-level domain is example.com), we can make the browser ignore that difference by document.domain = ‘example.com’;
  9. "sandbox"an attribute of the iframe which adds more restrictions.

For CORS, one can see a well defined medium article from here

https://medium.com/@baphemot/understanding-cors-18ad6b478e2b

Software engineer, full stack developer