Changing webpage by math.random using cookies - javascript

I am looking for a way to change webpage through a list without getting the same page twice. I have tried shuffling a list however when a new page is loaded it just reloads the script. So I guess I need to use some sort of cookie. However I am quite new to javascript. Can anyone please help me?
I was thinking something like this, just with a cookie of some sort:
var pages = ['sang1.html','sang2.html','sang3.html','sang4.html','sang5.html','sang6.html','sang7.html','sang8.html','sang9.html','sang10.html','sang11.html','sang12.html','sang13.html','sang14.html','sang15.html','sang17.html','sang18.html','sang19.html','sang20.html','sang21.html''sang22.html','sang23.html','sang24.html','sang25.html','sang26.html','sang27.html','sang28.html','sang29.html','sang30.html','sang31.html','sang32.html''sang33.html','sang34.html','sang35.html'];
var page = Math.floor((Math.random() * pages.length) + 1);
window.location.href = pages[page];
pages.splice(page);

var page = pages[Math.floor(Math.random() * pages.length)]
window.location.href = pages[page]

Here is a basic solution using localstorage as cookies would not be a good idea due to round trip
var pages = ['sang1.html', 'sang2.html', 'sang3.html', 'sang4.html', 'sang5.html', 'sang6.html', 'sang7.html', 'sang8.html', 'sang9.html', 'sang10.html', 'sang11.html', 'sang12.html', 'sang13.html', 'sang14.html', 'sang15.html', 'sang17.html', 'sang18.html', 'sang19.html', 'sang20.html', 'sang21.html'];
var page, visitedPages = JSON.parse(localStorage.getItem("visitedPages"));
if (visitedPages === null) {
visitedPages = [];
}
var unVisitedPages = difference(visitedPages, pages);
if(unVisitedPages.length === 0){//All pages visited at once
//add your logic when all page visited
}
else{
page = unVisitedPages[Math.floor(Math.random() * unVisitedPages.length)];
localStorage.setItem("visitedPages", JSON.stringify(visitedPages.push(page)));
window.location.href = page; //append if you want to kill cache"?ck="+new Date().getTime()
}
function difference(a,b){//b -a
var c = [];
for(var i=0; i< b.length; i++){
if(a.indexOf(b[i]) === -1){
c.push(b[i]);
}
}
return c;
}

Related

Is it possible to change a string parameter with a For Loop?

I'm not a programmer, neither studying something related to it, but just someone who wants to run a code to make my work life easier.
I need to open 50 tabs. Opening one by one takes so much time because when I click the open button, it shows me the new tab opened and then I have to go back to the original page to open the next one and so on.
After a weekend of doing some research, I found that Google Chrome has a "Console" that can be modified to make a webpage work as you want.
The code that runs to open a tab in this webpage is the following. I've run this code in the console and surprisingly it works:
if(typeof jsfcljs == 'function'){
jsfcljs(document.getElementById('ngFindListForm'), {'ngFindListForm:tblDataTable:0:j_id178':'ngFindListForm:tblDataTable:1:j_id178'},'_blank');}
And to open the next tab is:
if(typeof jsfcljs == 'function'){
jsfcljs(document.getElementById('ngFindListForm'),{'ngFindListForm:tblDataTable:1:j_id178':'ngFindListForm:tblDataTable:1:j_id178'},'_blank');}
As you see, the "only" part of code that changes is the number between colons (0 and 1).
So, according to my basic-high school-programming skills, I think I can change those number with a For Loop from 0 to 49 (50 tabs). I've tried that like this:
for (i = 0; i < 50; i++) {
param = 'ngFindListForm:tblDataTable:' + i +':j_id178';}
And then using this param something like this:
if(typeof jsfcljs == 'function'){
jsfcljs(document.getElementById('ngFindListForm'),{param:'ngFindListForm:tblDataTable:1:j_id178'},'_blank');}
But it's not working. It just makes to open the same page I'm on in a new tab.
Maybe the logic I have figured out how to make this work is totally wrong, but this is why I came here to ask you.
Thanks
move your code inside foreach and use [param] (ES6)
var form = document.getElementById('ngFindListForm');
if (typeof jsfcljs == 'function') {
for (i = 0; i < 50; i++) {
var param = 'ngFindListForm:tblDataTable:' + i + ':j_id178';
jsfcljs(form, {
[param]: 'ngFindListForm:tblDataTable:1:j_id178'
}, '_blank');
}
}
OR
var form = document.getElementById('ngFindListForm');
if (typeof jsfcljs == 'function') {
for (i = 0; i < 50; i++) {
var obj = {};
obj['ngFindListForm:tblDataTable:' + i + ':j_id178'] = 'ngFindListForm:tblDataTable:1:j_id178';
jsfcljs(form, obj, '_blank');
}
}
There are a few ways to do it, the easiest would be to use an object and set the string
function jsfcljs(e, o, t) {
console.log(o);
}
for (let i = 0; i < 5; i++) {
var obj = {}
obj['ngFindListForm:tblDataTable:' + i + ':j_id178'] = 'ngFindListForm:tblDataTable:' + i + ':j_id178'
jsfcljs(document.getElementById('ngFindListForm'), obj, '_blank');
}
<div id="ngFindListForm"></div>

