使用 window.showModalDialog 打开的窗口没有 opener 对象, 这的确给使用带来了很多麻烦, 以前一直也没用过这个东西, 所以没有更多关注. 今天一个朋友问到这个问题, 于是上网搜索了一下, 找到了解决方案, 发上来供大家参考.

首先来看看 window.showModalDialog 的参数

  1. vReturnValue = window.showModalDialog(sURL [, vArguments] [, sFeatures]) ;

sURL : 打开窗口的地址;

vArguments : 传递参数;

sFeatures : 窗口属性列表;

第一个参数是必须的, 后两个可以省略.

这里我们要利用的就是第二个参数. 原理是将父窗口的被控制对象以参数的形式传递到子窗口, 在子窗口中直接控制这个对象即可.

举例来说:

parent.html

<script type="text/javascript">

function openWin(){
// 子窗口地址

var srcFile = "child.html";

// 子窗口属性

var winFeatures = "dialogHeight:300px; dialogLeft:200px;";

// 将 From 的 ID 作为参数传递到子窗口

var obj = getForm;

// 打开子窗口

window.showModalDialog(srcFile, obj, winFeatures);

}

</script>

 

 

<form id="getForm"> 回传值:
<input id="getValue" type="text" />
</form>
<input onclick="openWin()" type="button" value="打开" />

 

child.html

 
<script type="text/javascript"><!--
function send(){

    // 获取参数传递的对象

    var obj = window.dialogArguments;
    // 控制对象

    obj.getValue.value = 'from Child';
}

// --></script>


<a onclick="send();" href="#">Send</a>

 

运行 parent.html , 单击 [打开] 按钮弹出对话框, 点击 Send 链接将值传递到 parent 的文本框中.

 

传递的参数当然也可以是其他对象, 例如 window . 值得注意的是传递的是对象, 而不是字符串.

 

 

window.showModalDialog 打开的子窗口,不支持 window.opener 属性

获取父窗口,需要显示作为参数传入


// a.aspx
window.showModalDialog("b.aspx", window);


// b.aspx
var theOpener = window.dialogArguments;
theOpener.close();

// 对于内嵌 c.aspx ->
var outerOpener = window.top.dialogArguments;
outerOpener.close();