您的位置:首页 > 其它

win下如何解决在chrome的同源访问问题

2016-03-01 21:57 316 查看
[b]引子:[/b]本来是想验证如果在网页中包含多个框架,那么就会存在两个以上的不同全局环境,如果从一个框架引用另一个框架的数据比如数组a,那么用 instanceof 判断这个数组a是不是另个框架Array的实例,于是html代码如下

index.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> New Document </title>
</head>
<frameset cols="20%,80%">
<frame src="link.html" name="link" />
<frame src="show.html" name="show" />
</frameset>
</html>


link.html:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var arrOrder=[];
</script>
</body>
</html>


show.html:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onclick="console.log(self.parent.link.arrOrder instanceof Array)">click</button>
</body>
</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的出现了。

[b]解决方案:[/b]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,稳定性和安全性会有所下降”,不用管它测试你的项目就好。





[b]总结:[/b]关于跨域请求解决的方案不止这一种。有兴趣的可以访问http://slashlook.com/articles_20140523.html

chrome还有一个插件神器专门解决ajax请求中的跨域问题:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: