您的位置:首页 > Web前端 > JavaScript

JS跨域调用之document.domain--相同基础域名页面之间的调用

2016-04-26 02:15 465 查看
最近项目需要跨域调用JS,整理一下相关知识,写几个帖子记录一下学习历程。

例子只需要1个tomcat即可,这里我的tomcat端口都改成80了。

背景:浏览器在执行Javascript时,出于对安全性的考虑,禁止两个或者多个不同域的页面进行互相操作。

相同域的页面在相互操作的时候不会有任何问题。

如下例子:文件放置于%TOMCAT_HOME%/webapps/domain/目录下

1. parent.html

Html代码


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>parent</title>

<script>

// document.domain = "wwwcomy.com";

function parentFunction() {

alert('function in parent');

}

function callChild() {

child.window.childFunction();

/*

child 为iframe的name属性值,

不能为id,因为在FireFox下id不能获取iframe对象

*/

}

</script>

</head>

<body>

<input type="button" name="call child" value="call child" onclick="callChild()"/>

<br/><br/>

<!--<iframe name="child" src="http://d1.wwwcomy.com/domain/child.html" >-->

<iframe name="child" src="child.html" >

</iframe>

</body>

</html>

2.child.html

Html代码


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>child</title>

<script>

// document.domain = "wwwcomy.com";

function childFunction() {

alert('function in child');

}

function callParent() {

parent.parentFunction();

}

</script>

</head>

<body>

<input type="button" name="call parent" value="call parent" onclick="callParent()"/>

</body>

</html>

通过localhost/domain/parent.html访问,则可以在子页面和父页面之间相互调用,点击按钮即可看到效果。

接下来我们模拟不用域名的调用,初步我们先处理相同基础域名这个前提下,页面之间的调用,即同顶级域名的不同二级域名之间的调用,如:

d1.wwwcomy.com/domain/parent.html



d2.wwwcomy.com/domain/child.html

首先需要修改本地域名映射文件hosts,XP系统此文件地址在C:\WINDOWS\system32\drivers\etc\hosts,win7与linux请google

添加两个域名映射:

127.0.0.1 d1.wwwcomy.com

127.0.0.1 d2.wwwcomy.com

接下来将parent.html中iframe的src替换为注释的那一段。

此时我们在浏览器中输入d2.wwwcomy.com/domain/parent.html即可访问到对应页面,这样就可以模拟 d2.wwwcomy.com 与 d1.wwwcomy.com两个二级域名页面之间的调用了。

如果没有去掉document.domain 这行的注释,浏览器会报错,chrome中的报错信息为

引用

Unsafe JavaScript attempt to access frame with URL http://d1.wwwcomy.com/domain/child.html from frame with URL http://d2.wwwcomy.com/domain/parent.html. Domains, protocols and ports must match.

即不安全的JS调用。

接下来取消注释parent与child页面中的 document.domain 这行代码,发现JS现在可以相互调用了。

注意两个文件都需要这行代码,如果依旧报错请查看是不是由于浏览器的缓存问题。

下面是对document.domain的使用说明和限制条件:

域名必须属于同一个基础域名!而且所用的协议,端口都要一致,否则无法利用document.domain进行跨域

例子中的基础域名就是"wwwcomy.com",这个域名不能随意指定的,也就是说,如果我们把刚才例子中的document.domain设置为"sina.com"是会报参数无效的错误的。

通过这种方法,就可以实现同一个基础域名下两个二级域名页面之间JS的跨域相互调用。后面的帖子会介绍其他跨域解决方案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: