Alcove
Alcove

Reputation: 39

Javascript - how to randomly redirect to websites without repeating?

I'd like to make a tampermonkey script that randomly redirects to websites without repeating. Once all the websites have been viewed, I want there to be an alert that notifies that the script is finished.

I've used the script from here (How to redirect to one out of given set of sites?) but it repeats the websites.

How should I go about with this?

// ==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];
} 

Upvotes: 0

Views: 306

Answers (1)

Jason
Jason

Reputation: 534

EDIT: fixed the math.random section of the code.

This should work. I'm just making a copy of the array and then after navigating to the url I remove that url from the copied array. It will only repeat a url after it has gone through all urls and started over.

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
}

If you want to open the url in a new tab or window, this answer says to replace the location.href line with the following:

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

Upvotes: 1

Related Questions