Mais conteúdo relacionado
iframe communication in JavaScript
- 5. Same Domain, Different Subdomain
www.a.com - a.html
document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://labs.a.com/b.html';
document.body.appendChild(ifr);
ifr.onload = function() {
var doc = ifr.contentDocument || ifr.contentWindow.document;
alert(doc.getElementById('header'));
};
labs.a.com - b.html
document.domain = 'a.com';
- 6. Cross Domain - location.hash
localhost - exA.html
function sendToIframe() {
var data = 'HelloWorld',
url = 'http://jsbin.com/lazacizi/2#';
document.getElementById('myIframe').setAttribute('src', url+data);
};
function checkHash() {
var data = location.hash ? location.hash.substring(1):'';
if (data) {
document.getElementById('msg').innerHTML = 'iframe said: ' + data;
};
};
setInterval(checkHash, 2000);
<iframe id="myIframe" src="http://jsbin.com/lazacizi/2"></iframe>
- 7. Cross Domain - location.hash
jsbin.com - exB.html
function checkHash() {
var data = location.hash ? location.hash.substring(1) : '',
url = 'http://localhost/iframe_example/location_hash/exBridge.html#',
sendData = 'HelloParent';
if (data) {
document.getElementById('test').innerHTML = 'Parent said: '+data;
document.getElementById('myIframe').setAttribute('src', url+sendData);
};
};
setInterval(checkHash, 2000);
<iframe id="myIframe"></iframe>
- 8. Cross Domain - location.hash
localhost - exBridge.html
parent.parent.location.hash = self.location.hash.substring(1);
- 9. Cross Domain - Html5 postMessage
localhost - postMessage.html
function callIframe() {
var ifr = document.getElementById('myIframe'),
targetOrigin = 'http://jsbin.com';
ifr.contentWindow.postMessage('Hello iframe !', targetOrigin);
};
<iframe id="myIframe" src="http://jsbin.com/damunuru/2"></iframe>
jsbin.com - iframe.html
window.addEventListener('message', function(e){
if (e.origin !== 'http://localhost') return;
document.getElementById('test').innerHTML = e.origin+' said: '+e.data;
}, false);