标签:这一 内容 pre add sharp cti window csharp tor
1.document.domain跨域
场景:http://a.xxx.com/A.htm 的主页面有一个<iframe src="http://b.xxx.com/B.htm"></iframe>,两个页面的js如何进行交互?
这种跨子域的交互,最简单方式就是通过设置document.domain。
只需要在A.htm与B.htm里都加上这一句document.domain = ‘xxx.com‘,两个页面就有了互信的基础,而能无碍的交互。
实现方式简单,并且主流浏览器都支持IE6+、Firefox、Chrome等.
适用:同一个主域名下,不同子域之间的交互。
用法:a页面
b页面
<script>
function setwindowname()
{
window.name=‘a页面设置的‘;
window.location.href="http://172.16.103.22/kuayu/6window.name.html";
}
</script>
<body>
<button onclick="setwindowname()">
click window.name
</button>
</body>
b页面
<script>
alert(window.name);
</script>
<body>
</body>
这样a页面设置的值传入到了b页面。
3. html5 window.postMessage
window.postMessage(message,targetOrigin) 方法是html5新引进的特性,可以使用它来向其它的window对象发送消息,无论这个window
对象是属于同源或不同源,目前IE8+、FireFox、Chrome、Opera等浏览器都已经支持window.postMessage方法。
调用postMessage方法的window对象是指要接收消息的那一个window对象,该方法的第一个参数message为要发送的消息,类型只能为字符串;
第二个参数targetOrigin用来限定接收消息的那个window对象所在的域,如果不想限定域,可以使用通配符 * 。
需要接收消息的window对象,可是通过监听自身的message事件来获取传过来的消息,消息内容储存在该事件对象的data属性中。
用法:a页面
<body>
<div style="width:300px;height:200px;">
<iframe id="proxy" src="http://172.16.103.22/kuayu/5postMessage.html" style="display: block"></iframe>
</div>
<button onclick="postMsg()"> click</button>
<script type="text/javascript">
var obj = {
msg: ‘this is come page a ‘
}
function postMsg() {
var iframe = document.getElementById(‘proxy‘);
var win = iframe.contentWindow;
win.postMessage(obj, ‘http://172.16.103.22‘);
}
</script>
</body>
b页面:
<script type="text/javascript">
window.addEventListener(‘message‘, function (event) {
console.log(‘received response: ‘, event.data);
var ps = document.getElementById(‘pid‘);
ps.textContent = event.data.msg;
console.log(ps);
}, false);
</script>
b页面可以接收到a页面的消息。
此外还有通过 flash 、服务器是指代理、img等方法实现。
标签:这一 内容 pre add sharp cti window csharp tor
原文地址:http://www.cnblogs.com/yxcoding/p/7286930.html