JavaScript 如何关闭用户通过URL打开的窗口

JavaScript 如何关闭用户通过URL打开的窗口

JavaScript 由于安全问题,不允许使用 window.close() 方法关闭用户打开的窗口。然而,我们可以通过一个变通方法关闭窗口。需要遵循的方法是使用JavaScript打开当前URL,然后使用脚本关闭它。

语法:

window.close()
JavaScript

方法: 下面的步骤演示了这种方法:

  • 打开一个新窗口使用 open() 方法 首先,我们需要使用 window.open() 方法打开一个新窗口。可以使用窗口对象的 location 属性访问当前URL。将窗口的目标属性或名称值设置为 _self 。这很重要,因为它使URL替换当前页面。
  • 使用 close() 方法关闭这个打开的窗口 window.close() 方法关闭调用它的窗口。通过使用这个方法关闭第一步打开的窗口。这是因为窗口现在是由我们的脚本打开而不是用户。

注意: 由于浏览器安全性的不同实现,这种方法可能不适用于所有浏览器。

示例: 下面的示例演示了上述步骤:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
 
 <h1 style="color: green;">
    GeeksforGeeks
</h1>
 
<p>
    Click on the button below to
    close the current window.
</p>
 
<!-- Define the button to 
       close the window -->
<button onclick="return closeWindow();">
    Close Window
</button>
 
<script type="text/javascript">
    function closeWindow() {
 
        // Open the new window 
        // with the URL replacing the
        // current page using the
        // _self value
        let new_window =
            open(location, '_self');
 
        // Close this window
        new_window.close();
 
        return false;
    }
</script>
</body>
 
</html>
HTML

输出:

JavaScript 如何关闭用户通过URL打开的窗口

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册