繁体   English   中英

Javascript-如何随机重定向到网站而不重复?

[英]Javascript - how to randomly redirect to websites without repeating?

我想制作一个tampermonkey脚本,该脚本可以随机重定向到网站,而无需重复。 查看完所有网站后,我希望有一个警报来通知脚本已完成。

我从这里使用了脚本( 如何重定向到给定站点集中的一个? ),但是它会重复这些网站。

我该怎么办?

// ==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。

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
}

如果您想在新标签页或窗口中打开网址,则此答案要求将location.href行替换为以下内容:

window.open(copyOfUrlsToLoad[urlIdx], '_blank');

暂无
暂无

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

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