Cross-domain height adaptation of an IFRAME (by nesting this domain page in a cross-domain page)

Source: Internet
Author: User

The internship soon received a task to nest another project's Web page in a Web page. I thought it was an easy thing to do and the result was tested by my sister. Many times and I talk about this high-level fixed causes the IFRAME scroll bar how ugly, the impact on the overall project how bad. Because of the cross-domain reason, this demand has been dragged for a long time, it is really painful thing. Finally, I took care of the order before I left the company.

I will write down my research process here for your reference.

First you need to know what is the same domain and what is the cross-domain:

URL Description whether to allow communication
http://www.a.com/a.js
http://www.a.com/ B.js
under the same domain name allow
http://www.a.com/lab/a.js
Http://www.a.com/script/b.js
different folders under the same domain name Allow
http://www.a.com:8000/a.js
http://www.a.com/b.js
same domain name, different ports do not allow
http://www.a.com/a.js
https://www.a.com/b.js
same domain name, different protocol does not allow
http://www.a. Com/a.js
http://70.32.92.74/b.js
domain name and domain name corresponding IP do not allow
http://www.a.com/a.js
H Ttp://script.a.com/b.js
primary domain, subdomain different not allowed
http://www.a.com/a.js
http://a.com/ B.js
Same domain name, different level two domain name (ibid.) not allowed
http://www.cnblogs.com/a.js
HTTP://WWW.A.COM/B.J s
different domain names not allowed
This form is from here.
Note : On cross-domain issues, domains are only identified by URLs, and no additional parsing is done, for example, the 127.0.0.1 is a cross-domain from the browser in the case of localhost.
Under the same domain name, different ports, even on the same server also counted cross-domain, this is the situation I encountered.

Contentwindow

At first, because of the inability to complete cross-domain high-level adaptation, I can only give up cross-domain situations, only to do a highly adaptive under the same domain, which is the first and second case in the table.

In the same domain, the following code obtains the window of the IFRAME page:

document.getElementById ("MyFrame"). Contentwindow

After you get the window of the child page, you can manipulate the child page in the parent page. If cross-domain, then the browser will error.

Child page Gets parent page window:

Parent.window

Midway

But this is not the only way to get the approval of the test sister, and then carefully study the cross-domain height adaptive.

Its principle is not complex, in the parent page nested sub-page, nested in the child page with the parent page of the same domain Proxy page, because the parent page and the proxy page is the same domain, the parent page and the proxy page can achieve communication.

When a child page assigns its own height to the URL of the proxy page, the proxy page gets the data from its own URL to the parent page, and the parent page changes the iframe height of the child page. Thus achieving the high cross-domain adaptive of the IFRAME.

That's a little bit more about it, the following schematic diagram:

Pictures from here.

Of course, to achieve cross-domain height adaptive There is a premise, you must be able to manipulate the sub-page, that is, the sub-page is also you can control, if you want to baidu.com as a sub-page to achieve a highly adaptive this can not be achieved.

Add the following code to the sub-page:

