获取DOM跨域的解决方案——document.domain、window.name、window.postMessage

如果两个网页不同源,就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。 获取DOM的跨域解决方案: (1)如果两个窗口一级域名相同,...

如果两个网页不同源,就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。




获取DOM的跨域解决方案:


(1)如果两个窗口一级域名相同,只是二级域名不同,那么设置document.domain属性,即可跨域获取DOM。


例如,可以在http://www.msnova.net/a.html和http://blogs.msnova.net/b.html两个文件中分别加上document.domain = “msnova.net”;然后通过a.html文件中创建一个iframe,去控制iframe的contentDocument,这样两个js文件之间就可以“交互”了。这种办法只能解决主域相同而二级域名不同的情况。


http://blogs.msnova.net/b.html



document.domain = "msnova.net";

http://www.msnova.net/a.html


document.domain = "msnova.net";
var ifr = document.createElement('iframe');
ifr.src = 'http://blogs.msnova.net/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
var x = ifr.contentDocument;
alert(x.getElementsByTagName("h1")[0].childNodes[0].nodeValue); //操作b.html
ifr.onload = null;
}



(2)否则,可以通过window.name和window.postMessage跨域获取DOM


2-1)window.name


http://JavaScript.exam.com/text.html:

<!DOCTYPE html>  
<html>  
    <head>  
    </head>  
    <body>  
        <script>  
window.name = "value";
</script>  
    </body>  
</html>

http://catagory.exam.com/text.html:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<iframe id="iframe" οnlοad="loading()" src="http://javascript.exam.com/text.html"></iframe>
<script>
var load = false;
function loading() {
if (load == false) {
// 同域处理,请求后会再次重新加载iframe
document.getElementById('iframe').contentWindow.location = 'http://catagory.exam.com/index.html';
load = true;

else {
// 获取window.name的内容,注意必须进行同域处理后方可访问!
alert(document.getElementById('iframe').contentWindow.name); //输出:value
load = false;
}
}
</script>
</body>
</html>



2-2)window.postMessage

http://catagory.exam.com/text.html:

<!doctype html>
<html>
<head>
</head>
<body>
<iframe id="iframe" src="http://JavaScript.exam.com/Test/text.html"></iframe>
<script>
window.onload = function() { 
document.getElementById('iframe').contentWindow.postMessage('Hello', "http://JavaScript.exam.com");  
};  
</script>
</body>
</html>

http://JavaScript.exam.com/text.html:

<!DOCTYPE html>  
<html>  
    <head>  
        <title></title>  
    </head>  
    <body>  
        <script>  
window.addEventListener('message', function(event){  
// 通过origin属性判断消息来源地址  
if (event.origin == 'http://catagory.exam.com') 
alert(event.data); //输出:Hello 
}, false); 
</script>  
    </body>  
</html>

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
廖雪
廖雪

78 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章