我有一个C# aspx Web应用程序,它使用JavaScript打开了一个弹出窗口。 我捕获窗口句柄并将该值放入数组中。 当 Web 应用程序关闭时,我想关闭弹出窗口。 当我询问数组时,窗口句柄不再在数组中,因此我找不到关闭它的窗口。 这种行为对我来说很奇怪,因为其他弹出窗口(不包含 silverlight)将保留在数组中,并在应用程序结束时关闭。
起初,我认为这是可以用框架解决的问题,例如包含 PDF 的弹出窗口无法关闭,但解决方案在这里对我来说不起作用。这是我必须与 PDF 一起使用的东西
问:当 aspx 主窗口关闭时,如何关闭包含 Silverlight 的弹出窗口?
一些 JavaScript 代码:
var openedWindows = new Array();
function OpenNamedWindow(url, name, features, replace)
{
var oWin = open(url, name, features, replace);
// The Silverlight window object is within this array afterwards, and in subsequent calls
// to this method
openedWindows.push(oWin);
}
function CloseOpenedWindows()
{
while (openedWindows.length > 0)
{
var window = openedWindows.shift();
if(!window.closed)
window.close();
}
}
主 aspx 形式(缩写)
<html>
<body onunload="CloseOpenedWindows();"> ... <body/>
</html>
试试这段代码,与C#和Silverlight无关。我不会声明变量"窗口",我肯定会将关闭事件"卸载"附加到"窗口"。
.html:
<button id=openwindow>open new window</button>
<br />
<a href="http://jsfiddle.net/">go to another page and close this</a>
JavaScript:
// lib AttachEvent
function AttachEvent(obj, evt, fnc, useCapture) {
if (!useCapture) useCapture = false;
if (obj.addEventListener) {
obj.addEventListener(evt, fnc, useCapture);
return true;
} else if (obj.attachEvent) return obj.attachEvent("on" + evt, fnc);
else {
MyAttachEvent(obj, evt, fnc);
obj['on' + evt] = function() {
MyFireEvent(obj, evt)
};
}
};
// lib AttachEvent
var windowOpenControl = {
__cache: [],
open: function(url, name, features, replace) {
var w = window.open(url, name, features, replace);
this.__cache.push(w);
},
closeAll: function() {
try {
var c = this.__cache.length;
for (var i = 0; i < c; i++) {
this.__cache[i].close();
}
} catch (e) {}
}
};
var
button = document.getElementById('openwindow'),
counter = 0;
AttachEvent(button, 'click', function() {
windowOpenControl.open("http://www.google.com", 'mywindow_' + (counter++));
});
AttachEvent(window, 'unload', function() {
windowOpenControl.closeAll();
});
运行示例
事实证明,包含
var openedWindows = new Array();
被多次加载,所以 JavaScript 对需要迭代哪个数组感到困惑。 确保 js 文件仅在加载一次即可解决问题。