J'écris un javascript ouvre plusieurs URL sur le même onglet. Je sais ouvrir un lien dans un nouvel onglet.
window.open(urlList[0],"_blank")
Cependant, mon client souhaite que j'ouvre un seul onglet avec plusieurs URL. Imaginez que vous ayez un javascript
var urlList=['https://www.google.com', 'www.youtube.com']
Je veux ouvrir ensuite un par un sur les mêmes nouveaux onglets avec un intervalle de 10secs. D'abord, je le fais
window.open(your_url,"_blank")
Mais si je fais toujours cela pour le second, cela ouvre un autre nouvel onglet, pas sur l'ancien. Est-ce que quelqu'un sait comment spécifier l'onglet ouvert?
3 Réponses :
Lorsque vous ouvrez en utilisant window.open
, il retournera l'objet de fenêtre de l'onglet nouvellement ouvert, utilisez-le pour mettre à jour l'URL après 10 secondes. Pour fournir un délai, utilisez setInterval
a> méthode. // 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)
ceci est un exemple de code.
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)); }
J'espère que cela vous aidera.
Je ne sais pas pourquoi vous voudriez faire ça. Ne fais pas ça. C'est super ennuyeux. Mais si vous devez le faire, ce qui suit fonctionne et a été testé en chrome (et uniquement en chrome)
Quelques des choses à noter:
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)