简体   繁体   中英

Calling function from current tab in a new tab

I wrote the following code:

function challenge() {
    var body = $("body").html();
    if(body.match(/td\>([0-9]+)\<\/td\>/)[1] > 0){
        // find challengable player
        var url = body.match(/href="(\/game.php?.*challenge.*[0-9a-f]+)"/)[1].replace(/&amp;/g, '&');
        // open new tab with the link
        var winEvent = window.open(url, '_blank');
        // get random number between 7 and 10
        var rand = Math.random() * (10 - 7) + 7;
        // set interval for new tab to random minutes
        winEvent.setInterval(challenge, rand*1000);
        // close current tab
        window.close();
    }
}
window.setInterval(challenge, 5*1000);

In challenge() I look for a link and open it in a new tab. However, the following line is not working as intended:

winEvent.setInterval(challenge, rand*1000);

The new tab should call the challenge() function every rand seconds

Thanks in advance!

Okay, based on your comment and given code. I am still a lil confused. But from what I understood here that you want to open a new tab and in that new tab you want to open another new tab.

Here is a generic solution. You can change it according to your needs.

To test it in a fiddle you need to allow your popup blocker and ad blocker.

<html>
  <body>
    <div>
      hello
    </div>
    <script>
      function openTab() {
        var newWindow = window.open(); //CREATE A NEW TAB

        //WRITE CURRENT OUTER HTML TO THE NEW TAB (BASICALLY CLONING THE CURRENT TAB)
        newWindow.document
                 .write(document.getElementsByTagName("html")[0].outerHTML)

        window.close();
      }

      setTimeout(() => {
        openTab();
      }, 1000); //OPEN TAB AFTER 1 SECOND

    </script>
  </body>
</html>

NOTE: This is not a good design or structure, as popup blockers or ad blockers will block your new tab opening. According to me, I wouldn't recommend doing something like this.

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