当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - same origin policy not working

问题描述:

I am trying to understand the same origin policy with a small demo that i have created. But somehow something is going wrong. Below are the html files on 2 different domains (virtual domains that i hosted in XAMP) :-

domain1.com

<html>

<title>

DOMAIN1.COM

</title>

<script>

function showTheirSecret()

{

var stolenSecret=document.getElementById('stealSecret').contentWindow.document.getElementsByName("mySecret")[0].value;

if (stolenSecret)

{

alert("Script on this page accessed the secret box and says "+stolenSecret);

}

else

alert("Script on this page can not access the secret box!! ");

}

</script>

<body>

WELCOME TO <h1>domain1.com</h1><br>

This is the contents on domain1.com. <br>

These can not be accessed by domain2.com

<br>

<br>

<iframe id="stealSecret" src="http://localhost/~user/training/domain2.com/"></iframe>

<br>

<br>

<h2>

Click the "ok" button to see domain 2's secret text.

</h2>

<input type="button" value="stealData" onclick="javascript:showTheirSecret()">

</body>

</html>

domain2.com

<html>

<title>

DOMAIN2.COM

</title>

<script type="text/javascript">

function showMe()

{

var secret=document.getElementsByName("mySecret")[0].value;

if(secret)

{

alert("Script on this page accessed the secret box and says "+secret);

}

else

alert("Script on this page can not access the secret box!! ");

}

</script>

<body>

WELCOME TO <h1>domain2.com</h1><br>

This is the contents on domain2.com. <br>

These can not be accessed by domain1.com

<br>

<h2>

Put your secret text here !!

</h2> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

<h2>

Click the "ok" button to see your own text.

</h2>

<input type="password" name="mySecret" value ="">

<input type="button" value="ok" onclick="javascript:showMe()">

</body>

Now lets say I am on domain1.com and in the iframe (that holds domain2.com), i put in some text in the text box in the iframe. Now i click on the "stealData" button. So ideally, what I am expecting here is that the same origin policy should kick in and i should not be allowed to access the contents of the text box in the iframe. And the same should be visible as an error in the java script console in Firefox. But this does not really happen. WHY ?

网友答案:

Thanks to all. After going through RichieHIndle's comment, I realized it was a mistake in setting up the domains itself. My httpd-vhosts.conf entries for my domains were incorrect. Rectifying this file did the job and I got what I was expecting. I could see the same origin policy in action.

分享给朋友:
您可能感兴趣的文章:
随机阅读: