using vanilla js how do i make the url update - javascript

how do i make the window.location.url update every 30 seconds to the next id found in the array. Right now i have it alerting hello every few seconds but want the url to change instead
const myIds=['1_aq4jiqb','1_4u0ocu4u'];
for (let i = 0; i < myIds.length; i++) {
window.location.href = 'https://yahoo.com' + myIds[i]+ '/embed/iframe?';
}
setInterval(function(){ alert("Hello"); }, 3000);
<html>
</html>
update to the next Id after 30 seconds?

It's not possible unless you control each of those sites that you're redirecting to.
When you do window.location.href =, an entirely new document is loaded, with (and with only) the JavaScript(s) that new document links to. Anything that happens in your code after a single window.location.href = runs will be effectively ignored, because your old JavaScript does not carry over to the newly-loaded page.
Unless you control each of the sites you're redirecting to, the only way to accomplish this (on your browser only) would be to inject JavaScript code of your own into every site with a userscript.

If I understand what your're asking, just put the code inside a function, and call that at the setInterval.
const myIds=['1_aq4jiqb','1_4u0ocu4u'];
function switchId() {
for (let i = 0; i < myIds.length; i++) {
window.location.href = 'https://yahoo.com' + myIds[i]+ '/embed/iframe?';
}
}
setInterval(function(){ switchId() }, 3000);
<html>
</html>

Related

Redirecting script on webpage with delay location.redirect not working javascript

This is in script tag in my base html
const arraypathname = [`array of paths`]
var i = 0;
```
this function loops array of paths and should redirect on every path url from array with delay
```
function redirectFunc(){
setTimeout(function() {
var path_to_redirect = arraypathname[i];
window.location.redirect(path_to_redirect);
```
this doesn work when i used alert() with path it work and every 3 sec i get alert with different path. Why windows.location.replace not working?
```
i++;
if (i < 10) {
redirectFunc();
}
}, 3000)
}
```
i have a base.html file witch is used on every page on my site and i want to do presentation script witch will loop through all paths on web with delay
```
i dont know why its not working like that when i used alert(path_to_redirect) every
3 seconds it alert me with url

Is there a way to constantly update a variable?

