引子:本來是想驗證如果在網頁中包含多個框架,那么就會存在兩個以上的不同全局環境,如果從一個框架引用另一個框架的數據比如數組a,那么用 instanceof 判斷這個數組a是不是另個框架Array的實例,於是html代碼如下
index.html:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <html> 3 <head> 4 <title> New Document </title> 5 </head> 6 <frameset cols="20%,80%"> 7 <frame src="link.html" name="link" /> 8 <frame src="show.html" name="show" /> 9 </frameset> 10 </html>
link.html:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 </head> 6 <body> 7 <script type="text/javascript"> 8 var arrOrder=[]; 9 </script> 10 </body> 11 </html>
show.html:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 </head> 6 <body> 7 <button onclick="console.log(self.parent.link.arrOrder instanceof Array)">click</button> 8 </body> 9 </html>
效果圖:
在firefox和IE的控制台下可以正常輸出false(驗證了用instanceof判斷一個對象是否為數組的弊端)
可是chrome控制台下輸出:Uncaught SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.
這是chrome同源策略引發的問題,而且不只是iframe的相互訪問時會出現,當需要通過ajax或者get和post方法從本地加載文件或者跨域訪問時也會遇到該問題,不然就不會有jsonp的出現了。
解決方案:stackoverflow大法好
http://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome
我這里只引用一下win平台下的解決方案,linux,OSX平台下可以參考鏈接里哈
For Windows go into the command prompt and go into the folder where Chrome.exe is and type
chrome.exe --disable-web-security
That should disable the same origin policy and allow you to access local files.
tip:Make sure you have closed all chrome processes, then try again. Chrome will issue a warning header if you have done it correctly: "You are using an unsupported command-line flag: --disable-web-security. Stability and security will suffer"
具體做法就是右鍵瀏覽器的快捷方式,添加箭頭所指的內容然后保存,然后重啟瀏覽器就ok,不過chrome會提示你“你使用的是不受支持的命令行標記:--disabled-web-security,穩定性和安全性會有所下降”,不用管它測試你的項目就好。
總結:關於跨域請求解決的方案不止這一種。有興趣的可以訪問http://slashlook.com/articles_20140523.html
chrome還有一個插件神器專門解決ajax請求中的跨域問題:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en