我想创建一个随机重定向到网站的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];
}
答案 0 :(得分:1)
编辑:修复了代码的math.random部分。
这应该有效。我只是制作数组的副本,然后导航到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');