当前位置:  开发笔记 > 编程语言 > 正文

JavaScript window.open仅在窗口尚不存在时才打开

如何解决《JavaScriptwindow.open仅在窗口尚不存在时才打开》经验,为你挑选了3个好方法。



1> Peter Bailey..:

我会这样做 - 基本上将所有引用的打开的窗口存储在函数本身上.当函数触发时,检查窗口是否不存在或已关闭 - 因此,启动弹出窗口.否则,请关注该请求的现有弹出窗口.

function launchApplication(l_url, l_windowName)
{
  if ( typeof launchApplication.winRefs == 'undefined' )
  {
    launchApplication.winRefs = {};
  }
  if ( typeof launchApplication.winRefs[l_windowName] == 'undefined' || launchApplication.winRefs[l_windowName].closed )
  {
    var l_width = screen.availWidth;
    var l_height = screen.availHeight;

    var l_params = 'status=1' +
                   ',resizable=1' +
                   ',scrollbars=1' +
                   ',width=' + l_width +
                   ',height=' + l_height +
                   ',left=0' +
                   ',top=0';

    launchApplication.winRefs[l_windowName] = window.open(l_url, l_windowName, l_params);
    launchApplication.winRefs[l_windowName].moveTo(0,0);
    launchApplication.winRefs[l_windowName].resizeTo(l_width, l_height);
  } else {
    launchApplication.winRefs[l_windowName].focus()
  }
}


+1效果很好.但有一件事,你在原始支票中有'winRefs`但后来你把它拼错为`winrefs`

2> scunliffe..:

您需要执行2次测试... 1检查是否定义了弹出窗口,2检查是否已关闭.

if(typeof(winRef) == 'undefined' || winRef.closed){
  //create new
  winRef = window.open(....);
} else {
  //it exists, load new content (if necs.)
  winRef.location.href = 'your new url';
  //give it focus (in case it got burried)
  winRef.focus();
}



3> M4N..:

您可以在打开新窗口的页面中使用类似的内容:

var newWindow = null;

function launchApplication()
{
  // open the new window only if newWindow is null (not opened yet)
  // or if it was closed
  if ((newWindow == null) || (newWindow.closed))
    newWindow = window.open(...);
}

推荐阅读
勤奋的瞌睡猪_715
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有