JavaScript Framework (IFRAME) Mutual transfer between the program code

Source: Internet
Author: User
Tags hash delete cache net domain

Many of the frameworks have a parent-child relationship that is cumbersome to operate, and many students often have this sad code:

The code is as follows Copy Code

Window.parent.document.getElementById ("main")
. ContentWindow.document.getElementById (' input '). Value =
document.getElementById (' Myiframe ')
. ContentWindow.document.getElementById (' S0 '). Value;


Look at a case I made myself.


An IFRAME invocation includes the following: (call contains HTML DOM,JS global variable, JS method)

The main page calls the IFRAME;

The IFRAME page calls the main page;

The main page contains the IFRAME between the calls;

Main points of knowledge


1:document.getelementbyid ("II"). After Contentwindow gets the IFrame object, you can get the window object that the iframe contains the page through Contentwindow. Then you can access the page elements normally;


2:$ ("#ii") [0].contentwindow If you use the jquery selector to obtain an IFRAME, you need to add a "0";


3:$ ("#ii") [0].contentwindow.$ ("#dd"). Val () can then use the jquery selector for page operation after getting the window object of the IFRAME;


4:$ ("#ii") [0].contentwindow.hellobaby= "DSAFDSAFSDAFSDAFSDAFSDAFSADFSADFSDAFSADFDSAFFDSAAAAAAAAAAAAA"; Can pass the parameter to the IFRAME page in this way, can obtain the value in the IFRAME page Window.hellobaby, Hellobaby is the custom variable;


5: In the IFRAME page through parent can get the main page window, then you can normally access the elements of the Father page;


6:parent.$ ("#ii") [0].contentwindow.ff; The same level of IFRAME between the page calls, you need to get the Father's window, and then call the same-level iframe to get the window to operate;

Source


Main.html

The code is as follows Copy Code

? <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> Show Chart </title>
<script src= "/jquery-1.7.1.min.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
var gg= "Dsafdsafdsafdsafsdaf";
function GgMM () {
Alert ("2222222222222222222222222222222");
}
function Calliframemethod () {
document.getElementById ("II"). Contentwindow.test ();
$ ("#ii") [0].contentwindow.test (); Use a jquery call to add a [0]
}
function Calliframefield () {
Alert ($ ("#ii") [0].contentwindow.ff);
}
function calliframehtml () {
Alert ($ ("#ii") [0].contentwindow.$ ("#dd"). Val ());
Alert ($ ("#ii") [0].contentwindow.document.getelementbyid ("DD"). Value);
Alert ($ ("#ii") [0].contentwindow.document.getelementbyid ("DD"). Value);
}
function Giveparameter () {
$ ("#ii") [0].contentwindow.hellobaby= "DSAFDSAFSDAFSDAFSDAFSDAFSADFSADFSDAFSADFDSAFFDSAAAAAAAAAAAAA";
}
</script>
<body>
<a href= "#" onclick= "Giveparameter ();" > Parameter Pass </a>
<a href= "#" onclick= "Calliframemethod ();" > Invoke sub-iframe method </a>
<a href= "#" onclick= "Calliframefield ();" > Invoke sub-iframe variable </a>
<a href= "#" onclick= "calliframehtml ();" > Invoke sub-iframe component </a></br>
<iframe id= "II" src= "frame.htm" width= "100%" frameborder= "0" ></iframe>
<iframe id= "new" src= "newframe.htm" width= "100%" frameborder= "0" ></iframe>
</body>

Frame.htm

The code is as follows Copy Code
? <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title> Show Chart </title>
<script src= "Scripts/jquery-1.7.1.min.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >

