Sop Lab
Same Origin Policy Example1
-
Suppose that index.html on site1.com (referred to as origin1: http://site1.com) wants to access , via an Ajax request (xhr), the home.html page on domain site2.con (referred to as origin2: http://site2.com)
-
Open http://site1.com/index.html , go to developer tools > console and try to execute following ajax code to send http request to the http://site2.com/home.html
function checkSiteAvailability(url) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('The site is available (Status Code 200 OK)');
} else {
console.error('The site is not available (Status Code ' + xhr.status + ')');
}
}
};
xhr.send();
}
checkSiteAvailability('http://site2.com/home.html');
- same origin policy will not allow the execute this ajax request
Same Origin Policy Example2
- We have to documents: the main document http://site1.com/index.html and the iframe document http://site1.com/iframe.html
- Here is iframe.html page source
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<iframe src="http://site1.com/index.html" frameborder="200"></iframe>
</body>
</html>
- Now open to console and try to catch this iframe via javascript code
window.frames[0].body
- SOP will allow to execute this js code, beacuse we are on the same origin.
- Now change the iframe src with http://site2.com/index.html and try to catch iframe again.
- This time sop will not allow us to execute js code , because we are on the different origin