检查窗口是否已打开window.open

Sag*_*tri 19 html javascript

我有一个HTML页面.在页面的正文中,我调用了onload调用javascript函数的事件来打开弹出窗口.这是代码:

var newWindow = null;
function launchApplication()
{
    if ((newWindow == null) || (newWindow.closed))
    {
        newWindow = window.open('abc.html','','height=960px,width=940px');
    }
}
Run Code Online (Sandbox Code Playgroud)

当我移动到另一个页面,并再次返回该页面时,弹出窗口重新打开,虽然它已经打开.请指导我正确的方向,如果弹出已经打开,那么它不应再打开.我试过,document.referred但它需要网站在线,目前我在线下工作.

Jon*_*nna 12

newWindow = window.open('abc.html','com_MyDomain_myWindowForThisPurpose','height=960px,width=940px');
Run Code Online (Sandbox Code Playgroud)

给窗口一个名字.像这样在您的域名上添加名称可以防止您选择其他人碰巧选择的名称的机会.

永远不要组成一个以开头的名称_,这些名称保留给浏览器以不同方式处理的特殊名称(与锚元素的"target"属性相同).

请注意,如果使用不同的选项(例如,不同的高度)打开该名称的窗口,那么它将保留这些选项.此处的选项仅在没有该名称的窗口时才会生效,因此您创建一个新选项.

编辑:

请注意,"名称"是窗口,而不是内容.它不影响标题(newWindow.document.title会影响它,当然会编码abc.html).它确实会影响其他尝试跨窗口执行操作.因此,window.open具有相同名称的另一个将重用此窗口.此类链接<a href="def.html" target="com_MyDomain_myWindowForThisPurpose">clicky!</a>也会重复使用它.有关浏览器在各种情况下阻止打开窗口的常规警告(弹出窗口阻止)适用.


Tim*_*nen 9

打开一个窗口并在页面刷新之间保持对它的引用.

var winref = window.open('', 'MyWindowName', '', true);
if(winref.location.href === 'about:blank'){
    winref.location.href = 'http://example.com';
}
Run Code Online (Sandbox Code Playgroud)

或以函数格式

function openOnce(url, target){
    // open a blank "target" window
    // or get the reference to the existing "target" window
    var winref = window.open('', target, '', true);

    // if the "target" window was just opened, change its url
    if(winref.location.href === 'about:blank'){
        winref.location.href = url;
    }
    return winref;
}
openOnce('http://example.com', 'MyWindowName');
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以通过在窗口关闭时重新分配对它的引用来检查窗口是打开还是关闭.例:

var newWindow;
var openWindow = function(){
    newWindow = newWindow || window.open('newpage.html');
    newWindow.focus();
    newWindow.onbeforeunload = function(){
        newWindow = null;
    };
};
Run Code Online (Sandbox Code Playgroud)