js实现网页间通信

来源:互联网 发布:linux 内核参数 编辑:程序博客网 时间:2024/05/20 22:40

在用window.open("a,html")后打开的网页后,在打开的a.html文件发现,opener是存在的,但是opener.document却是null;而window.parent和window.parent.document是有的,但是却取不出数据,很奇怪。由此,引出了两个问题:

1,opener和parent的联系和区别是什么?

2,如何进行父子界面的通信?(打开它的页面和这个页面间的通信)

3,如何进行页面间的通信?


一、opener和parent的联系和区别

1,opener和parent的概念

根据w3c school文档,opener 属性是一个可读可写的属性,可返回对创建该窗口的 Window 对象的引用。opener即谁打开我的,比如A页面利用window.open弹出了B页面窗口,那么A页面所在窗口就是B页面的opener,在B页面通过opener对象可以访问A页面。

parent相对简单,只有一句话:返回父窗口。

那么什么叫父窗口?比如一个A页面利用iframe或frame调用B页面,那么A页面所在窗口就是B页面的parent。

在JS中,window.opener只是对弹出窗口的母窗口的一个引用。比如:a.html中,通过点击按钮等方式window.open出一个新的窗口b.html。那么在b.html中,就可以通过window.opener(省略写为opener)来引用a.html,包括a.html的document等对象,操作a.html的内容。

那么,第一个问题解决了,opener是打开自己的窗口,而parent是这个小窗口所在的窗口。

但是,为什么我会遇到有opener但是没有document这种问题?


二、和opener通信

我用了如下两段代码:

aa.html:

<html>
<head>
<title>无标题文档</title>
</head>
<body>
<span id="name"></span>
<input type="button" " value="弹窗" onclick="window.open('bb.html')" />
</body>
</html


bb.html:

 <head>
 <title>无标题文档</title>
 </head>
 <body>
 <input type="text"  id="inputValue"/>
 <input type="button"  value="添加" onclick="window.opener.document.getElementById('name').innerHTML=inputValue.value"/>
 </body>
 </html> 


 <head>
 <title>无标题文档</title>
 </head>
 <body>
 <input type="text"  id="inputValue"/>
 <input type="button"  value="添加" onclick="window.opener.document.getElementById('name').innerHTML=inputValue.value"/>
 </body>
 </html> 


代码很简单,想法是在bb.html中的text中输入一段文字后点添加即可在aa中显示添加的内容。


最后返现在360中不论如何都不能显示,而在ie中设置允许控件之后就可以执行了。


结论:做javascript试验时最好用ie,是否设置空间可以显示。


三、和parent通信

类似于opener通信。


原创粉丝点击