问题
I'm struggling with myself to figure out why my code works in a specific way ( rather than the other way) :
+----------------------------+
| jsfiddle |
| |
| +---------+ |
| | | |
| | jsbin | |
| +---------+ |
+----------------------------+
Goal :
jsfiddle
should connect to jsbin
and jsbin
should return data to jsfiddle
using window.name
( cross domain technique).
(Again --the code is working)
jsbin's
response is a Html page with :
<script>
window.name = 1*(new Date());
</script>
And here is the code for jsFiddle
:
/*1*/ var f;
/*2*/
/*3*/ function loadRequest()
/*4*/ {
/*5*/ f.onload = function ()
/*6*/ {
/*7*/ alert(f.contentWindow.name);
/*8*/ frame.parentNode.removeChild(frame);
/*9*/ }
/*10*/ f.src = 'about:blank';
/*11*/ }
/*12*/
/*13*/ $(".b").on('click', function ()
/*14*/ {
/*15*/ f = document.createElement('iframe');
/*16*/ f.name = framename = 'fetchData';
/*17*/ f.onload = loadRequest;
/*18*/ f.src = 'http://jsbin.com/AjUyoYU/8/quiet';
/*19*/ document.body.appendChild(f);
/*20*/ });
As you can see - the code works : http://jsfiddle.net/7Nawt/2/
So where is the question ?
Looking at line #17 , I do attach an onload
handler for the iframe
. (loadRequest
).
But the loadRequest
method - in turn --attaches again(!! --line #5) an onload
function.
I dont understand why it is working like this .
I mean : the common sense tells me that the loadRequest
method should be :
function loadRequest()
{
alert(f.contentWindow.name);
frame.parentNode.removeChild(frame);
}
But it is not working.
What am I missing ? ( any other attempts display : a cross domain error)
回答1:
You need to send the iframe window back to a domain that is accessible to the parent window before you check window.name
, otherwise you'll get the cross-domain error. So, after it loads and the remote page sets window.name
, you send it to about:blank
, which isn't subject to the same-origin policy, and then read window.name
from the parent window.
The first trick here is that window.name
sticks around no matter where you send the window. So, you send the window to a remote domain, let it set window.name
, send it back to an accessible domain, and then read it.
The second trick is that about:blank
is a happy environment for Both A
and B
. and so - no cross domain errors.
来源:https://stackoverflow.com/questions/19487729/cross-domain-using-window-name-double-onload-should-be-used