Same origin policy

The same origin policy permits scripts running on pages originating from the same domain to access each other’s DOM  with no specific restrictions, but prevents access to DOM on different domains.


Let me explain how policy works with an example:

Suppose consider you have page1.html in a domain

And consider this is the content of the page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<script  src=""></script>
<span>Page1 content goes here</span>
<iframe src=""></iframe>
<iframe src=""></iframe>

If you see in the above example there are two iframe tags.

First iframe pointing to the page2 of a same domain and it works fine.

But the second iframe which is pointing to the page of another domain will not load this  because it’s not from the same domain.

(Note: Again it’s depends on the domain too some domains even allow the other domains to access their  DOM without any security restrictions

Ex for such sites: From any domain you can access this site).

This Same origin Policy poses a problem for large websites that uses multiple subdomains.

To overcome from this problem we can use an open source service which is provided by  .

What this service does is  It just grabs content from a website specified in GET parameter and returns it together with HTTP status code as JSON data. By this we are not pointing iframe to the target site directly instead we are just getting the html content and rendering the same.

So we can modify the above example as:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<script src=""></script>
<span>Page1 content goes here</span>
<iframe src=""></iframe>
<div id="siteLoader">
var url = '';
$.getJSON('' + encodeURIComponent(url) + '&callback=?', function(data){
 var html = ""+data.contents;
/* Replace relative links to absolute ones */
html = html.replace(new RegExp('(href|src)="/', 'g'),  '$1="'+url+'/');

In the above example we are creating a div with id siteLoader which is a place holder for url content.

In the javascript we are getting the content of the url using service provided by

Later on we are adding the html content to the div tag


Now you can see both pages iframes seamlessly.

There are other techniques too provided to come out of this policy like

1. Document.domain property

2. Cross-Origin Resource Sharing

3. cross-document messaging


The following two tabs change content below.

Chaman Shareef

Latest posts by Chaman Shareef (see all)

Submit a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current month ye@r day *