Random order for flash files on page using php, ajax, javascript

I have no experience of Ajax and little experience of java, lots of sql & php experience so I will probably receive lots of comments for this question but here goes.
Ultimately I have 4 flash swf files that needs to be rotated on the website main page randomly. So I've found a shuffle javascript function online and implemented that. Now I need to implement this ajax function (from this post Javascript change inner html of div that conatins php include ) to change the swf files according to the numbers in the array, so if tempArray = 4,3,1,2 then display flash-4.php for 3sec, then change to flash-3.php for 3sec, then change to flash-1.php for 3sec, etc.
I've got the shuffle part working:
<script type="text/javascript">
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
var tempArray = [ 1, 2, 3, 4 ]
tempArray.shuffle();
// and the result is...
alert(tempArray);
//alert(tempArray[0]);
</script>
I've got the ajax part where it's replacing the content working:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function()
{
$.ajax( "flash-2.php" )
.done(function(res) {
document.getElementById("swfdiv").innerHTML = res;
})
},
3000);
</script>
But how do I put it together to rotate depending on the array values?
Why not something like this?
var index = 0;
var tempArray = ...
setInterval(function()
{
index = (index + 1) % tempArray.length;
$.ajax( "flash-" + tempArray[index] + ".php" )
.done(function(res) {
document.getElementById("swfdiv").innerHTML = res;
})
},
3000);

JavaScript Find Specific URLs.

Alright, I've been working on a userscript that redirects when a specific page is loaded.
This is what I have so far:
function blockThreadAccess() {
var TopicLink = "http://www.ex.com/Forum/Post.aspx?ID=";
var Topics = [ '57704768', '53496466', '65184688', '41182608', '54037954', '53952944', '8752587', '47171796', '59564382', '59564546', '2247451', '9772680', '5118578', '529641', '63028895', '22916333', '521121', '54646501', '36320226', '54337031' ];
for(var i = 0; i < Topics.length; i++) {
if(window.location.href == TopicLink + Topics[i]) {
// Execute Code
}
}
}
The function is called on the page load, but it doesn't seem execute the code.
What it's supposed to do is check to see if the user is on that specific page, and if he is then execute the code.
Say someone goes to this link - http://www.ex.com/Forum/Post.aspx?ID=54646501, it then redirects the use. I'm trying to make it efficient so I don't have to add a bunch of if statements.
try converting both to lower case before comparing
var loc = window.location.href.toLowerCase();
var topicLnk = TopicLink.toLowerCase();
for(var i = 0; i < Topics.length; i++) {
if(topicLnk + Topics[i] == loc) {
// Execute Code
}
}

