location.hash+iframe 跨域解决方案

xiaoxiao2021-02-28  103

利用location.hash和iframe可以解决完全跨域的问题。其原理是利用location.hash传值,创建定时器,坚持hash的变化,执行相应的操作。 下面我们来完成一个案例: 在bao.com域名下有个index.html, 在index.html中通过iframe引入hui.com域名下header.html。使index.html和header.html可以相互通信。

index.html代码:

<html> <meta charset="UTF-8" /> <h1>通过IFRAME 和 location.hash 进行javasript 跨域</h1> 引入header.html <iframe id="iframe" src="http://www.hui.com/header.html"></iframe> <input type="button" onClick="changecolor()" value="change color" id="btn" /> <script> var iframe = document.getElementById('iframe'); var _timeid = setInterval(checkHash, 1000);function checkHash() { switch (location.hash) { case '#mainred': document.getElementById("btn").style.color = "red"; break; } } function changecolor() { iframe.src = 'http://www.hui.com/huanhuba/modelWebsite/js/iframe/hash/header.html#red'; } </script> </html>

hui.com下的 header.html代码:

<html> <meta charset="UTF-8" /> <body> <a href="javascript:;" id="btn">点击改变主页面按钮颜色</a> <iframe src="http://www.bao.com/huanhuba/modelWebsite/js/iframe/hash/crossdomain.html" width="" height="" id="cdiframe" style="display: none;"></iframe> <script> var _timeid = setInterval(checkHash, 1000); function checkHash() { switch (location.hash) { case '#red': callback(); break; } } function callback() { document.getElementById("btn").style.color = "red"; } document.getElementById("btn").onclick = function(){ document.getElementById("cdiframe").src = document.getElementById("cdiframe").src + "#mainred"; }; </script> </body> </html>

现阶段index.html中可以更改引入的iframe的src的hash。header.html中通过定时器判断hash值的变化,做出相应的操作。但是在header.html不可以直接操作index.html的hash。如果直接用parent.locatin.hash = name;会出现 111111113324禁止跨域操作 此时需要引入一个代理文件(crossdomain.html),此文件与index.html同域,因此,index.html可以和crossdomian.html相互通信。通过在header.html中改变crossdomain.html的hash,在crossdomain.html中监听 hash的变化,在通过parent.parent.location.hash改变index.html的hash值。

crossdomain.html代码:

<html> <meta charset="UTF-8" /> <script> /****crossmain 和 index在同一域名下可以相互通信**************/ var _timeid = setInterval(checkHash, 1000); function checkHash(){ parent.parent.location.hash = self.location.hash.substring(1); } </script> </html>

location.hash + iframe跨域的优点: 1.可以解决域名完全不同的跨域 2.可以实现双向通讯

location.hash + iframe跨域的缺点: location.hash会直接暴露在URL里,并且在一些浏览器里会产生历史记录,数据安全性不高也影响用户体验。另外由于URL大小的限制,支持传递的数据量也不大。

转载请注明原文地址: https://www.6miu.com/read-34137.html

最新回复(0)