setInterval change Interval - javascript

Hello I am new in javascript, I am making chrome extension, this extension contains the setInterval command, I want to change the time with javascript to the textbox I have added to a website. This change should remain when I refresh the page, how can I do this.
My content script start document_end
var Refresh = setInterval(clickerStart,4000)
function clickerStart(){
var selection1 = document.querySelector("#\\30 ") !== null;
if (selection1) {
location.reload();
} else {
console.log("Islem Bulundu.");
};
}
//textbox
var Interval = document.createElement("INPUT");
Interval.setAttribute("type", "text");
Interval.setAttribute("value", " ");
document.body.appendChild(Interval);

If you are not handling with sensitive data, which I think it is the case, you can use localStorage or cookies to store and reuse data (the interval time) until the user returns to the page (after refreshing it or reopening it).
Here's an explanation on how to set cookies:
https://www.w3schools.com/js/js_cookies.asp

Related

How to automatically reload a web page

I want my website page to reload once when it has already opened for the first time. I wrote this function in my javascript file for that...
var i;
$(document).ready(function(){
for ( i=0;i<1;i++){
if(i===0){
location.reload();
break;
}
}
});
But the page keeps reloading again and again as if the above function was a recursive one.
How do I do this?
P.S I'm doing it because of this issue.
<script type='text/javascript'>
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
} else
localStorage.removeItem('firstLoad');
}
})();
</script>
Here is what's happening:
The page loads for the first time, jQuery calls any handlers on the document.ready event
The page reloads
The document.ready call is made again
repeat
Out of curiosity, why would you want to do that? And why do you have a for loop that will run for one iteration?
Also, to answer your question as far as I know the only way to make sure the page doesn't reload is use a cookie that lasts for about 5 seconds. Then, on document.ready check for that cookie and if it exists then don't reload.
You must either set a cookie (or use javascript's localStorage), or use xhr to retrieve a value held on a remote server.
If you want to use cookies, it's as simple as
document.cookie = "username=John Doe";
where the document.cookie is a query string of the form (x=y;a=b;n=z)
If you want the page to reload every time the user vists, be sure to unset the cookie once you've done any necessary processing when a page reload has been set.
$( window ).load(function() {
if (window.location.href.indexOf('reload')==-1) {
window.location.replace(window.location.href+'?reload');
}
});
Code is ok. But if the page is opened from another page with a link to an id (.../page.html#aa) the code only works with firefox. With other browsers reload the page without going to id. (Sorry for my english).
I found the solution with this code. It is assumed that the page is refreshed no earlier than one hour. Otherwise, add minutes to the oggindex variable.
<script>
var pagina = window.location.href;
var d = new Date();
var oggiindex = d.getMonth().toString()+'-'+d.getDate().toString()+'-'+d.getHours().toString();
if (localStorage.ieriindex != oggiindex)
{
localStorage.setItem("ieriindex", oggiindex);
window.location.replace(pagina);
}
</script>
Yours code executed each time $(document).ready(), so it's not surprise that your loop is infinity - each load finished as ready state.
If you give more detailed requirements we can solve it with no using window object as data holder. It's bad way but you can set it for test.
Window object stores variables not depend on reload because it's higher then document.
Let's try:
if( window.firstLoad == undefined ){
// yours code without any loop
// plus:
window.firstLoad = false;
}
You can make it with localStorage API.
Check this link also, it's giving more information about window object variables:
Storing a variable in the JavaScript 'window' object is a proper way to use that object?

How to make a jquery count-down timer that doesn't restart on refresh

I am creating a web template for sale, but I can't make timer count down, I don't how to make it. I need timer count down (when a date is added, it should be decreased), also it should not restart on refresh time or shut down time. Please help me to do this code... I will use it in my template.
If you are not working with a database, then you can use HTML5 localstorage. Store a variable on the users local machine if they have already visited. When the page loads, do a check of local storage for that variable. If it is not null, then don't init the timer as they have already been on the site.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Create localstoreage var:
var myStorage = localStorage;
If user loads page - store true in "visited"
localStorage.setItem('visited', 'true');
If visitor reloads page, check for visited == true, and if true, dont trigger timer.
var hasVisited = function() {
var didVisit = myStorage.getItem('visited');
if(didVisit == "true"){
//do nothing}
}else{
//start your timer
};

Continual counter regardless of page refresh

I have this piece of jQuery that currently increments a number by one every 5 seconds. The problem I have is that its client side, therefore it resets every time you refresh the page.
Instead I'd like the counter to continue even if you are away from the site and regardless of how many times you refresh the page, which is why I thought a server side script such as PHP would be better suited to my use case. If not please suggest otherwise.
I've setup a working fiddle of what I currently have with jQuery: http://jsfiddle.net/f354bzy5/
What would be the PHP to recreate this affect that include my requirements above?
Here's the Jquery I'm using:
//Counter
var counter = 22000000000;
$(".count").html(counter);
setInterval(function () {
$(".count").html(counter);
++counter;
}, 5000);
Check this DEMO
//Counter
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
$(".count").html(counter);
++counter;
localStorage.setItem('counts',counter);
}, 1000);
Highlight on localStorage
localStorage is an implementation of the Storage Interface. It stores
data with no expiration date, and gets cleared only through
JavaScript, or clearing the Browser Cache / Locally Stored Data -
unlike cookie expiry.
Can you store counter in cookie.
document.cookie = counter.
so you can get last value from cookie, if user refresh the page.
It comes down to two simple choices for you. Just choose the right one which better fits your requirement:
Choose Cookie : If you want the server side to access the counter. Remember cookies are sent along with the requests by default.
Choose Local Storage : If you don't want to send the counter along with requests every time, you are supposed to go for local storage.
You could do it with localStorage. Here's how I am doing it. You can tweak it as you need.
//detecting support for localStorage.
if (window.localStorage) {
//counterValue already exists in localStorage? Let's use that or set to zero.
var counterValue = localStorage.counterValue || 0;
setInterval(function() {
//increment the counter and store updated vale in localStorage as well.
localStorage.counterValue = ++counterValue;
//put it in your HTML if you might
$(".count").html(counterValue);
}, 5000);
}
How about using localStorage with some utility functions? Bear in mind that this is a client side solution and the item would be wiped off when the user deletes the browser cache/local data etc.
function isLocalStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
function setCounter(key, val) {
localStorage.setItem(key, val);
}
function getCounter(key) {
return parseInt(localStorage.getItem(key), 10);
}
(function() {
var key = "myCounter";
var counter = isLocalStorage() && getCounter(key) || 1;
var $placeholder = $(".count");
$placeholder.html(counter);
setInterval(function () {
counter++;
$placeholder.html(counter);
isLocalStorage() && setCounter(key, counter);
}, 2000);
}());
-- Demo --

Is it possible to know how long a user has spent on a page?

Say I've a browser extension which runs JS pages the user visits.
Is there an "outLoad" event or something of the like to start counting and see how long the user has spent on a page?
I am assuming that your user opens a tab, browses some webpage, then goes to another webpage, comes back to the first tab etc. You want to calculate exact time spent by the user. Also note that a user might open a webpage and keep it running but just go away. Come back an hour later and then once again access the page. You would not want to count the time that he is away from computer as time spent on the webpage. For this, following code does a docus check every 5 minutes. Thus, your actual time might be off by 5 minutes granularity but you can adjust the interval to check focus as per your needs. Also note that a user might just stare at a video for more than 5 minutes in which case the following code will not count that. You would have to run intelligent code that checks if there is a flash running or something.
Here is what I do in the content script (using jQuery):
$(window).on('unload', window_unfocused);
$(window).on("focus", window_focused);
$(window).on("blur", window_unfocused);
setInterval(focus_check, 300 * 1000);
var start_focus_time = undefined;
var last_user_interaction = undefined;
function focus_check() {
if (start_focus_time != undefined) {
var curr_time = new Date();
//Lets just put it for 4.5 minutes
if((curr_time.getTime() - last_user_interaction.getTime()) > (270 * 1000)) {
//No interaction in this tab for last 5 minutes. Probably idle.
window_unfocused();
}
}
}
function window_focused(eo) {
last_user_interaction = new Date();
if (start_focus_time == undefined) {
start_focus_time = new Date();
}
}
function window_unfocused(eo) {
if (start_focus_time != undefined) {
var stop_focus_time = new Date();
var total_focus_time = stop_focus_time.getTime() - start_focus_time.getTime();
start_focus_time = undefined;
var message = {};
message.type = "time_spent";
message.domain = document.domain;
message.time_spent = total_focus_time;
chrome.extension.sendMessage("", message);
}
}
onbeforeunload should fit your request. It fires right before page resources are being unloaded (page closed).
<script type="text/javascript">
function send_data(){
$.ajax({
url:'something.php',
type:'POST',
data:{data to send},
success:function(data){
//get your time in response here
}
});
}
//insert this data in your data base and notice your timestamp
window.onload=function(){ send_data(); }
window.onbeforeunload=function(){ send_data(); }
</script>
Now calculate the difference in your time.you will get the time spent by user on a page.
For those interested, I've put some work into a small JavaScript library that times how long a user interacts with a web page. It has the added benefit of more accurately (not perfectly, though) tracking how long a user is actually interacting with the page. It ignore times that a user switches to different tabs, goes idle, minimizes the browser, etc.
Edit: I have updated the example to include the current API usage.
http://timemejs.com
An example of its usage:
Include in your page:
<script src="http://timemejs.com/timeme.min.js"></script>
<script type="text/javascript">
TimeMe.initialize({
currentPageName: "home-page", // page name
idleTimeoutInSeconds: 15 // time before user considered idle
});
</script>
If you want to report the times yourself to your backend:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","ENTER_URL_HERE",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
xmlhttp.send(timeSpentOnPage);
TimeMe.js also supports sending timing data via websockets, so you don't have to try to force a full http request into the document.onbeforeunload event.
The start_time is when the user first request the page and you get the end_time by firing an ajax notification to the server just before the user quits the page :
window.onbeforeunload = function () {
// Ajax request to record the page leaving event.
$.ajax({
url: "im_leaving.aspx", cache: false
});
};
also you have to keep the user session alive for users who stays long time on the same page (keep_alive.aspxcan be an empty page) :
var iconn = self.setInterval(
function () {
$.ajax({
url: "keep_alive.aspx", cache: false });
}
,300000
);
then, you can additionally get the time spent on the site, by checking (each time the user leaves a page) if he's navigating to an external page/domain.
Revisiting this question, I know this wouldn't be much help in a Chrome Ext env, but you could just open a websock that does nothing but ping every 1 second and then when the user quits, you know to a precision of 1 second how long they've spent on the site as the connection will die which you can escape however you want.
Try out active-timeout.js. It uses the Visibility API to check when the user has switched to another tab or has minimized the browser window.
With it, you can set up a counter that runs until a predicate function returns a falsy value:
ActiveTimeout.count(function (time) {
// `time` holds the active time passed up to this point.
return true; // runs indefinitely
});

How can I get the time a particular window is open?

I have a simple user survey form in which there is one section where the user needs to click on a link, read the page inside the link and then come back to continue the form. Currently, I have a parent HTML page from which I am providing a link to open a child web page in a different window/tab.
How can I obtain the time the user spent on the child window/tab?
listen to the user's click by something like
$('a').on('click', function(){
var d = new Date();
var curr_time = d.getTime();
//save in cookie1
})
and now in the other html page where the user is reading....do the same thing but only on window's unload
$(window).unload(function(){
var d1 = new Date();
var curr_time1 = d1.getTime();
//save in cookie2
})
save this also....
then when s/he comes back I mean on its onfocus you can subtract the values of these 2 cookies and divide by 1000 to get seconds as these time will be in milliseconds.
(cookie1 -cookie2)/1000 seconds //if the cookie thing is used
Does the user leave the page by clicking on the link, or is the second page displayed inside the first one? In the first case, you'll have to use a cookie to store the click time, in the second case, use a variable. Time can be retrieved using new Date().
Record the time of window open
Open the page in a named window
Set a timeinteval function (on original page) to check the location.href of the named window of say 1000 ms
if changed (to a finished/thankyou page) or not existing user must have finished reading
You should set a cookie or an DOM storage value while the page-to-read is open. In that page:
var isFocused = true; // just opened
var secondsLookedupon = 0; // eventually init with a saved value
window.onblur = function(){ isFocused=false; }; // use addEventHandler and co
window.onfocus = function(){ isFocused=true; }; // use addEventHandler and co
window.setInterval(function(){
if (!isFocused) {
secondsLookedupon++;
document.cookie.name = secondsLookedupon; // set a cookie in some way
window.sessionStorage.setItem("name", secondsLookedupon); // or use DOM storage
}
}, 1000);
and from the survey form page you can read that value from the cookie or domstorage whenever you need.

Categories

Resources