【问题标题】:Open multiple urls in same new tab javascript在同一个新标签 javascript 中打开多个 url
【发布时间】:2019-04-01 14:35:08
【问题描述】:

我正在编写一个 javascript 在同一个选项卡上打开多个 URL。我知道如何在新标签中打开链接。

window.open(your_url,"_blank")

但是,我的客户希望我只打开一个带有多个 URL 的选项卡。 想象一下你有一个 javascript

var urlList=['https://www.google.com', 'www.youtube.com']

我想以 10 秒的间隔在相同的新选项卡上一一打开。 首先,我这样做

window.open(urlList[0],"_blank")

但是,如果我仍在为第二个标签执行此操作,它会打开另一个新标签,而不是旧标签。有谁知道如何指定打开的标签?

【问题讨论】:

    标签: javascript google-chrome url tabs


    【解决方案1】:

    当您使用window.open 方法打开时,它将返回新打开的选项卡的窗口对象,用于在 10 秒后更新 URL。提供延迟使用setInterval 方法。

    // website lists
    const urlList = ['https://www.google.com', 'http://www.youtube.com']
    
    // open the first url and cache the window object reference
    const win = window.open(urlList[0], "_blank")
    
    // variable for keeping track of array position(urls)
    let i = 1;
    
    // create interval with 10seconds delay and keep 
    // interval reference to clear the event in future
    let int = setInterval(() => {
      // update the location with next array value
      win.location = urlList[i];
      // check value of i and increment, if reached the max value then clear the interval
      if (i++ >= urlList.length) clearInterval(int)
    }, 10000)
    

    【讨论】:

      【解决方案2】:

      这是一个示例代码。

          async function navigate() {
       var _window = window.open("","_blank")
       var urlList=['https://www.google.com', 'https://www.youtube.com'];   
       for (var url of urlList) {     
          _window.location.replace(url);
          await sleep(10000);
       }   
      }
      
      function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      

      希望对你有所帮助。

      【讨论】:

        【解决方案3】:

        我不知道你为什么要这样做。不。 这太烦人了。但是如果你必须这样做,下面的工作并且已经在 chrome 中测试过(在 chrome 中)

        有几点需要注意:

        1. 这不会绕过弹出窗口阻止程序。用户必须允许
        2. 这在技术上并不使用“相同”标签。旧的已关闭,新的打开速度足够快,用户不会注意到。

        var myWindow;
        
        let urls = ["https://stackoverflow.com", "https://stackexchange.com/"];
        let counter = 0;
        let openWindow;
        
        function openWin(url) {
            openWindow = window.open(url, "_blank");
        }
        
        function closeWin(){
            openWindow.close();
        }
        
        setInterval(function(){
            if(openWindow) closeWin();
            openWin(urls[counter]);
            counter++;
        }, 10000)

        【讨论】:

          猜你喜欢
          • 2019-08-17
          • 1970-01-01
          • 2020-11-23
          • 2011-06-28
          • 2012-03-11
          • 1970-01-01
          • 1970-01-01
          • 2015-04-09
          • 2011-09-22
          相关资源
          最近更新 更多