javascript - 从数组随机 URL 重定向

标签 javascript php google-chrome-extension hyperlink

/** * 政治动物 * contentscript.js 加载到 list .json 中列出的每个页面上 * 该插件将新闻网站网站上的所有图像替换为以下图片 * 穿西装的动物,作为对新闻的评论。专为 Web 2 打造 * 2013 年 11 月 20 日 */

//随机图像数组

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'];

//重定向

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];

//确保代码执行我想要的操作。只要链接显示的数字大于 -1,则站点扩展正在运行 控制台.log(引用者); console.log(acceptedWebsites.indexOf(referrer));

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

//图像源经过以下脚本函数 $('img').each(function(){

//创建随机化

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(“转到以下任意网站:fox.com、nbc.com、nytimes.com、latimes.com 或 cnn.com”);

我在 JavaScript 中有这个数组。我希望拥有它,以便用户自动重定向到数组中的链接之一(可能是随机的)。我不知道我是否可以在 javascript 中做到这一点。我将其用于 chrome 扩展,所以我不知道是否可以使用 php。

这些都是很棒的答案,只是它们不断重定向。我希望它们只是被重定向到数组中的一个,而不是不断重定向。

**编辑 2:我添加了整个代码,因为某些原因导致不断重定向而不是仅一次。

**编辑 3:我更新了我的代码。 console.log 证明我的新变量可以工作并且 =-1。我如何使用它们来重定向?

最佳答案

从数组中获取随机 URL,并重定向?

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

关于javascript - 从数组随机 URL 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100450/

相关文章:

javascript - jquery中的正则表达式只允许匹配一个

javascript - 打印时调整 Google map 大小

php - Laravel 更新并选择

php - PHP为什么我在数组女巫中得到0值只包含字符串

javascript - 努力确定如何使用下拉菜单存储和检索 JSON

javascript - 如何从较小的 Canvas 上获得高分辨率图像?

javascript - 获取 angularJS 中的 html 元素

javascript - 调用函数不更新数据

javascript - 在 Chrome Devtools 中记录用户操作 : Possible?

javascript - Chrome 扩展程序在检测 iframe 时失败