我想制作一个tampermonkey脚本,随机重定向到网站而不重复。查看完所有网站后,我希望出现一个警报,通知脚本已完成。
我使用了这里的脚本( How to redirect to one out of given set of sites? ),但它重复了网站。
我应该如何处理这个问题?
// ==UserScript==
// @name Cat slideshow
// @match https://i.imgur.com/homOZTh.jpg
// @match https://i.imgur.com/NMDCQtA.jpg
// @match https://i.imgur.com/iqm9LoG.jpg
// ==/UserScript==
var urlsToLoad = [
'https://i.imgur.com/homOZTh.jpg',
'https://i.imgur.com/NMDCQtA.jpg',
'https://i.imgur.com/iqm9LoG.jpg',
];
setTimeout (GotoRandomURL, 4000);
function GotoRandomURL () {
var numUrls = urlsToLoad.length;
var urlIdx = urlsToLoad.indexOf (location.href);
if (urlIdx >= 0) {
urlsToLoad.splice (urlIdx, 1);
numUrls--;
}
urlIdx = Math.floor (Math.random () * numUrls);
location.href = urlsToLoad[urlIdx];
}
最佳答案
编辑:修复了代码的 math.random 部分。
这应该有效。我只是复制该数组,然后在导航到该 url 后,从复制的数组中删除该 url。它只会在遍历所有 url 并重新开始后重复一个 url。
const urlsToLoad = [
'https://i.imgur.com/homOZTh.jpg',
'https://i.imgur.com/NMDCQtA.jpg',
'https://i.imgur.com/iqm9LoG.jpg',
];
let copyOfUrlsToLoad = [];
setTimeout(goToRandomURL, 4000);
function goToRandomURL () {
if (copyOfUrlsToLoad.length === 0) {
copyOfUrlsToLoad = urlsToLoad;
}
urlIdx = getRandomInt(0, copyOfUrlsToLoad.length);
location.href = copyOfUrlsToLoad[urlIdx];
copyOfUrlsToLoad.splice(urlIdx, 1);
}
// This function comes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
如果您想在新选项卡或窗口中打开网址,this answer表示将 location.href
行替换为以下内容:
window.open(copyOfUrlsToLoad[urlIdx], '_blank');
关于Javascript - 如何随机重定向到网站而不重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498886/