JavaScript Popups and Window Methods

One of the oldest methods of showing an additional document to the user is a popup window.

Here is an example of running a popup window:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      window.open('https://www.w3docs.com/');
    </script>
  </body>
</html>

Running the code above will open a new window with a particular URL. Modern browsers are configured for opening new tabs instead of separate windows.

The initial idea of implementing popup windows was to show different content without closing the primary window.

In the modern world, there are other ways of doing that: for example, loading content dynamically with fetch and showing it in a dynamically generated <div>. So, a popup is not a means of everyday use.

Moreover, popups can be tricky on mobile devices.

Yet, some tasks require the usage of popups: Auth authorization ( login with Google). Here are the general reasons for using popups:

  • Opening a popup is easy.
  • It is a separate window with own independent JavaScript environment. Hence, opening a popup with a third-party non-trusted site can be safe enough.
  • Popups navigate (change URL) and can send messages to the opener.

Previously, popups very abused too much. Bad pages applied a large number of popup windows with ads. Therefore, nowadays many browsers block popups to protect the user.

Most of the browsers block popups in case they are called outside of the user-triggered event handlers, such as onclick.

Here is an example of using onclick :

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      // popup blocked
       window.open('https://www.w3docs.com/');           
      // popup allowed
      button.onclick = () => {
        window.open('https://www.w3docs.com/');
      };      
    </script>
  </body>
</html>

So, this keeps the users protected from unwanted popups. Anyway, the functionality isn’t entirely disabled.

There can be a tricky case of opening from onclick but after setTimeout. In such cases, you can use the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      // open after 2 seconds
      setTimeout(() => window.open('https://w3docs.com'), 2000);
    </script>
  </body>
</html>

The popup window will open in Chrome, but Firefox will block it.

Decreasing the delay will make it work in Firefox too, like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      // open after 1 seconds
      setTimeout(() => window.open('https://w3docs.com'), 1000);
    </script>
  </body>
</html>

Window.open

The syntax of opening a popup is the following:

window.open(url, name, params);

In the syntax:

  • url: it’s an URL for loading into the new window.
  • name: the name of the new window. Every window should have a window.name, and here it is possible to specify what window to use for the popup. In case, a window with such a name already exists, the given URL opens in it, otherwise, a new window is opened.
  • param: it’s the configuration string for the new window. It includes settings that are delimited with a comma. No spaces should be in params ( for example, width:500,height=500 .
  • Here are the params settings:

  • the position:
    1. left/top (numeric): includes the coordinates of the window top-left corner on the screen. But, you can face a limitation: you can’t position a new window offscreen.
    2. width/height (numeric): it specifies the width and height of the new window. There can be a limit on them. So, creating an invisible window is not possible.
  • the features of the window:
    1. toolbar (yes/no): it either displays or hides the browser navigation bar on the new window.
    2. menubar (yes/no): it displays or hides the browser menu on the new window.
    3. location (yes/no): it displays or hides the field of URL in the new window. FF and IE don’t allow hiding it by default.
    4. status (yes/no): displays or hides the status bar. However, most browsers force it to display.
    5. resizable (yes/no): allows disabling the resize for the new window. It is not recommended for usage.
    6. scrollbars (yes/no): allows disabling the scrollbars for the new window. It is not recommended either.

Example: a minimalistic window

Let’s try to open a window using minimal set of features for seeing which of them the browser allows to deactivate:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      let params = `scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,
      width=0,height=0,left=-1000,top=-1000`;
      open('/', 'test', params);
    </script>
  </body>
</html>

In the example above, most of the window features are deactivated, and the window is positioned offscreen.

Let’s add to the example above normal positioning options and width, height, left, top coordinates, like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      let params = `scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,
      width=500,height=400,left=100,top=100`;
      open('/', 'test', params);
    </script>
  </body>
</html>

Accessing Popup from Window

The call open returns a reference to the new window. It can be applied for manipulating its properties, changing the location, and so on.

Generating popup content from JavaScript is demonstrated in this example:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      let newWin = window.open("about:blank", "welcome", "width=500,height=500");      
      newWin.document.write("Welcome to W3Docs");
    </script>
  </body>
</html>

And now let’s modify the contents after loading, like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      let newWindow = open('/', 'example', 'width=500,height=500')
      newWindow.focus();
      alert(newWindow.location.href); // (*) about:blank, loading hasn't started yet
      newWindow.onload = function() {
        let html = `<div style="font-size:30px">Welcome to W3Docs!</div>`;
        newWindow.document.body.insertAdjacentHTML('afterbegin', html);
      };
    </script>
  </body>
</html>

Please, take into account that after window.open the new will not be loaded immediately. That is shown by alert in line (*). So, it’s necessary to wait for onload for modifying it. The DOMContentLoaded handler can also be used for newWin.document.

Accessing Window from Popup

With the window.opener reference, a popup can access the opener window. It is considered null for all the windows, except for popups.

Running the code below will replace the opener window content with “Test”, as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      let newWin = window.open("about:blank", "welcome", "width=500,height=500");      
      newWin.document.write(
        "<script>window.opener.document.body.innerHTML = 'Welcome to W3Docs'<\/script>"
      );
    </script>
  </body>
</html>

The connection between the windows is considered bidiercional: the primary window and the popup reference one another.

Closing a Popup

To close a window, you can act like this: win.close().

For checking whether a window is closed you can run win.closed.

The window.close() method is technically available for any window, but git clone is ignored by the majority of the browsers in case the window is not created using window.open() . So, that will operate only on a popup.

If the window is closed, the closed property is true.

Here is an example of the window closed with the true property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the Document</title>
  </head>
  <body>
    <script>
      let newWindow = open('/', 'example', 'width=500,height=500');      
      newWindow.onload = function() {
        newWindow.close();
        alert(newWindow.closed); // true
      };  
    </script>
  </body>
</html>

Scrolling and Resizing

Also, there exist methods for moving or resizing a window.

Here they are:

  • the win.moveBy(x,y) method, which is used for moving the window relative to current position x pixels to the right side and y pixels down. You can also apply negative values here.
  • the win.moveTo(x,y) method, which is used for moving the window to coordinates ( x,y) on the screen.
  • the win.resizeBy(width,height) method that is used for resizing the window by a particular width/height relative to the current size. Here, negative values are acceptable too.
  • the win.resizeTo(width,height) method - to resize the window to the specific size.

Usually, the browsers block the methods above for preventing abuse. They can only work reliably on the already opened popups having no additional tabs. JavaScript doesn’t provide any way to minify or maxify a window. The OS-level functions are usually hidden from Frontend-developers.

The move/resize methods don’t operate for minimized/maximized windows.

Scrolling a Window

Now, we are going to represent the methods of scrolling a window.

Find them below:

  • the win.scrollBy(x,y) method is used for scrolling the window x pixels right and y down near the current scroll. Negative values are acceptable.
  • the win.scrollTo(x,y) method - for scrolling the window to the specific coordinates ( x,y).
  • the elem.scrollIntoView(top = true) method- for scrolling the window to make elem appear at the top or bottom for elem.scrollIntoView(false) .

Focus/blur on a Window

The window.focus() and window.blur() methods are used to focus/unfocus on a window. There are also focus and blur events that allow focusing a window and catching the moment when the user switches elsewhere.

Consider the following code:

window.onblur = () => window.focus();

When the user tries to switch out of the window (blur), it returns the focus. The aim “locking” the user inside the window. But, the existing limitations forbid such a code. It mostly depends on the browser.

Focusing will not work once a popup opens in a separate tab rather than a new window.

Summary

Popup windows are not used often, as there are alternatives, such as loading and displaying information in-page or inframe.

Once trying to open a popup, a good practice is informing the user about it. An icon next to a link or a button will help the user to survive the focus shift, keeping both windows in mind.

You can open a popup with the open(url, name, params) call. With it, the reference will be returned to the newly opened window.

Generally, browsers block open calls from the code out of the user actions. The user may allow them once a notification appears.

By default, browsers open a new tab. If sizes are provided, then it will be a popup window.

Thewindow.opener property is used for accessing the opener window. And, if the main window and the popup have the same origin, they can easily read and modify one another. Otherwise, they change the location of one another, exchanging messages.

The window.opener call is used for closing the popup. Also, it can be closed by the user like any other window. After that, the window.closed will be true.

Practice Your Knowledge

Which of the following are methods to show popups in JavaScript?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?