Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random HTML page redirect

So what I'm trying to do is have it so when you are on one of my webpages, there is a small chance to be randomly redirected to another page. Like 1 in 500 chance. Is this even possible? Please help.


1 Answers

This could be done easily in javascript.

Just get a random number between 0 and 500, let's say if the random number is 0 then we redirect the user to another page, otherwise we don't.

<script>
    var randNum = Math.floor(Math.random() * 500);

    if (randNum == 0)
        window.open('redirect-url', '_self');
</script>

If you want to redirect the user to a random website from a list of websites you can do something like this:

<script>
    // get a random number between 0 and 499
    //
    var randNum = Math.floor(Math.random() * 500);

    // An array of URL's
    var randURLs = [
        "http://url0",
        "http://url1",
        "http://url1"
    ];

    // There was a 1 in 500 chance we generated a zero.
    if (randNum == 0) {
        // randURLs.length will tell us how many elements are
        // in the randURLs array - we can use this to generate
        // a random number between 0 and n (number of elements)
        //
        // In our case there are 3 elements in the array, 0, 1
        // and 2. So we want to get another random number in
        // the inclusive range 0 - 2
        //
        var randURL = Math.floor(Math.random() * randURLs.length);

        window.open(randURLs[randURL]);
    }
</script>
like image 146
Michael Nealon Avatar answered Jun 29 '26 18:06

Michael Nealon