/** * Midway Page Height Adaptive code * After the SRC address of the parent page iframe add Midway_url as a clue * One can realize the function, the second is to realize the dynamic loading JS, to achieve this function of the general * Midway_url for the need to embed the target page to achieve the function of JS Address*/;(function() {    varStr_midway_url = "Midway_url"; //get midway_url from the URL    varMidway_reg =NewREGEXP (Str_midway_url + "= ([^&]*) (&|$)"); varMidway_res =Window.location.search.match (Midway_reg); //get Midway_url from Cookies    varcookies =Document.cookie; varoffset =Cookies.indexof (Str_midway_url); //If a URL exists, the cookie is obtained and stored    //If the cookie is present, obtain    varMidway_url = ' '; if(midway_res) {Midway_url= Unescape (midway_res[1]); Document.cookie= Str_midway_url + "=" +Midway_url; } Else if(Offset! =-1) {offset+ = Str_midway_url.length + 1; varEnd = Cookies.indexof (";", offset); End= (End! =-1)?end:cookies.length; Midway_url=cookies.substring (offset, end); }    //The JS of the target address is introduced into the page to realize the function    if(midway_url) {varDom_script = document.createelement ("Script"); DOM_SCRIPT.SRC=Midway_url;    Document.body.appendChild (Dom_script); };}) ();

The parent page introduces a sub-page via an IFRAME tag, and adds an additional parameter midway_url after the URL of the child page. In the sub-page JS to add the above code, the core code is a judgment statement: If the URL or cookie exists in this parameter, then continue to the next step, if it does not exist will not continue.

Generally about IFRAME cross-domain articles are in the sub-page directly through the IFRAME to introduce proxy pages, there are several drawbacks:

    1. Code redundancy. If you access the sub-page directly, the Sub-page proxy page becomes redundant code.
    2. Lack of flexibility. If the sub-page is also accessed by other pages, then the adaptive functionality cannot be implemented.

The midway.js is passed to the child page by the URL parameter, and the sub-page determines that it is being referenced. Child page creation <script> tags introduced midway.js.

Some of the pages because some relationships need self-refresh, so that the parameters in the URL is lost, it will be midway_url stored in the cookie persisted.

The midway.js that are introduced into the sub-page are the following:

/** * This is the Quilt page reference Js-midway.js * Midway.js must be in the same directory as midway.html*/;(function() {    varMidway ={init:function() {            varstr_midway_id = "Midwayagentpage"; varMidway_url = This. Getmidwayurl ();  This. CREATEMIDWAYIFR (str_midway_id, Midway_url);  This. SETHEIGHT2IFR (str_midway_id, Midway_url); },        //creates a proxy iframe in a sub-page that points to the midway.html of the same domain as the parent pageCREATEMIDWAYIFR:function(str_midway_id, midway_url) {varMIDWAY_IFR = document.createelement ("iframe"); Midway_ifr.id=str_midway_id; MIDWAY_IFR.SRC=Midway_url; Midway_ifr.style.display= "None";        Document.body.appendChild (MIDWAY_IFR); },        //timed to append the target height value to the SRC address of the agent IFrame #SETHEIGHT2IFR:function(str_midway_id, Midway_url) {setinterval (function() {                //here to get the target height, not directly take the body height, should be in the content of the jacket layer Div placed inside the body                varTarget_height = document.getElementsByTagName ("div") [0].scrollheight; varMIDWAY_IFR =document.getElementById (str_midway_id); if(MIDWAY_IFR) {midway_ifr.src= Midway_url + ' # ' +Target_height; }            }, 66); },        //get Midway_url return http://.../midway.html from CookiesGetmidwayurl:function() {             varStr_midway_url = "Midway_url"; varcookies =Document.cookie; varoffset =Cookies.indexof (Str_midway_url); varMidway_url = ' '; if(Offset! =-1) {offset+ = Str_midway_url.length + 1; varEnd = Cookies.indexof (";", offset); End= (End! =-1)?end:cookies.length; Midway_url=cookies.substring (offset, end); }            if(midway_url) {//The original midway_url for ... midway.js, here instead ... mindway.html                returnMidway_url.slice (0, Midway_url.lastindexof ("/")) + "/midway.html";    }        }    }; Midway.init ();}) ();

The main function of Midway.js is to create an IFRAME in the sub-page to introduce midway.html, and assign the actual height of the sub-page to the SRC of the IFRAME according to Midway_url.

The code for the midway.html introduced in the sub-page is as follows:

<!DOCTYPE HTML> <HTML> <Head>    <title>Midway</title></Head> <Body> <Script>window.onload= function() {    //get an IFRAME from the parent page    varIFR=Parent.parent.document.getElementById ('MyFrame'); //to get the target height from the URL at a timed time    //and give the target iframe the corresponding height to achieve adaptiveSetInterval (function() {var h = location.hash? Location.hash.substring (1): 0;if (h) ifr.style.height = h + ' px ';    },  the);};</Script> </Body> </HTML> 

Midway.html is equivalent to a transit point, because midway.html and the parent page can communicate with each other, so the height of the iframe in the parent page is changed in real time by midway.html.

The code for the IFRAME in the parent page is as follows:

<iframeID= "MyFrame"name= "MyFrame"width=100%Height=100%frameborder=0marginheight=0marginwidth=0scrolling= "No"></iframe><Script>$ (document). Ready (function() {        //the URL for midway.js here        //Note: Midway.js and midway.html should be in the same folder        varMidway_url= "Http://.../midway.js"; //After you add the Midway.js address to the URL of the destination page        $("#myframe"). attr ("src", "http://...&midway_url=" +Midway_url); });</Script>

Although it is more around, but the realization of the test sister needs to function, is also considered a perfect solution to the task.

Document.domain

The problem is solved at the same time, also did some other research, also writes below.

In the case of different subdomains in the same primary domain, such as news.a.com and a.com or news.a.com and blog.a.com, you can communicate with each other by JS for the settings of the primary domain:

Document.domain = "A.com"

This allows you to use the first method for free communication between two pages.

Window.name

The Window.name property can set or return a string that holds the name of the window. It is convenient to use this property to do the cross-domain value transfer of the IFRAME.

See here for specific instructions.

Its principle is similar to Midway, Midway uses a proxy page that is the same domain as the parent page, By changing its location.hash to achieve cross-domain values, this is achieved by changing the window.name to achieve cross-domain values, essentially through proxy iframe as a mediator.

The data that Location.hash can transmit is very limited.

Window.name can deliver more data (typically up to 32M or so in size, 2m,ie and Firefox), and data formats can be customized (JSON).

Reference:

Beginners learn to cross-domain iframe

JavaScript cross-domain Summary and solutions

Universal solution for IFRAME cross-domain communication

The pound sign of the URL

Https://developer.mozilla.org/zh-CN/docs/Web/API/Window/name

Https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash

Cross-domain height adaptation of an IFRAME (by nesting this domain page in a cross-domain page)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.