/**
* 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?
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;
}
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.
window.location = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
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];
// Get random site
var randomSite = acceptedWebsites[Math.floor(Math.random() * acceptedWebsites.length)];
// redirect to selected site
window.location = randomSite;
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;
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.
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});
});
Related
I am having a java scripts for a game, but this game is like a test and if the user failed the game he will retake the test (redo the game), but I want a specific number of attempts only for the user to re do the test. now what I have, makes the user start from the beginning without any limitations even if he re do it for like 100 times, he will keep go back to the beginning.
I need in the fail massage to give another attempt (form like max 4 attempts) if failed once then the next fail massage to give him 3 tries and then 2 and then last one, and then he can't redo the test.
Script 1;
var player=GetPlayer();
var textArray = [];
for (var i = 1; i <= 15; i++) {
textArray.push(i);
};
var itemsLeft = textArray.length;
textArray=textArray.map(String).toString();
player.SetVar("Text_Array", textArray);
player.SetVar("Items_Left", itemsLeft);
Script 2:
//get the StoryLine player
var player=GetPlayer();
//get Storyline variable value as a string
var textArray=player.GetVar("Text_Array");
//Convert string to a numeric array
numArray=textArray.split(",").map(Number);
//Get a random number from the array and send it to StoryLine
var randNum = numArray[Math.floor(Math.random() * numArray.length)];
player.SetVar("Random",randNum);
//Remove the random number from your array and get the array's length
numArray.splice(numArray.indexOf(randNum), 1);
var itemsLeft=numArray.length;
//Convert array to a string and send it back to SL along with the array's length
textArray=numArray.map(String).toString();
player.SetVar("Items_Left", itemsLeft);
player.SetVar("Text_Array", textArray);
I have a static website (HTML, CSS, JS) where people can keep track of their times.
I would like it so that they can generate a link that creates a new html page to display their time. I would like this link to be shareable, so other people can see the time.
e.g.
I time myself and get a really good time that I would like to share. I generate a link which is linked to that time, and send it to my friends, who on clicking that link can see the time & other details associated with it.
Is this possible, and if it is, how?
Thanks
I made a working demo to show you what you can do w/o database and keep data unmodified and "secure".
When you press "share" it encode with btoa JS function your time and name value to url and then generate a link.
When someone go to link, it read the params from URL ?time=XXX?name=XXXX and then decode them with atob JS function then set name et timer elements text to display on page.
NOTE: Remove first const queryString = '?time=MTBtMjFz&name=Q29kZXJHdXJ1WFla'; and uncomment const queryString = '?time=MTBtMjFz&name=Q29kZXJHdXJ1WFla'; to make this code work on your page server.
window.onload = function() {
let timerEl = document.getElementById('timer');
let nameEl = document.getElementById('name');
const queryString = '?time=MTBtMjFz&name=U2FtIEJaRVo='; //Get the time parameter index.html?time=MTBtMjFz&name=Q29kZXJHdXJ1WFla" from URL (encoded with javascript)
//Uncomment next line in production
//const queryString = window.location.search;
if (queryString !== '') {
const urlParams = new URLSearchParams(queryString);
const time = urlParams.get('time');
const name = urlParams.get('name');
timerEl.innerText = window.atob(time);
nameEl.innerText = window.atob(name)
}
let share = document.getElementById('share');
share.addEventListener('click', function(e) {
//Generate URL
document.getElementById('sharelink').innerText = 'http://example.com/timer.html?time=' + window.btoa(timerEl.innerText) + '&name=' + window.btoa(nameEl.innerText);
});
}
<!-- Consider this page URL is http://example.com/timer.html -->
<main>
<h1>I'm <span id="name"></span></h1>
<h2> My time is: <span id="timer"></span></h2>
<button id="share">Share my time !</button>
<h3 id="sharelink"></h3>
</main>
if you just need show time and not worry with security you can use get parameters. You make url like: yoursite.com/time?time=20 and in your time page:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
// Your time as stored in this variable.
var time = findGetParameter("time");
but i recommend a database with server-side langague like PHP, NODE or .NET.
var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()
Hi this is my cocde to load an xml file:
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
this.url = url;
xmlLoader.load(new URLRequest("C:\Documents and Settings\...books.xml"));
function LoadXML(e:Event):void {
xmlData = new XML(e.target.data);
trace(xmlData.author.text()[0]);
}
but I want to generate a random number in this line trace(xmlData.author.text()[0]);
so instead of [0] there needs to be an random number between the [ ]
Continuation from comments; you can't just copy and paste your way through a problem - you have to apply a little thought...
// break down the problem, if this line returning
// an array lets assign it to a variable.
var authorText = xmlData.author.text();
// random index should be within the bounds of the array length
var random = Math.floor( Math.random() * authorText.length );
// put it together
trace( authorText[random] );
Assuming the rest of your code is okay then this should work - here's a demo in javascript though I suspect you are doing something in actionscript / flash (though they both conform to ECMAScript so it should work just the same).
Hi I have a script wich changes the source of an image ie webpics/1.jpg to webpics/2.jpg on click of an image. One problem i am having though is that the script will still work for one more image after there is images, so if i have 11 images i can press next 11 times and will get an empty image, what i would like is for the script to run a error check and stay on the current image if the next on doesn't exist. Here is the script:
$("#prev, #next").click(function() {
var currentNumber = parseInt($("#image1").attr("src").split('gallery/')[1]); // get the
number
var newNumber = ($(this).attr("id")=="next")?currentNumber+1:currentNumber-1;
var testImage = new Image();
testImage.onload=function() {
var img = $("#image1");
img.attr("src",this.src);
img.css("visibility","visible");
}
testImage.onerror=function() {
$("#image1").css("visibility","hidden");
}
testImage.src="http://www.yogahealth.net.au/gallery/"+newNumber+".jpg";
return false;
});
Do you know how many images exist? If so, just test if the new number would exceed the total count (if newNumber ...) and do nothing (i.e. skip the part where you change the testImage.src.
For example, you need to have the total count in the variable totalImages, then you could do:
$("#prev, #next").click(function() {
var currentNumber = parseInt($("#image1").attr("src").split('gallery/')[1]); // get the number
var newNumber = ($(this).attr("id")=="next")?currentNumber+1:currentNumber-1;
var totalImages = // get the number of total images here
if ((newNumber > totalImages) || (newNumber <= 0)) {
return false; // just do nothing
}
// here comes the rest of your code
});
Note that I also added the possibility that your number becomes less than 0 or 0, depending on whether you have an image named 0. If yes, you can change the <= to <, otherwise it won't show the 0 image.
In order to get this number into your Javascript code, you could either render the code using PHP and insert it into your script with <?php echo $total; ?> or you extract it from another element from the HTML page, as you did with the currentNumber.