The same-origin policy is a security implementation found in the most common browsers that allow scripts or documents contained in a first web page to access data in a second web page, but only if both web pages have the same origin. Origin is considered on the basis of protocol, port number, and, more importantly, the hostname of the web page. This policy restricts a malicious script on one page from obtaining access to sensitive data on another web page.
Demonstration of the same-origin policy in Google Chrome browser for example:
When the previous code runs inside the Chrome browser, it throws an exception and gives the following message in the console.log() output:
DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame. at HTMLIFrameElement.document.getElementsByName.onload (file:///C:/test.html:12:19)
The script was run from the localhost, and Google Chrome’s same-origin policy (SOP) mechanism prevented localhost from accessing the contents of the example.com iframe.