爪哑脚本 |检查是否已打开具有特定 URL 的窗口

Javascript | Check if a windows with specific URL already is opened

本文关键字:URL 窗口 脚本 检查 是否      更新时间:2023-09-26

此函数显示/ticket.html 弹出窗口。

我需要在窗口是否已经打开之前检查。如果是,请取消新的打开。

怎么能做到这一点呢?

function popitup() {
           newwindow=window.open("ticket.html","_blank","toolbar=yes,scrollbars=yes, resizable=yes, top=500, left=500, width=730, height=700");
           newwindow.moveTo(350,150);
       if (window.focus) 
              {
                 newwindow.focus()
              }
      }

问候

打开窗口时,可以保存对窗口的引用。window.open方法返回一个windowObjectReference

使用此引用,您可以检查窗口是否已关闭(closed属性,布尔值),或者只是窗口是否为 null(window属性,它将是一个Window对象或 null,如果关闭)。

简单的例子:

// Open the pop-up and save the reference.
var windowObjRef = window.open('ticket.html');
// Verification, alternative 1. You may encapsulate this in a method.
if (windowObjRef.closed) {
    // The window is closed.
else {
    // The window is still open.
}
// Verification, alternative 2. You may encapsulate this in a method.
if (windowObjRef.window) {
    // The window is still open.
else {
    // The window is closed.
}

参考: https://developer.mozilla.org/en-US/docs/Web/API/Window

我是javascript的新手。我找到了一个提供以下代码的网站。但它仅提供有关窗口是否更早创建的信息。

function myOpenWindow(winURL, winName, winFeatures, winObj)
{
  var theWin; // this will hold our opened window 
  // first check to see if the window already exists
  if (winObj != null)
  {
    // the window has already been created, but did the user close it?
    // if so, then reopen it. Otherwise make it the active window.
    if (!winObj.closed) {
      winObj.focus();
      return winObj;
    } 
    // otherwise fall through to the code below to re-open the window
  }
  // if we get here, then the window hasn't been created yet, or it
  // was closed by the user.
  theWin = window.open(winURL, winName, winFeatures); 
  return theWin;
}

此外,访问其他选项卡的内容也可能对用户的隐私造成攻击。