Page domain relationship :
The main page a.html belongs to domain A: www.taobao.com
The iframed page b.html belongs to domain B: www.alimama.com, assuming address: http://www.alimama.com/b.html
Realization effect :
The page a.html under the A domain name is embedded into the page b.html under the B domain name through an iframe. Since the width and height of b.html are unpredictable and can change, the iframe in a.html needs to be adaptively sized.
Nature of the problem:
js has a problem with cross-domain iframe access, because in order to control the height and width of the iframe in a.html, you must first read the size of b.html. A and B do not belong to the same domain. For security reasons, the browser makes js Cross-domain access is limited, and the height and width of b.html cannot be read.
Solution:
Introducing proxy pages c.html and a.html belong to the same domain A. c.html is a good intermediate proxy page provided under domain A. Assume that the address of c.html is: www.taobao.com/c.html, which is responsible for reading Get the width and height values in location.hash, and then set the width and height of the iframe in a.html in the same domain as it.
The code is as follows:
a.html code
First, b.html is introduced through iframe in a.html
<iframe id=”b_iframe” height=”0″ width=”0″ src=”http://www.alimama.com/b.html” 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");
c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //http://www.taobao.com/c.html#width|height”
}
</script>
<!–js reads the width and height of b.html, and sets the read width and height into the hash of the src of the intermediate proxy page c.html in the same domain as a.html–>
<iframe id=”c_iframe” height=”0″ width=”0″ src=”http://www.taobao.com/c.html” 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>
The iframe in a.html can be adapted to the width and height of b.html.
Other similar js cross-domain operation problems can also be solved according to this idea.
Original text: http://ued.alimama.com/?p=197