Screeching Kitten Soul Screeching Kitten Soul - 27 days ago 18
Javascript Question

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.

Answer

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');
</script>

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

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

    var randURLs = [ "http://url0", "http://url1", "http://url1" ];

    if (randNum == 0) {
        var randURL = Math.floor(Math.random() * randURLs.length);
        window.open(randURLs[randURL], '_blank');
    }
</script>
Comments