简体   繁体   English

从新标签页中的当前标签页调用函数

[英]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. 在Challenge()中,我寻找一个链接并在新选项卡中将其打开。 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 新选项卡应每rand秒调用一次Challenge()函数

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. 据我说,我不建议这样做。

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

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