Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Solve the problem of location.hash cross-domain iframe adaptation


May 30, 2021 Article blog



Page domain relationships:

Main page a.html Domain A: www.taobao.com

Page b of iframe.html Domain B: www.alimama.com, assuming address: https://www.w3cschool.cn/

To achieve the effect:

Page a under A domain name a.html embeds page b .html under B domain name via iframe, because the width and height of b.html is unpredictable and changeable, so the iframe adaptive size in the a .html is required.

The nature of the problem:

js for cross-domain iframe access problems, because to control the height and width of iframe in a .html must first read the size of the b.html, A, B does not belong to the same domain, browser for security reasons, so that js cross-domain access is limited, can not read the height and width of b .html.

solution:

The introduction of agent page c.html and a.html belongs to the same domain A, c .html is a good intermediate proxy page under domain A, assuming that c .html address: www.taobao.com/c.html, it is responsible for reading the values of the width and height inside location.hash, and then set the width and height of the iframe in the a .html under its domain.

The code is as follows:

a.html code

First, a .html introduces a b-.html through iframe

<iframe id=”b_iframe” height=”0″ width=”0″ src=”https://www.w3cschool.cn/ frameborder=”no” border=”0px” marginwidth=”0″ marginheight=”0″ scrolling=”no” allowtransparency=”yes” >

</iframe>

b.html code

<script type=”text/javascript”>

var b_width = Math.max(document.documentElement.clientWidth,document.body.clientWidth);

var b_height = Math.max(document.documentElement.clientHeight,document.body.clientHeight);

var c_iframe = document.getElementById(”c_iframe”); //liehuo.net

c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //https://www.w3cschool.cn/#width|height”

}

</script>

<!–js读取b.html的宽和高,把读取到的宽和高设置到和a.html在同一个域的中间代理页面车c.html的src的hash里面–>

<iframe id=”c_iframe” height=”0″ width=”0″ src=”https://www.w3cschool.cn/” style=”display:none” ></iframe>

c .html code

<script type=”text/javascript”>

var b_iframe = parent.parent.document.getElementById(”b_iframe”);

var hash_url = window.location.hash;

var hash_width = hash_url.split(”#”)[1].split(”|”)[0]+”px”;

var hash_height = hash_url.split(”#”)[1].split(”|”)[1]+”px”;

b_iframe.style.width = hash_width;

b_iframe.style.height = hash_height;

</script>

a iframe in .html can be adapted to the width and height of b .html.
Other js-like cross-domain operation issues can also be solved along these lines