Home >Web Front-end >JS Tutorial >JavaScript implements iframe automatic height adjustment and cross-domain cross-domain between different main domain names_javascript skills

JavaScript implements iframe automatic height adjustment and cross-domain cross-domain between different main domain names_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:13:121375browse

Everyone knows that Js has a same-origin policy, which means that iframes nested in different main domain names do not allow Js to communicate.

For example, I have a website, and I want to embed its website pages in the website. Then I can use iframe to reference the address of the third-party website.

However, the problem is that the height of the iframe is fixed and cannot be well integrated with third-party websites. For example, the third-party website uses a waterfall flow plug-in. To automatically calculate the height during rolling loading, let’s talk about cross-domain first: iframe main Domain names have different cross-domain methods. If an iframe is placed in the website A.com B.com A and references B.com, in this case, the Js in B.com cannot access A.com. Cross-domain JS must have the same origin, that is, the same main domain name, so what should we do?

We can introduce an iframe in B.com, let’s call it C for now. This iframe loads a web page in A.com. In this way, if the same source exists, the web page in the iframe in B.com can communicate with A.com. Next, as long as B and C communicate, let C communicate with A to complete the B->A communication, so that when the height of B changes, C is notified, and C notifies A to adjust the iframe height.
Communication between B and C can actually be achieved through the url address. The B.com iframe is set to hidden, and C can receive it when the src address is changed.

Stop talking nonsense and get on with the code

A.com/index.html

<html>
  <script src="{$smarty.const.STATIC_URL}/js/jquery-1.7.1.min.js"></script>
  <script>
   var test = function() {
     $('#h1').html('test');
   }
   </script>
<body>
<h1 id="h1">nba.alltosun.net</h1>
<iframe id="ifm" width="760" height="100" src="http://***.sinaapp.com/"></iframe>
</body>
</html>


B.com/index.html

<html>
<head></head>
<body>
  <h1>**.appsina.com</h1>
  <button id="button">设置高度</button>
  <div id="div" style="height:200px;display:none;"></div>
  <script src="http://nba.alltosun.net/js/jquery-1.7.1.min.js"></script>
  <script>
  $(function(){
    window.ifrH = function(e){
      var searchUrl = window.location.search;
      var b = null;
       
      var getParam = function(url, param) {
        var q = url.match(new RegExp( param + "=[^&]*")),
        n = "";
        if (q && q.length) {
          n = q[0].replace(param + "=", "");
        }
        return n;
      }
       
      var f = getParam(searchUrl,"url"),
        h = getParam(searchUrl, "ifmID"),
        k = getParam(searchUrl, "cbn"),
        g = getParam(searchUrl, "mh");
       
 
      var iframeId = 'testiframe';
      var iframe = document.getElementById(iframeId);
      var divId = 'alltosun';
       
      if (!iframe){
        var iframe = document.createElement('iframe');
        iframe.id = iframeId;
        iframe.style.display = "none";
        iframe.width = 0;
        iframe.height = 0;
        document.body.appendChild(iframe);
      }
       
      if (e && e.type == "onload" && h) {
        b.parentNode.removeChild(b);
        b = null;
      }
       
      if (!b) {
        b = document.createElement("div");
        b.id = divId;
        b.style.cssText = "clear:both;"
        document.body.appendChild(b);
      }
       
      var l = b.offsetTop + b.offsetHeight;
      iframe.src = (decodeURIComponent(f) || 
          "http://*****/test2") + "&h=" + l + "&ifmID=" + (h || "ifm") + "&cbn=test" + "&mh=" + g + "&t=" + ( (+ new Date()));
       
      if (e && e.type =="onload") {
        window.onload = null;
      }
    }
     
    window.onload = function() {
      ifrH({type: "onload"});
    }
     
    // ifrH();
    $('button').click(function(){
      $('div').show();
      ifrH();
    })
  })
  </script>
</body>
</html>


C proxy file

<script>
var search = window.location.search,
getSearchParam = function (search, key) {
  var mc = search.match (new RegExp ( key + "=([^\&]*)") ),
    ret="";
  mc && mc.length && (ret = mc[0].replace( key + "=",""));
  return ret;
},
// 参数h 
h = getSearchParam(search,"h"),
ifmID = getSearchParam(search,"ifmID"),
cbn = getSearchParam(search,"cbn"),
// 宽高
mh = getSearchParam(search,"mh") || h,
isFunction = function(fn){
  return !!fn && !fn.nodeName && fn.constructor != String 
      && fn.constructor != RegExp && fn.constructor != Array 
      && (/function/i).test(fn + "");
};
 
try{
  if(parent && parent.parent){
    ifm = parent.parent.document.getElementById(ifmID);
    ifm && mh && (ifm.height=mh);
    fn=parent.parent[cbn];
    isFunction(fn) && fn.call();
    ifm=null;
  }
}catch(ex){
  console.log(ex);
}
 
</script>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn