1、cookie与setInterval
在A界面设置一个使用setInterval定时器不断刷新,检查Cookies的值是否发生变化,如果变化则刷新Cookie。由于Cookie在同域可度,所以页面B审核的时候,改变Cookie的值,页面A可以获得改变的值。
缺点:相当浪费资源,实现方案不够优雅。
2、SharedWorker
HTML5的Web Worker可以分为两种不同线程类型,一种是专用线程Dedicated Worker,一个是共享线程Shared Worker。
1、Dedicated Worker直接使用new Worker()即可创建,这种web Worker是当前页面专用。
2、SharedWorker 可以被多个window、标签页、iframe共同使用,但是要保证所有标签页是同源的(相同协议、主机和端口号)
3、iframe跨域
直接获取对方的Dom,适用于两个页面在同一个域:可以传递对象数据(对象数据使用 instanceof 做类型判断时有坑);参考 window.open;
// 父页面获取子iframedocument.getElementById('iframe的id').contentWindow.document// 子iframe获取父页面window.parent.document
4、window.name
浏览器有个window.name属性,这个属性特点是无论是否同源,只要在同一个窗口,前一个窗口设置了这个属性,后一个窗口就可以读取它。
父窗口先打开一个子窗口,载入不同源的网页,将网页信息写入window.name
window.name=data
子窗口跳回一个与主窗口同域的网址
window.location.href = 'http://parent.url.com/xxx.html';
然后,主窗口就可以读取子窗口的window.name
var data = document.getElementById('iframe的id').contentWindow.name;
优点:window.name容量大,可以放置非常长的字符串。
缺点:必须监听子窗口window.name属性的变化,影响网页性能。
5、postMessage
window.postMessage() 方法可以安全地实现跨源通信。广义上,一个窗口可以获得对另一个窗口的引用。
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: 其他窗口的一个引用,例如iframe的contentWindow属性、执行window.open()窗口对象。
message:将要发送给其他window的数据。它将会被结构化克隆算法序列化。(所以可以将数据对象传送
给目标对象
targetOrigin:指定哪些窗口可以接受消息事件。
var popup = window.open(...popup details...);
// 如果弹出框没有被阻止且加载完成
// 这行语句没有发送信息出去,即使假设当前页面没有改变location(因为targetOrigin设置不对)
popup.postMessage("The user is 'bob' and the password is 'secret'",
"https://secure.example.net");
// 假设当前页面没有改变location,这条语句会成功添加message到发送队列中去(targetOrigin设置对了)
popup.postMessage("hello there!", "http://example.org");
function receiveMessage(event)
{
// 我们能相信信息的发送者吗? (也许这个发送者和我们最初打开的不是同一个页面).
if (event.origin !== "http://example.org")
return;
// event.source 是我们通过window.open打开的弹出页面 popup
// event.data 是 popup发送给当前页面的消息 "hi there yourself! the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);
//当A页面postMessage被调用后,这个function被addEventListener调用
function receiveMessage(event)
{
// 我们能信任信息来源吗?
if (event.origin !== "http://example.com:8080")
return;
// event.source 就当前弹出页的来源页面
// event.data 是 "hello there!"
// 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把event.source
// 作为回信的对象,并且把event.origin作为targetOrigin
event.source.postMessage("hi there yourself! the secret response " +
"is: rheeeeet!",
event.origin);
}
window.addEventListener("message", receiveMessage, false);
6、JSONP
JSONP利用script标签的src属性中链接可以访问跨域js脚本,利用这个特性,服务端不再返回JSON格式的数据,而是返回一段函数的js代码,在src中调用,实现跨域。
缺点:只支持get
7、CORS
服务端设置Access-Control-Allow-Origin即可,前端无需配置。如果带cookie参数,前后端后需要设置。
