Random URL redirect from array

2020-05-09 06:06发布

问题:

/** * 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 pictures of * animals in suits, as a commentary on what the news has become. Made for Web 2 * November 20, 2013 */

//Random Image array

var arrayImg = ['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg','http://ny-image0.etsy.com/il_fullxfull.85564656.jpg','http://afraidofmice.com/blog/wp-content/uploads/2011/08/berkleyill.jpg','http://elizabethmarshallgalleryblog.files.wordpress.com/2011/05/etsy-panda-for-blog1.jpg','http://moesewco.typepad.com/.a/6a00e5500684b488330120a5c7cf3a970c-300wi','http://ih3.redbubble.net/image.13276877.5059/flat,800x800,070,f.u1.jpg','http://www.tildeshop.com/blog/wp-content/uploads/2012/09/SeaLionFemale-21.jpg'];

//redirect

var acceptedWebsites =['www.cnn.com', 'www.nytimes.com', 'www.latimes.com', 'www.washingtonpost.com', 'www.nbcnews.com', 'www.foxnews.com'];
var currentUrl = document.location.href;
var referrer =  currentUrl.match(/:\/\/(.[^/]+)/)[1];

//Making sure the code does what I want it to. As long as the link shows a number greater than -1, then the site extension is working console.log(referrer); console.log(acceptedWebsites.indexOf(referrer));

//var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)]; //document.location.href = url;

// image source goes through the following script function $('img').each(function(){

// creating the randomizing

var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
//Takes the current array and applies the source with the random function
$(this).attr('src', random);
//removing the stretch
 var theWidth = $(this).width();
            var theHeight = $(this).height();
            if (theWidth < theHeight) {
                $(this).height(150);
            }
            else {
                $(this).width(150);
            }
});

//alert ("Go to any of the follow websites: fox.com, nbc.com, nytimes.com, latimes.com, or cnn.com");

I have this array in javascript. I want to have it so that the user is automatically redirected to one of the links from the array, possibly randomly. I don't know if I can do this in javascript. I am using this for a chrome extension, so I don't know if I can use php.

These are fantastic answers, except they constantly redirect. I want it so that they are just redirected to one from the array once, not constantly redirect.

**Edit 2: I added my whole code because something is causing there to be a constant redirect instead of only once.

**Edit 3: I updated my code. The console.log proves that my new variables work and do ==-1. How can I use them to redirect?

回答1:

Get a random URL from the array, and redirect ?

if ( acceptedWebsites.indexOf(document.location.href) == -1 ) {
    var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
    document.location.href = url;
}


回答2:

Try the following:

var acceptedWebsites =['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];
    var number = Math.floor(Math.random() * acceptedWebsites.length);

number will generate a random number between 1 and the number of entries in your acceptedwebsites array.



回答3:

window.location = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];


回答4:

The basic jist of the logic would be...

var acceptedWebsites = ['http://www.cnn.com/', 'www.nytimes.com', 'www.latimes.com', 'http://www.washingtonpost.com/', 'http://www.nbcnews.com/', 'http://www.foxnews.com/'];

var randomLink = Math.floor(Math.random() * acceptedWebsites.length);

window.location = acceptedWebsites[randomLink];


回答5:

// Get random site
var randomSite = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];

// redirect to selected site
window.location = randomSite;


回答6:

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;


回答7:

Try this solution:

var size = acceptedWebsites.length;

var x = Math.floor((Math.random()* size)+1); 

Now use loop for value x-1 like

var location = acceptedWebsites[x-1];
window.location.href = location;

If we run this in loop ,we will get different value of x every time between 0-size of array and then we can use that random value to randomly redirect.



回答8:

window.location doesn't work since content scripts are unprivileged. Further more, window.location.href returns the current location, but it is not a method so you cannot overwrite it.

you'll need to:

Send redirect url from a content script to a background page:

var url = acceptedWebsites[Math.floor(Math.random()*acceptedWebsites.length)];
chrome.extension.sendRequest({redirect: url });

In a background page update tab's url which would cause redirect:

chrome.extension.onRequest.addListener(function(request, sender) {
    chrome.tabs.update(sender.tab.id, {url: request.redirect});
});