关闭包含silverlight的Javascript弹出窗口

时间:2012-06-06 14:24:09

标签: c# javascript asp.net silverlight

我有一个C#aspx Web应用程序,它使用JavaScript打开一个弹出窗口。我捕获窗口句柄并将该值放入数组中。当Web应用程序关闭时,我想关闭弹出窗口。当我询问数组时,窗口句柄不再在数组中,所以我找不到关闭它的窗口。这种行为对我来说很奇怪,因为其他弹出窗口(不包含silverlight)将保留在数组中,并在应用程序结束时关闭。

起初,我认为这是可以通过框架解决的问题,例如包含PDF无法关闭的弹出窗口,但是解决方案对我来说不起作用。 This was something I had to use with PDFs

问题:当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>

2 个答案:

答案 0 :(得分:0)

你可以尝试这个代码,与c#和silverlight无关。我不会声明一个变量&#39;窗口&#39;,我肯定会附上关闭事件&#39;卸载&#39;到了窗口&#39;。

<强> 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();
});​

run example

答案 1 :(得分:0)

原来是包含

的javascript文件
var openedWindows = new Array();

被多次加载,因此javascript对于需要迭代的数组感到困惑。确保仅加载js文件一次就解决了问题。