Open evantianx opened 7 years ago
老生常谈的话题,今天来总结一下。
谈到跨域就必须说一说“同源策略”:
所谓同源策略 The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. http://store.company.com/dir2/other.html //同源 http://store.company.com/dir/inner/another.html //同源 https://store.company.com/secure.html //不同源,协议不同 http://store.company.com:81/dir/etc.html //不同源,端口不同 http://news.company.com/dir/other.html //不同源,host不同 From Same-origin policy MDN
所谓同源策略 The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin.
http://store.company.com/dir2/other.html //同源 http://store.company.com/dir/inner/another.html //同源 https://store.company.com/secure.html //不同源,协议不同 http://store.company.com:81/dir/etc.html //不同源,端口不同 http://news.company.com/dir/other.html //不同源,host不同
From Same-origin policy MDN
JSONP
<script> //jsonp回调方法,一定要写在jsonp请求前面 function testjson(txt){ alert(txt); } </script> <script src ="/demo/testJsonp.shtml?callback=testjson" type="text/javascript" ></script>
/** * jsonp 测试 * @return */ @RequestMapping(value="testJsonp",method=RequestMethod.GET) @ResponseBody public String testJsonp(String callback){ return callback +"('test jsonp');"; }
JSONP的缺点在于只支持GET请求而不支持POST请求。
document.domain
不同的框架之间(父子或同辈),是能够获取到对应的window对象的,但是不可以操作其属性和方法。
此时修改document.domain可以实现框架间的跨域。
//http://www.example.com/a.html <script> function onLoad() { var iframe = document.getElementById('iframe'); var win = iframe.contentWindow; //可以获取 var doc = win.document; //这里获取不到 } document.domain = "example.com"; </script> //http://example.com/b.html <iframe id="iframe"onload="onLoad()"> <script> //http://example.com/b.html document.domain = "example.com"; </script> </iframe>
window.name
特征为: 在一个窗口的生命周期内,窗口载入的所有页面都共享一个window.name,而每个页面对window.name都有读写的权限。
window.name值只能为字符串形式,一般容量为2M。
window.postMessage
HTML5新特性
<!-- 这是http://test.com/a.html --> <script> function onLoad(){ var iframe = document.getElementById('iframe'); var win = iframe.contentWindow; win.postMessage('来自页面a的消息', '*'); } </script> <iframe id="iframe" src="http://www.test.com/b.html" onload="onLoad()"></iframe>
<!-- 这是页面http://www.test.com/b.html --> <script> window.onmessage = function(e) { //注册message事件接收消息 e = e || event; alert(e.data); } </script>
js中几种实用的跨域方法原理详解
老生常谈的话题,今天来总结一下。
谈到跨域就必须说一说“同源策略”:
JSONP
document.domain
此时修改
document.domain
可以实现框架间的跨域。window.name
特征为: 在一个窗口的生命周期内,窗口载入的所有页面都共享一个
window.name
,而每个页面对window.name
都有读写的权限。window.name
值只能为字符串形式,一般容量为2M。window.postMessage
HTML5新特性