简体   繁体   中英

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. I want to open link in new tab and new tab should be closed after 15 seconds. 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. In setTimeout() function put time in miliseconds refers how many times it delay to execute the given function.

<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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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