Popups and Window Methods
JavaScript Popups and Window Methods (JavaScript弹出窗口和窗口方法)
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.w3cdoc.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. (运行上面的代码将打开一个带有特定URL的新窗口。现代浏览器配置为打开新标签页,而不是单独的窗口。)
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. (-这是一个独立的窗口,有自己的独立JavaScript环境。因此,使用第三方不受信任的网站打开弹出窗口可能足够安全。)
Popups navigate (change URL) and can send messages to the opener. (-弹出窗口导航(更改URL ) ,并可以将消息发送到打开器。)
Popup Blocking
Popup Blocking (弹出窗口阻止)
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. (大多数浏览器都会阻止弹出窗口,以防它们在用户触发的事件处理程序(如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.w3cdoc.com/');
// popup allowed
(//允许弹出窗口)
button.onclick = () => {
window.open('https://www.w3cdoc.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
(2秒后)
setTimeout(() => window.open('https://w3cdoc.com'), 2000);
</script>
</body>
</html>
The popup window will open in Chrome, but Firefox will block it. (弹出窗口将在Chrome中打开,但Firefox会阻止它。)
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
(//1秒后打开)
setTimeout(() => window.open('https://w3cdoc.com'), 1000);
</script>
</body>
</html>
Window.open
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 .
the position:
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. 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:
toolbar (yes/no): it either displays or hides the browser navigation bar on the new window. menubar (yes/no): it displays or hides the browser menu on the new window. 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. status (yes/no): displays or hides the status bar. However, most browsers force it to display. resizable (yes/no): allows disabling the resize for the new window. It is not recommended for usage. scrollbars (yes/no): allows disabling the scrollbars for the new window. It is not recommended either.
Example: a minimalistic window
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,
(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,
(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
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. (调用open返回对新窗口的引用。它可用于操作其属性、更改位置等。)
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 w3cdoc");
</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')
(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 w3cdoc!</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. (请注意,在window.open之后,新的不会立即加载。这由()行中的警报显示。因此,有必要等待onload进行修改。DOMContentLoaded处理程序也可用于newWin.document。)
Accessing Window from Popup
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. (使用window.opener引用,弹出窗口可以访问opener窗口。除弹出窗口外,所有窗口都将其视为空。)
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(
(newWin.document.write ()
"<script>window.opener.document.body.innerHTML = 'Welcome to w3cdoc'<\/script>"
);
</script>
</body>
</html>
The connection between the windows is considered bidiercional: the primary window and the popup reference one another.
Closing a Popup
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. (要检查窗口是否关闭,可以运行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. (Window.close ()方法在技术上可用于任何窗口,但如果窗口不是使用window.open ()创建的,大多数浏览器都会忽略git clone。因此,这仅适用于弹出窗口。)
If the window is closed, the closed property is true. (如果窗口关闭,则关闭的属性为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
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. (- win.moveBy (x, y)方法,用于将窗口相对于当前位置x像素向右移动, y像素向下移动。您也可以在此处应用负值。)
the win.moveTo(x,y) method, which is used for moving the window to coordinates ( x,y) on the screen. (- win.moveTo (x, y)方法,用于将窗口移动到屏幕上的坐标(x, y)。)
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. (- win.resizeBy (width, height)方法,用于相对于当前大小按特定宽度/高度调整窗口大小。在这里,负值也是可以接受的。)
the win.resizeTo(width,height) method - to resize the window to the specific size. (- win.resizeTo (width, height)方法-将窗口大小调整为特定大小。)
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. (通常,浏览器会阻止上述防止滥用的方法。 它们只能在没有其他选项卡的已打开弹出窗口上可靠地工作。 JavaScript不提供缩小或最大化窗口的任何方法。 操作系统级函数通常对前端开发人员隐藏。)
The move/resize methods don’t operate for minimized/maximized windows. (移动/调整大小方法不适用于最小化/最大化窗口。)
Scrolling a Window
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. (- win.scrollBy (x, y)方法用于在当前滚动附近向右和向下滚动窗口x像素。负值是可以接受的。)
the win.scrollTo(x,y) method - for scrolling the window to the specific coordinates ( x,y). (- win.scrollTo (x, y)方法-用于将窗口滚动到特定坐标(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) . (- elem.scrollIntoView (top = true)方法-用于滚动窗口,使elem出现在elem.scrollIntoView (false)的顶部或底部。)
Focus/blur on a Window
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. (Window.focus ()和window.blur ()方法用于聚焦/不聚焦窗口。还有聚焦和模糊事件,允许对焦窗口并捕捉用户切换到其他位置的时刻。)
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. (当用户尝试切换出窗口(模糊)时,它会返回焦点。AIM将用户“锁定”在窗口内。但是,现有的限制禁止此类代码。这主要取决于浏览器。)
Focusing will not work once a popup opens in a separate tab rather than a new window. (在单独的选项卡而不是新窗口中打开弹出窗口后,焦点将不起作用。)
Summary
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. (您可以使用打开的(url, name, params)调用打开一个弹出窗口。使用它,引用将返回到新打开的窗口。)
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. (Window.opener属性用于访问打开器窗口。而且,如果主窗口和弹出窗口具有相同的原点,它们可以轻松地互相读取和修改。否则,他们会改变彼此的位置,交换信息。)
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. (Window.opener调用用于关闭弹出窗口。此外,用户可以像关闭任何其他窗口一样关闭该窗口。之后, window.closed将为true。)