Random URL redirect from array

前端 未结 8 1404
刺人心
刺人心 2021-01-27 05:37

/** * Political Animals * contentscript.js is loaded on each page(s) listed in manifest.json * This plugin replaces all the images on the website of news sites with pic

8条回答
  •  野性不改
    2021-01-27 06:28

    Generate a "random" key and use window.location.href to redirect the user. Others have posted the same approach, though with less explanation. I'm giving my best to let you actually understand what happens here.

    Note that most of this code is comments. It looks longer than it actually is.

    var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
    
    // This function returns a random key for an array
    function randomKey(arr) {
        // Math.random() returns a number between 0 and 0.99999...
        // If you multiply this value with the length of an array, you get a
        // random floating point number between 0 and that length.
        // Use Math.floor() to round it down to the next integer
        return Math.floor(Math.random() * arr.length);
    }
    
    // Select a random website from the array
    var key = randomKey(acceptedWebsites);
    var newLocation = acceptedWebsites[key];
    
    // Redirect the user
    window.location.href = newLocation;
    

提交回复
热议问题