同源策略不起作用

same origin policy not working

本文关键字:不起作用 策略      更新时间:2023-09-26

我正在尝试用我创建的一个小演示来理解同源策略。但不知怎的,有些地方出了问题。以下是2个不同域名(我在XAMP中托管的虚拟域名)上的html文件:-

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>

现在让我们说我在domain1.com和在iframe(持有domain2.com),我在iframe的文本框中放入一些文本。现在我点击"stealData"按钮。所以理想情况下,我在这里期望的是同源策略应该启动,我不应该被允许访问iframe中文本框的内容。在Firefox的java脚本控制台中,应该可以看到同样的错误。但这并没有真正发生。为什么?

感谢大家。在看完RichieHIndle的评论后,我意识到设置域名本身是一个错误。我的域的httpd-vhosts.conf条目不正确。纠正这个文件完成了工作,我得到了我所期望的。我可以看到同源政策在起作用。