Developer Snippet Diary

User need to visit link for 30 seconds else error in javascript | Task in js

User need to click on a link it will open target site in new tab. And check every second if tab is not closed. If user close the tab He/She need to do that task again.

HTML CODE

<h1 class="elem" onclick="newTabHandle('https:\/\/love.com')">Open website in new tab for 30 seconds</h1>

Javascript code

<script>
    function newTabHandle(url) {
        let ad;
        let timer = 30; //seconds
        let btn = document.getElementsByClassName('elem')[0];
        ad = window.open(url);
        let checker = setInterval(function(){
            timer--;
            if(timer >= 0) {
                if(ad.closed) {
                    btn.innerHTML = "Watch it Again";
                    clearInterval(checker);
                } else {
                    document.title = timer+ "seconds remaining, do not close the page!";
                    btn.innerHTML = timer+ "seconds remaining!";
                }
                

            }else if(timer >= -3) {
                document.title = "Validating, please wait...";
                btn.innerHTML = "Validating...";
            }else if(timer == -4) {
               
                $.ajax({
                    url: "https://mybackend.com/verify",
                    method: 'POST',
                    data: {
                        user_id: 1,
                        task:'completed'
                    },
                    success: function(data) {
                        if(data.error == true) {
                            btn.innerHTML = data.message;
                        }

                        btn.innerHTML = "Redirecting...";
                        document.title = "Redirecting...";
                        clearInterval(checker);

                        setTimeout(function(){
                            window.location.reload();
                        }, 1000);
                    }
                });    
            }
        }, 1000);
    }
</script>
Posted by: R GONDAL
Email: rizikmw@gmail.com