How to run a setInterval that loops and tries a max of 10 times before breaking?

I have the following to try to reload on a connection drop:
setInterval(window.location.reload(), 1000);
My concern with this is that it could continue forever, ddos'ing my application.
How can I update the above to try at max 20 times before giving up and breaking?
Thank you
This makes me feel dirty, but you could update/extract the window hash with each refresh:
function hack () {
var last = parseInt(location.hash.slice(1));
if (last < 20) {
window.location.hash = last + 1;
window.location.reload();
}
}
window.location.hash = 0;
setTimeout(hack, 1000);
You need to persist some counter state from one page load to the next so you can know when 20 reloads have been done. Your options are:
A hash value
A query parameter
A cookie value
Something stored in local storage
If you don't need this value to persist beyond just the reloads of this page, then options 1) and 2) are better as they are only as persistent as you need. A hash value will not be sent to your server, but could interfere with other uses of the hash value. A query parameter would be sent to the server, but any reasonable server will ignore query values it doesn't know and it won't interfere with anything else. I'd probably pick a query parameter and have actually used one to avoid infinite redirection loops in some of my code. You could implement option 2) like this:
function checkAutoReload() {
var currentCnt = 0;
var re = /(\?|&)(reloadCnt=)(\d+)/;
var param = window.location.search.match(re), newURL;
if (param) {
currentCnt = parseInt(param[3], 10);
newURL = window.location.href.replace(re, "$1$2" + (currentCnt + 1))
} else {
newURL = window.location.href;
newURL += window.location.search ? "&" : "?";
newURL += "reloadCnt=1";
}
if (currentCnt < 20) {
window.location.replace(newURL);
}
}
setTimeout(checkAutoReload, 1000);
Notice, there's no need for a setInterval() because a given page's code only runs once before it either reloads or finds that it is done reloading.
Store the reloadCount in localStorage
MDN DOM Storage
var maxReload = 20;
var reloadPage = function() {
if (typeof a !== "undefined" && a !== null) {
console.log(localStorage.reloadCount);
localStorage.reloadCount = 0;
};
var reloadCount = parseInt(localStorage.reloadCount, 10);
console.log(reloadCount);
if (reloadCount < maxReload) {
reloadCount += 1;
localStorage.reloadCount = reloadCount;
// RELOAD CODE HERE
};
};
// call reloadPage from your code
reloadPage();

Executing Javascript code after loading refreshed page

I have a Javascript file that is split into to two parts. The first part of the code ends by refreshing the current page. I would like to try to get the second part of the code to execute as soon as the page reloads, but I am having trouble finding a way to implement this. I pretty much want a way to do
window.onload = someFunction()
except that it activates the function after reloading the page due to the first part of the Javascript. Is there an effective way to do this?
You could do that using Jquery.
This is executed on page loading
$(function() {
callMyFunction()
});
Use
document.onload = somefunction()
Instead . This will get executed immediately after the DOM loads .
You can also use the jQuery to do the same like
$(document).ready(function(){
somefunction();
});
The only way I can think of is to add query string value when refreshing, then read that value and act upon it.
You can use such code:
function ParseQueryString() {
var result = [];
var strQS = window.location.href;
var index = strQS.indexOf("?");
if (index > 0) {
var temp = strQS.split("?");
var arrData = temp[1].split("&");
for (var i = 0; i < arrData.length; i++) {
temp = arrData[i].split("=");
var key = temp[0];
var value = temp.length > 0 ? temp[1] : "";
result[key] = value;
}
}
return result;
}
window.onload = function WindowLoad() {
var QS = ParseQueryString();
var reloaded = QS["reloaded"];
if (reloaded === "1") {
//execute second part of code
}
}
Then when reloading, redirect to same page adding ?reloaded=1 otherwise (if this flag is already raised) don't refresh the page again to avoid infinite loop.

Categories

Resources