简体   繁体   English

使用 window.open() 打开一个带有链接的新标签,我希望该标签在 15 秒后自动关闭

[英]opening a new tab with a link using window.open() and i want that tab close automatically after 15sec

I am using window.open function in a button with onclick event.我在带有 onclick 事件的按钮中使用 window.open 函数。 I want to open link in new tab and new tab should be closed after 15 seconds.我想在新标签中打开链接,新标签应该在 15 秒后关闭。 So the countdown should be on the current page where button exists.所以倒计时应该在按钮所在的当前页面上。 Code snippet:代码片段:

<button onClick="openlike()">Like</button>
<script>

        function openlike(){
            var likewindow = window.open('http://www.google.com');
        }

</script>

when you open the new window store the window handler in a global variable and after clicking the button use setTimeout() function to close the window after several times.当您打开新窗口时,将窗口处理程序存储在全局变量中,并在单击按钮后多次使用setTimeout()函数关闭窗口。 In setTimeout() function put time in miliseconds refers how many times it delay to execute the given function.setTimeout()函数中,以miliseconds时间是指延迟执行给定函数的次数。

<button onClick="openlike()">Like</button>

<script>
        var likewindow;
        function openlike(){
            likewindow = window.open('http://www.google.com');
            setTimeout(windowClose,15000);
        }
        function windowClose(){
            likewindow.close();
        }

</script>

See the jsFiddle for demo.有关演示,请参阅jsFiddle

You can achieve this way:您可以通过这种方式实现:

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var newWindow = window.open("http://www.w3schools.com");
    setTimeout(() => newWindow.close(), 15 * 1000);
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM