Wednesday, May 16, 2012

Same Origin Policy for Document Object Model


The Same Origin Policy was introduced by Netscape in 1995. It has been implemented by all modern web browsers. Its principle is “Pages from the same site can access each other’s DOM without restriction. But the pages from one site cannot access DOM of pages from other different sites. “The Same Origin Policy provides strict content segregation for different websites to preserve confidentiality and integrity.

The origin is defined by three parts:

  • Domain name  (for example, www.example.com)
  • Application protocol (for example, http or https)
  •  Port number (for example, 80 or 8080)

Two origins are considered same if the values of three parts are exactly same. However, Internet Explorer does not include port number into same origin components.

There are two popular ways to get around “Same Origin Policy”
  • Changing document.domain

Two sites sharing a common top-level domain can mutually set their document.domain to the common top-level domain. For example, login.example.com and register.example.com can bypass the restriction by setting their document.domain=example.com. The security concern is that unwanted domains like evil.example.com can join the party by setting their document.domain=example.com.
  •  Use postMessage of HTML5

HTML5 provide a new method postMessage for passing data between documents in different domains. All modern web browsers support this new function, which provide a secure way for bypassing Same Origin Policy.

For example,
var framewindow=window.parent.frames["orgFrame"];
framewindow.postMessage(‘this is a test message’), ‘http://www.example.com’);
function receiveMessage(event)
{
            if (event.origin !== "http://example.org") // Make sure to accept messages from trusted domain
                        return;
            //process the received message
}
window.addEventListener("message", receiveMessage, false); // add message handler

No comments:

Post a Comment