![18468891-5616847e3d225bd1.png](https://upload-images.jianshu.io/upload_images/18468891-5616847e3d225bd1.png)
a-agent-b
a.com 中的iframe.src是b.com, 不同域名访问不到contents();
中间使用agent.html作为代理,agent.html是b.com中增加的隐藏iframe,域名必须是a.com
页面如下:
a.com/index.html
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>a.com/index.html</title>
</head>
<body>
<iframe src="http://b.com/index.html"
id="A"
frameborder="0"
scrolling="no"
width="100%"
style="border: 0px;margin: 0">
</iframe>
</body>
</html>
b.com/index.html
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>b.com/index.html</title>
</head>
<body>
----嵌入的主体内容----
----嵌入的主体内容end----
<iframe
id="B"
height="0"
width="0"
src="http://a.com/agent.html" style="display:none">
</iframe>
<script type="text/javascript">
(function(){
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var B= document.getElementById("B");
B.src = B.src + "#" + b_width + "|" + b_height; // 这里通过hash传递b.htm的宽高
console.log(document.body.scrollWidth,B.src)
})();
</script>
</body>
</html>
a.com/agent.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var A = window.parent.parent.document.getElementById("A");
var hash_url = window.location.hash;
if(hash_url.indexOf("#")>=0){
var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
A.style.width = hash_width;
A.style.height = hash_height;
}
</script>
</head><body></body></html>
亲测好用,如果有别的实现方式,忘留言谢谢