var ff= "Adfdasfdsafdsafdsaf";
function Test () {
Alert ($ ("#dd"). Val ());
}
function Callmainfield () {
alert (PARENT.GG);
}
function Callmainmethod () {
PARENT.GGMM ();
}
function callmainhtml () {
Alert (parent.$ ("#ii"). attr ("id");
}
function GetParameter () {
alert (Window.hellobaby);
}
</script>
<body>
<a href= "#" onclick= "GetParameter ();" > Accept Parameters </a>
<a href= "#" onclick= "Callmainmethod ();" > Invoke sub-iframe method </a>
<a href= "#" onclick= "Callmainfield ();" > Calling main window variable </a>
<a href= "#" onclick= "callmainhtml ();" > Invoke sub-iframe component </a>
<input id= "dd" type= "text" value= "1111111111"/>
</body>

Brother IFrame Page newiframe.htm

The code is as follows Copy Code


<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd"
<meta http-equiv= "Content-type" content= "text/html; charset=utf-8"
<title > Display Chart </title>
<script src= "/jquery-1.7.1.min.js" type= "Text/javascript" ></SCRIPT>
<script type= "Text/javascript"
Function Calllevelframe () {
    var ff=parent.$ ("#ii") [0 ].CONTENTWINDOW.FF;
    alert (FF);
}
</script>
<body>
    <a href= "# onclick=" Calllevelframe (); " > Call Brother iframe</a>   
    <input id= "nn" type= "text" value= "SDAFSDFSA"/
</body>


In fact, this problem can be greatly simplified, the framework of the application of a fixed window is called Window.top, if we cache the data to this page, all the frames can be obtained, regardless of how the child page changes. There is no need to adopt cookies, and you do not need to adopt any HTML5 local database policy, you only need to refer to a JS file for each page, the following content:

The code is as follows Copy Code


 
var share = {

 /**
  * Cross-framework data sharing Interface
  * @param  {String}  stored data name
  * @param &n Bsp {any}   any data that will be stored (no this returns the queried data)
  */
 data:function (name, value) {
  var top = Window.top,
   cache = top[' _cache '] | | {};
  top[' _cache '] = CACHE;
  
  return value!== undefined? Cache[name] = Value:cache[name];
 },
 < br>  /**
  * Data sharing Removal Interface
  * @param  {String}  deleted data name
  */
 removedata:fun Ction (name) {
  var cache = window.top[' _cache '];
  if (Cache && Cache[name]) Delete Cache[name];
 }
 
};


 

This few lines of method can share any type of data for each frame page to read, it has nothing to do with the page name, hierarchy, even if the day frame page level is modified, you do not have to worry, it can work properly.

For example, if we can store shared data on page A:

The code is as follows Copy Code

Share.data (' MyBlog ', ' http://www.planeart.cn ');
Share.data (' Edittitle ', function (val) {
Document.title = val;
});

Then a frames page takes any data from page a

The code is as follows Copy Code

Alert (' My blog address is: ' + share.data (' MyBlog ');
var edittitle = share.data (' Edittitle ');
Edittitle (' I've got the data ');


Instance Kua-Field Operation

Settings for Document.domain+iframe
Examples of the same primary domain and different subdomains can be resolved by setting up a Document.domain method. The specific approach is to add document.domain = ' a.com ' to the two documents in Http://www.a.com/a.html and http://script.a.com/b.html respectively. And then through the a.html file to create an IFRAME to control the contentdocument of the IFRAME, so that two JS files can be "interactive". Of course this method can only solve the primary domain is the same and two domain name different situation, if you whimsical to the script.a.com Domian set for Alibaba.com that is obviously will be the error! The code is as follows:

The a.html on the www.a.com

The code is as follows Copy Code
Document.domain = ' a.com ';
var IFR = document.createelement (' iframe ');
IFR.SRC = ' http://script.a.com/b.html ';
Ifr.style.display = ' None ';
Document.body.appendChild (IFR);
Ifr.onload = function () {
var doc = Ifr.contentdocument | | Ifr.contentWindow.document;
To manipulate b.html here.
Alert (Doc.getelementsbytagname ("H1") [0].childnodes[0].nodevalue);
};

The b.html on the script.a.com

Document.domain = ' a.com '; This method applies to any page in {www.kuqin.com, kuqin.com, script.kuqin.com, css.kuqin.com} to communicate with each other.

Note: The domain default for a page is equal to Window.location.hostname. The main domain name is the domain name without www, for example a.com, the main domain name prefix is usually two level domain name or multi-level domain name, for example, www.a.com is actually a level two domain name. Domain can only be set as the primary domain name, you cannot set domain to c.a.com in b.a.com.

Problem:
1, security, when a site (b.a.com) is attacked, another site (c.a.com) will cause security vulnerabilities.
2, if a page to introduce multiple IFRAME, to be able to operate all IFRAME, you must have to set the same domain.
2. Create script dynamically
Although the browser prohibits Cross-domain access by default, it does not prohibit the use of JS files that refer to other domains in the page, and it is free to perform function (including action cookies, Dom, and so on) in the introduced JS file. This makes it easy to achieve full cross-domain communication by creating a script node. The specific procedure may refer to Yui's get Utility

It is interesting to judge whether the script node is loaded or not: IE can only pass the script's ReadyStateChange attribute, and the other browser is the script load event. The following are some of the methods used to determine the completion of script loading.

  code is as follows copy code
js.onload = Js.onreadystatechange = function () {
    if (!this.readystate | | this.readystate = = ' Loaded ' | | this.r Eadystate = = ' complete ') {
       //callback to execute here
         js.onload = Js.onreadystatechange = null;
   }
};

3. Using IFRAME and Location.hash
This method is more winding, but it can solve the problem of footstep replacement in the case of complete cross domain. The principle is to use Location.hash to carry out the value. In the Url:http://a.com#helloword ' #helloworld ' is location.hash, changes the hash does not cause the page to refresh, therefore may use the hash value to carry on the data transmission, certainly the data capacity is limited. Assume that the domain name a.com under the file cs1.html to and 111cn.net domain name under the cs2.html to pass information, cs1.html first create a hidden iframe,iframe to create an automatic src point 111cn.net under the Domain name cs2.html page, when the hash value Can be used for parameter transfer. Cs2.html responds to the request and then passes the data by modifying the cs1.html hash value (since two pages are not in the same domain ie, Chrome is not allowed to modify the value of Parent.location.hash, so it is possible to modify it with the help of an agent Iframe;firefox under the a.com domain name. At the same time, add a timer on the cs1.html, at intervals to determine whether the value of Location.hash has changed, a little change to get the hash value. The code is as follows:

First the file cs1.html file under a.com:

The code is as follows Copy Code

function Startrequest () {
var IFR = document.createelement (' iframe ');
Ifr.style.display = ' None ';
IFR.SRC = ' Http://www.111cn.net/lab/cscript/cs2.html#paramdo ';
Document.body.appendChild (IFR);
}

function Checkhash () {
try {
var data = Location.hash? Location.hash.substring (1): ';
if (Console.log) {
Console.log (' Now ', the data is ' +data ');
}
catch (e) {};
}
SetInterval (Checkhash, 2000);

Cs2.html under the 111cn.net domain name:

The code is as follows Copy Code

Simulate a simple parameter-handling operation
Switch (Location.hash) {
Case ' #paramdo ':
CallBack ();
Break
Case ' #paramset ':
Do something ...
Break
}

function CallBack () {
try {
Parent.location.hash = ' Somedata ';
catch (e) {
The security mechanism of IE and chrome cannot modify Parent.location.hash,
So to use a proxy iframe in the middle of the cnblogs domain
var ifrproxy = document.createelement (' iframe ');
Ifrproxy.style.display = ' None ';
IFRPROXY.SRC = ' Http://a.com/test/cscript/cs3.html#somedata '; Note that the file is under the "a.com" field
Document.body.appendChild (Ifrproxy);
}
}

. com under the domain name cs3.html

Because Parent.parent and itself belong to the same domain, you can change the value of its Location.hash
Parent.parent.location.hash = self.location.hash.substring (1); Of course, there are many drawbacks to this, such as data directly exposed to the URL, data capacity and type are limited, etc.

Related Article

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.