iframe 跨域解决跨域带参同源代理带参

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>

亲测好用,如果有别的实现方式,忘留言谢谢

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、iframe 定义和用法 iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。 HTML 与 X...
    _双眸阅读 7,200评论 0 1
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    Yaoxue9阅读 5,117评论 0 6
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    他方l阅读 4,709评论 0 2
  • 什么是跨域 跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实...
    HeroXin阅读 4,286评论 0 4
  • 元素会创建包含另外一个文档的内联框架(即行内框架); 一、align 属性(不赞成) align属性规定ifram...
    puxiaotaoc阅读 19,861评论 0 14