I'm trying to make this thing where in one tab you type something, and in another it pops up. However, I have to constantly reload the page to get my next message. First, this is what I tried.
<!DOCTYPE html>
<html>
<body>
<p id="message"></p>
<script>
var x = localStorage.getItem('message')
var i;
for (i = 0; i < 5) {
document.getElementById('message').innerHTML = x;
}
</script>
</body>
</html>
HOWEVER, this puts the page in a constant reloading state. How would I do this? Thanks!
Use setInterval instead of a loop.
setInterval(function() {
var x = localStorage.getItem('message');
document.getElementById('message').innerHTML = x;
}, 1000);
This will update every second.
Instead of constantly polling for updates, you can set up an event listenener to catch every message that is sent. You can do this thanks to the storage event:
// Every time a change it made to this domain's localStorage (item added, changed, removed)
window.addEventListener('storage', function() {
// Update your DOM
document.getElementById('message').innerHTML = localStorage.getItem('message');
});
You have an infinite loop. A for loop has four steps.
Initialization: Declaring the variable and its initial value(Happens
once)
Condition: Checking the condition to continue the loop
Final
Expression: Usually where you handle your logic that will end your
loop like incrementing the i variable
Execution: Execute the code in the code block
Your method is working but it never stops working, hence why your browser doesn't stop loading.
The for loop moves too quickly anyway and it would be better to put to listen for a storage event update on your document.
var messageContainer = document.querySelector('#message')
window.addEventListener('storage', function() {
var text = localStorage.getItem('message')
messageContainer.textContent = text
}

Loop not stopping or not starting

I am making a small userscript for a survey site. Whenever I click the survey and it is indicated that I did not receive it the script is supposed to refresh a certain amount of times trying to claim the survey until it gives up.
(If you do not know what a userscript is, think of it as something that stays running all the time on a specific website, so you can control things using javascript selectors and stuff)
This is my script so far (the javascript portion as that is what the problem is in):
var elementExists = document.getElementsByClassName("message warning")[0];
if(elementExists)
{
var attempts = 0;
while(attempts<5)
{
attempts += 1;
location.reload();
if(elementExists)
{
//nothing
}
else
{
window.stop();
}
}
window.stop();
}
This is actually my first time using Javascript so I assumed that would be the reason for errors, but after 45 minutes of debugging I am completely baffled. If I remove that last "window.stop();" the code refreshes the webpage infinitely. If that stays there then the code doesn't even start. It seems almost as if the while loop is being skipped if the "window.stop();" is present. Is this something that Javascript does, or is the problem elsewhere?
If someone could lead me in the right direction or help me fix this I would be very grateful!
(Also I checked the selector to see if that is the issue, but I have done that correctly)
UPDATE: Turns out location.reload(); stops the script and thus forces a reload. Since I am creating a userscript I realized that I could use the Greasemonkey APIs (or more like stumbled upon). By using GM_setValue and GM_getValue I was able to work around this problem and the script successfully reloaded a certain amount of times (depending on the variable tries) and stopped when it finished. But after messing around a bit, then reverting to the older version the script, the script doesn't doesn't execute at all anymore; "counter < tries" seems to be false for some reason... could anyone figure out why? Also if documentation is needed:
https://wiki.greasespot.net/GM_getValue
https://wiki.greasespot.net/GM_setValue
var tries = 5;
var elementExists = document.getElementsByClassName("message warning")[0];
var counter = GM_getValue('counter', 0);
if(elementExists && counter < tries)
{
GM_setValue('counter', ++counter);
location.reload();
}
(Both counter and tries seem to be integer values.. so there should be in problem in comparing them...)
Also as suggested by #yuriy636 I attempted to reset the variables and created something like this
var tries = 5;
var elementExists = document.getElementsByClassName("message warning")[0];
var counter1 = GM_getValue('counter1', 0);
if(elementExists && counter1 < tries)
{
GM_setValue('counter1', ++counter1);
location.reload();
}
if(elementExists && counter1 == tries)
{
GM_deleteValue('counter1');
window.close();
}
if(!!elementExists)
{
GM_deleteValue('counter1');
return;
alert("stops script while hidden");
}
But again I am hit with the infinite loop.. RIP
Update 2: Not so RIP afterall... solution:
var tries = 50;
var elementExists = document.getElementsByClassName("message warning")[0];
var counter = GM_getValue('counter', 0);
if(elementExists && counter < tries)
{
GM_setValue("counter", counter + 1);
location.reload();
}
else
{
GM_deleteValue("counter");
}
if(elementExists && counter >= tries)
{
window.close();
}
100% Working, after indicated amount of tries, if error still exists the page is closed
The most likely problem is that you have location.reload() in your while loop. This causes the page to refresh before anything interesting happens in your loop. In this particular code I would expect the page to refresh seemingly infinitely because every time the page refreshes, it will refresh again.
Normally this would look more like:
var elements = document.getElementsByClassName("message warning");
for (var i = 0; i < elements.length; i++) {
console.log (elements[i]);
}
.getElementsByClassName returns an array of elements with the class message and/or warning which you are capturing only the 1st one [0]. Hope that helps.

Maintaining a Javascript variable between HTML pages to send to database?

I'm doing an experiment for university that involves timing how long participants take to read a simple webpage. Because of the nature of the experiment, I can't tell them I'm timing them before they visit the page, so on the following page I need to tell them that they were being timed and then offer an option to opt out if they object to their data being passed on to a database using a Python CGI script.
At the top of the first page I have this:
<script type="text/javascript" src="timing.js">
</script>
And at the bottom I have a link to take them to the next page, but also to stop the timer:
Click here when you are ready to proceed.
<button onclick="window.location = 'timer2.html'; stopTime()">Click Here</button>
...and in the .js file, I have the following:
var sec = 0;
function takeTime()
{
setInterval(function(){sec += 1},1000);
}
myTime = takeTime();
function stopTime()
{
clearInterval(myTime);
}
function showTime()
{
alert("Time is " + sec + " seconds.");
}
When I click the link to go the second page, the "sec" variable just resets to 0. If I take the declaration out of the .js file and put it in a separate script tag before the one that refers to the .js file in the first HTML page, the second HTML page doesn't recognise the variable "sec" at all. How can I store the time so that I can then either send it to a database or get rid of it from the second HTML page?
One way is to use the query string.
<button onclick="window.location = 'timer2.html?time=' + sec">Click Here</button>
They will be sent to eg timer2.html?time=252 if it took 252 seconds. Then use How can I get query string values in JavaScript? to get this value on timer2.html.
Javascript variables do not maintain their state from one page load to the next, so you will need another way to store that information. Another method besides passing it through the query string is HTML5 Local Storage. Using Local Storage, you can store values in the browser that are retrievable from one page load to the next, within the same domain.
For example, your first page:
var sec = 0;
localStorage.time = 0;
function takeTime()
{
setInterval(function(){sec += 1},1000);
}
myTime = takeTime();
function stopTime()
{
clearInterval(myTime);
localStorage.time = sec;
}
function showTime()
{
alert("Time is " + sec + " seconds.");
}
And somewhere in timer2.html:
var sec = localStorage.time;

Javascript bookmarklet/iFrame to auto-refresh loaded page if no activity detected within set timeframe?

I have a browser-based application that I use at work (as effectively all corporate apps are now browser-based for obvious reasons) that has an annoyingly short session timeout. I'm not sure precisely what the session timeout is set to, but it's something along the order of 5-10 minutes.
Inevitably whenever I have to use it the session has timed out, I enter the information into the app, submit it, and then the page loads with a brand new session without any of the information actually being passed on - all I get is a new session. I then have to re-enter the information and submit it again in order to have it actually pull up what I want. Of course, I could first refresh the page and then enter the info, but I never know if the session is timed out or not and occasionally it runs painfully slowly so this is a waste of time. Our development team's inability to foresee that little things like this are not only annoying, but also end up costing us a ton of money when you consider the amount of time lost (I work for a VERY large corporation) just waiting for the blasted thing to reload and then having to re-enter the submitted information if a pre-refresh was forgotten as it usually is happens to be beyond me. At some point I'm hoping to become the liaison between the programmers and our customer service body.
Anyway, I digress.
What I'm looking to do is this: I'd like to create a Javascript bookmarklet or something that will automatically refresh whatever page it happens to be on if activity isn't detected within a certain timeframe. This timeframe will be a bit short of whatever I end up figuring out what the session timeout is. Basically I just want to make the page reload itself every, say, five minutes if there hasn't been activity within that period. (I don't want it to refresh out of the blue because the time is up while I'm in the middle of using the app, the only time it should do the auto-refresh is if the app page has been sitting idle)
Can this be done with a Javascript bookmarklet? Should I program a page "wrapper" of sorts that loads the application page within an iFrame or something of the sort? The app site that I use has many subpages, and I'd prefer for it to refresh whatever page I happen to be on at the time if the auto-refresh timeout occurs. Of course, if that isn't possible I'd accept it just reloading the main site page if that's not easily possible since if I've been out of the app long enough for the timeout to happen then I likely don't need to still be on whatever account/page I was on at the time.
Hopefully I've explained myself well enough. The logic is simple - if no activity detected withing x amount of time, refresh the current page is the gist of it.
Thank you, my StackOverflow brethren, yet again for your assistance.
-Sootah
Since I have no ability to influence the coding of the page itself, I've got to have the most simple solution possible. A bookmarklet that times the last refresh/pageload and then refreshes the same page if the timeout is reached would be perfect.
If that's not possible, then if I could write a simple page that I could run from the local computer that'd do the same function by loading the page in a frame or something that'd also be acceptable.
EDIT 10/3/11 7:25am MST
Since I work graves and an odd schedule at work (and this site, unfortunately, being blocked there since it's considered a 'forum' - I work in finance, they're overly cautious about information leakage) before I award the bounty, does one of these event detectors detect the last time the page loaded/? Something like document.onload or whatnot. I'm thinking that setting the timer from the last time the page was loaded is going to be the simplest and most effective approach. My mouse may move over the browser that I have the site open in inadvertently while working on other things, and if the timer resets because of that without me actually having interacted with the site in such a way that a page loads/reloads then the session times out.
This is the bookmarklet code #1 for you, set up to FIVE seconds. Change time to what you like more.
javascript:
(function () {
var q = null;
function refresh() { window.location.reload(); }
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
document.body.onclick = x;
document.body.onmousemove = x;
document.body.onmousedown = x;
document.body.onkeydown = x;
}())
p.s.: would have been nicer to include eventListeners, but i suppose you need to support IE8, too, so i replaced them with inline events, - if you DON'T need IE8, use code #2:
javascript:
(function () {
var q = null;
function refresh() { window.location.reload(); }
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
document.body.addEventListener( "click", x, false );
document.body.addEventListener( "mousemove", x, false );
document.body.addEventListener( "mousedown", x, false );
document.body.addEventListener( "keydown", x, false );
}())
edit: in response to comments, here is code #3 with pulling, instead of refreshing page. Yet, despite advices to use iframe, i decided it might be desirable to not execute scripts on that page, so we will use img instead:
javascript:
(function () {
var q = null;
var u = window.location.href;
var i = document.createElement('img');
i.style = "width: 1px; height: 1px;";
document.body.appendChild(i);
function refresh() {
i.src = "";
i.src = u;
x();
}
function x() { clearTimeout(q); a(); }
function a() { q = setTimeout( refresh, 5000 ); }
var evs = ['click', 'mousemove', 'mousedown', 'keydown'];
for( var j = 0; j < evs.length; j++) {
document.body['on'+evs[j]] = x;
}
}())
Create a bookmark and place the code below in the "url" value. Please note that you should change the values of "sessiontimeout" and "checkinterval". They're both in milliseconds.
javascript:(function(){var lastmove = new Date().valueOf(),sessiontimeout=10000,checkinterval=1000;document.onmousemove = function(e){lastmove= new Date().valueOf();};timer = setInterval( function() {var differential = (new Date().valueOf() - lastmove);if (differential > sessiontimeout) {var iframe = document.getElementById("bkmrkiframerefresher");if (iframe) { document.getElementsByTagName("body")[0].removeChild(iframe);} iframe = document.createElement("iframe");iframe.setAttribute("src", "/");iframe.setAttribute("width", 0);iframe.setAttribute("height", 0);iframe.setAttribute("style", "width:0;height:0;display:none;");iframe.setAttribute("id", "bkmrkiframerefresher");document.getElementsByTagName("body")[0].appendChild(iframe);lastmove = new Date().valueOf();} }, checkinterval);})();
This is a bookmarklet that will inject the code below in the page. I tested the bookmarklet in Chrome. It worked on multiple sites except stackoverflow, it seems that they block framing for security reasons. Before you leave your desk, open the website which session you wanna keep alive, then click the bookmarklet on it. Once you're back, refresh the page in order to get rid of the running timers.
The formatted (and commented) code is:
<script type="text/javascript">
// last time the mouse moved
var lastmove = new Date().valueOf();
var sessiontimeout=10000;
var checkinterval=1000;
// reset the last time the mouse moved
document.onmousemove = function(e){
lastmove= new Date().valueOf();
}
// check periodically for timeout
timer = setInterval( function() {
var differential = (new Date().valueOf() - lastmove);
if (differential > sessiontimeout) {
var iframe = document.getElementById("bkmrkiframerefresher");
// iframe already exists, remove it before loading it back
if (iframe) {
document.getElementsByTagName("body")[0].removeChild(iframe);
}
// alert("more than 10 secs elapsed " + differential);
// create an iframe and set its src to the website's root
iframe = document.createElement("iframe");
iframe.setAttribute("src", "/");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("id", "bkmrkiframerefresher");
iframe.setAttribute("style", "width:0;height:0;display:none;");
document.getElementsByTagName("body")[0].appendChild(iframe);
// reset counter.
lastmove = new Date().valueOf();
}
}, checkinterval);
</script>
Stefan suggested above that you need no logic besides polling. The edited code is the following:
<script type="text/javascript">
var pollInterval=1000;
timer = setInterval( function() {
var iframe = document.getElementById("bkmrkiframerefresher");
// iframe already exists, remove it before loading it back
if (iframe) {
document.getElementsByTagName("body")[0].removeChild(iframe);
}
// create an iframe and set its src to the website's root
iframe = document.createElement("iframe");
iframe.setAttribute("src", "/");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("id", "bkmrkiframerefresher");
iframe.setAttribute("style", "width:0;height:0;display:none;");
document.getElementsByTagName("body")[0].appendChild(iframe);
}
}, pollInterval);
</script>
This code only reload the page once
Here is a bookmarklet(inspired by Kaj Toet's pseudo code), tested in Chrome and Safari, change the timeout value with the var time at the start of the line
Onliner:
javascript:var time = 500; var timeoutFunc = function(){location.reload(true);};timeout = setTimeout(timeoutFunc,time);document.onmousemove = function() {clearTimeout(timeout);timeout = setTimeout(timeoutFunc,time); };
Code
//The time in milliseconds before reload
var time = 500;
//The function that is called when the timer has reached 0
var timeoutFunc = function() {
location.reload(true);
};
//start the timer
timeout = setTimeout(timeoutFunc,time);
//restart the timer if the mouse is moved
document.onmousemove = function() {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunc,time);
};
pseudocode
timeout = settimeout("call",200);
document.onmousemove = function() { timeout = new timeout("call",200); }
function call() {
document.refresh();
}
like this?

Categories

Resources