您的位置:首页 > 大数据 > 人工智能

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

2017-03-11 12:32 411 查看
如果两个网页不同源,就无法拿到对方的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.htmldocument.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" onload="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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: