[size=medium] js跨域调用许多种解决方案,有document.domain+iframe、动态创建script和HTML5 postMessage等等。最近遇到了一些案例,需要调用iframe的脚本,而又不能使用document.domain来解决,这有一个比较有趣的解决跨域,原理是利用location.hash来进行传值.[/size]
[b]a.com下的1.html文件[/b]
[b]b.com下的2.html文件[/b]
[b]a.com下的1.html文件[/b]
<script type="text/javascript">
var url = "http://b.com/2.html";
var iframe = null;
window.onload = function(){
iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.width = "100%";
iframe.style.height = "1px";
iframe.style.border = "none";
document.body.appendChild(iframe);
}
function sendData(data){
try {
if (console.log) {
console.log('Send data '+data);
iframe.src = url + "#" + data;
}
} catch(e) {};
}
</script>
[b]b.com下的2.html文件[/b]
<script type="text/javascript">
var url = "http://b.com/2.html";
var iframe = null;
window.onload = function(){
setInterval(receiveData, 2000);
}
function receiveData(){
try {
var data = location.hash ? location.hash.substring(1) : '';
if (console.log) {
console.log('Receive the data is '+data);
}
} catch(e) {};
}
</script>