使用相同的URL,JavaScript打开多个迷你窗口

时间:2014-05-28 06:04:28

标签: javascript jquery browser

我无法在页面中打开多个具有相同网址的窗口,每次在for循环中调用window.open时,旧的迷你窗口内容将被新内容替换。但我不想替换内容,而是单独打开一个新窗口。

JavaScript代码:

function OpenMultipleWindows() {
    var winContent = ['Page1', 'Page2', 'Page3', 'Page4']
    for (var i = 0; i < winContent.length; i++) {
        (function (text) {
            var newWin = open('/localFolder/window.html', 'Print', 'width=500,height=500', '_blank');
            newWin.document.body.innerHTML = winContent[text];
        }(i));
    }
}

$(function () {
    OpenMultipleWindows();
});

window.html html代码: -

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <script type="text/VBScript">
        document.write "<object ID='WB' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'></object>"
        Sub printitinvb()
         On Error Resume Next
         OLECMDID_PRINT = 6
         OLECMDEXECOPT_DONTPROMPTUSER = 2
         OLECMDEXECOPT_PROMPTUSER = 1
         call WB.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, 1)
         End Sub
    </script>
    <script type="text/javascript">
        function printit() {
            printitinvb();
        }
    </script>
</head>

<body onload='printit();'>
</body>

</html>

这个问题有解决办法吗?

1 个答案:

答案 0 :(得分:4)

您的问题是,您没有更改弹出窗口的标识符。 你可以尝试这样的事情:

function OpenMultipleWindows() {
    var winContent = ['Page1', 'Page2', 'Page3', 'Page4'];
    for (var i = 0; i < winContent.length; i++) {
        (function (text) {
            var newWin = open('/localFolder/window.html', 'Print' + i, 'width=500,height=500', '_blank');
            newWin.document.body.innerHTML = winContent[text];
        }(i));
    }
}

$(function () {
    OpenMultipleWindows();
});

第二个参数是标识符,必须是唯一的。

//编辑:添加注释作为评论的答案

您需要等到文档在弹出窗口中加载。我通常会为此添加一个JavaScript元素。但你可以像我想的那样(未经测试):

function addTextToPopup(handle, text){
    if (!handle|| handle.closed) return;
    var bodyElem = handle.document.getElementsByTagName('body');
    if (!bodyElem || bodyElem.length !== 1){
        //check again after a short period
        window.setTimeout(function(){
             addTextToPopup(handle, text);
        }, 250);
        return;
    }

    handle.document.body.innerHTML = winContent[text];
}

function OpenMultipleWindows() {
    var winContent = ['Page1', 'Page2', 'Page3', 'Page4'];
    for (var i = 0; i < winContent.length; i++) {
        (function (text) {
            var newWin = open('/localFolder/window.html', 'Print' + i, 'width=500,height=500', '_blank');
            addTextToPopup(newWin, winContent[text]); 
        }(i));
    }
}

$(function () {
    OpenMultipleWindows();
});

如果这不起作用,请尝试附加一个JS变量,如domIsReady = false;,并在弹出的html onload事件中将其设置为true,并检查newWin.domIsReady === true是否为真