Executing a jquery function or bypass jquery countdown - javascript

There is a countdown in a page. And i want to bypass or speed it up.
Is there a possibility to run add ticket function from chrome's console or something?Or can I change the xtime variable to something like 2-3 seconds.Or directly call the add ticket function?
jQuery(document).ready(function($){
var xTime=120;
$("#ticketTimer").html(xTime);
var myVar = setInterval(
function(){
if(typeof checkAdBlock === 'undefined')
{
document.getElementById("compt").innerHTML = "<b>you use an AdBlocker!</b> To win a ticket, <b>Desactivate AdBlock and reload the page.</b>";
return false;
}
else if(xTime>0)
{
xTime--;
$("#ticketTimer").html(xTime);
}
else
{
addTicket();
clearInterval(myVar);
}
},
1000);
});

Related

Measure time spent by a user during a website visit

I'm trying to build a website locally using PHP and Javascript and MAMP.
What I'm looking for is to put a timer on every page of the website and that timer counts the time spent by the user in the whole website. Even if the user switches between pages the timer will still continue. The solution I've found only shows the time spent on each page and when I reload the same page again the timer restart from zero.
Here's the Javascript for the timer I did:
window.onload=function(){
time=0;
}
window.onbeforeunload=function(){
timeSite = new Date()-time;
window.localStorage['timeSite']=timeSite;
}
I've search everywhere for the solution but with no luck, if anyone knows how to do this please let me know.
Here's a working example. It will stop counting when the user closes the window/tab.
var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();
function getTimeSpentOnSite(){
timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
return timeSpentOnSite;
}
function startCounting(){
timerStart = Date.now();
timer = setInterval(function(){
timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
console.log(parseInt(timeSpentOnSite/1000));
},1000);
}
startCounting();
Add the code below if you want to stop the timer when the window/tab is inactive:
var stopCountingWhenWindowIsInactive = true;
if( stopCountingWhenWindowIsInactive ){
if( typeof document.hidden !== "undefined" ){
var hidden = "hidden",
visibilityChange = "visibilitychange",
visibilityState = "visibilityState";
}else if ( typeof document.msHidden !== "undefined" ){
var hidden = "msHidden",
visibilityChange = "msvisibilitychange",
visibilityState = "msVisibilityState";
}
var documentIsHidden = document[hidden];
document.addEventListener(visibilityChange, function() {
if(documentIsHidden != document[hidden]) {
if( document[hidden] ){
// Window is inactive
clearInterval(timer);
}else{
// Window is active
startCounting();
}
documentIsHidden = document[hidden];
}
});
}
JSFiddle
Using localStorage may not be the best choice for what you need. But sessionStorage, and localStorage is most suitable. Have in mind that sessionStorage when opening a new tab resolves to a new session, so using localStorage has to do with the fact that if only sessionStorage was used and a user opened a new tab in parallel and visit your website would resolve to a new separate session for that browser tab and would count timeOnSite from start for it. In the following example it is tried for this to be avoid and count the exact timeOnSite.
The sessionStorage property allows you to access a session Storage
object for the current origin. sessionStorage is similar to
Window.localStorage, the only difference is while data stored in
localStorage has no expiration set, data stored in sessionStorage gets
cleared when the page session ends. A page session lasts for as long
as the browser is open and survives over page reloads and restores.
Opening a page in a new tab or window will cause a new session to be
initiated, which differs from how session cookies work.
function myTimer() {
if(!sessionStorage.getItem('firstVisitTime')) {
var myDate = Date.now();
if(!localStorage.getItem('timeOnSite')) {
sessionStorage.setItem('firstVisitTime',myDate);
} else {
if(localStorage.getItem('tabsCount') && parseInt(localStorage.getItem('tabsCount'))>1){
sessionStorage.setItem('firstVisitTime',myDate-parseInt(localStorage.getItem('timeOnSite')));
} else {
sessionStorage.setItem('firstVisitTime',myDate);
}
}
}
var myInterval = setInterval(function(){
var time = Date.now()-parseInt(sessionStorage.getItem('firstVisitTime'));
localStorage.setItem('timeOnSite',time);
document.getElementById("output").innerHTML = (time/1000)+' seconds have passed since first visit';
}, 1000);
return myInterval;
}
window.onbeforeunload=function() {
console.log('Document onbeforeunload state.');
clearInterval(timer);
};
window.onunload=function() {
var time = Date.now();
localStorage.setItem('timeLeftSite',time);
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))-1);
console.log('Document onunload state.');
};
if (document.readyState == "complete") {
if(localStorage.getItem("tabsCount")){
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))+1);
var timer = myTimer();
} else {
localStorage.setItem("tabsCount",1);
}
console.log("Document complete state.");
}
Working fiddle
If you want a server-side solution then set a $_SESSION['timeOnSite'] variable and update accordingly on each page navigation.

Javascript setTimeout fires as many times in as page loaded by ajax

I am executing setTimeout function in a page which loads via ajax call. but if i click the link to load the page again, i afraid the last setTimeout call still continues and the number of intervals of the calls set by setTimeout executes multiple times.
tried this is the remote page:
var RefreshInterval = null;
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
RefreshInterval = null;
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
declare var RefreshInterval = null; outside of page loaded by ajax and use this code on the page:
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
if i don't want to declare it in parent page, here is the solution i found:
//Clear previously loaded calls if exists
try{ clearTimeout(wifiRadarRefreshInterval); }catch(e){}
var wifiRadarRefreshInterval = null;
function somefunction(){
....
setNextRefresh();
}
function setNextRefresh() {
try{
clearTimeout(wifiRadarRefreshInterval);
wifiRadarRefreshInterval = null;
wifiRadarRefreshInterval = setTimeout('somefunction();', 20*1000);
}
catch(e){
console.log(e.message + e.stack);
}
}
Do not use this
var RefreshInterval = null;
clearTimeout(RefreshInterval);
You are actually assigning a null and then trying to clear it. Which will not work, The timeout must be cleared by using the clearTimeout and by passing the variable which was assigned to the setTimeout. Here you will end up passing a null so the timer is never cleared.
Here is a small sample which will demonstrate a fix to your problem JS Fiddle
So insted of setting the variable to null and then trying to clear it, Just check if the variable is not defined and if it is defined clear it, else move on. Use the code below, Also you must remove the top two lines as mentioned
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
Click on the button say like 4 times, The output should be printed only once. That is if the ajax call is made 4 times the set time out must execute only once. Check below snippet for demo
var clickCount= 0; // just to maintain the ajax calls count
function NewPageSimilator(clicksTillNow) { // this acts as a new page. Let load this entire thing on ajaX call
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
function setNextRefresh() {
window.RefreshInterval = setTimeout(printTime, 3000); //20*1000
}
function printTime() {// dumy function to print time
document.getElementById("output").innerHTML += "I was created at click number " + clicksTillNow + '<br/>';
}
setNextRefresh();
}
document.getElementById("ajaxCall").addEventListener("click", function() { // this will act as a ajax call by loading the scripts again
clickCount++;
NewPageSimilator(clickCount);
});
document.getElementById("clear").addEventListener("click", function() { //reset demo
clickCount = 0;
document.getElementById("output").innerHTML = "";
});
<p id="output">
</p>
<button id="ajaxCall">
AJAX CALL
</button>
<button id="clear">
Clear
</button>

anonymous window.setTimeout function reloading page

Using Tampermonkey to change the behavior of a website. Have some problems with a website with the following code:
<script language="JavaScript">
if (typeof jQuery != 'undefined') {
jQuery(window).load(function() {
window.setTimeout(function() {
window.location.replace(window.location.href);
}, 180E3);
});
}
</script>
How does one remove/prevent it reloading the page?
Without messing that much with jQuery, if your script runs before that piece of code you can do the following:
jQuery.fn.load = function() {
console.log("Tried to reload the page!")
}
// Then the following, outputs 'Tried to reload the page!' and does nothing else
jQuery(window).load(function() {
// code
})
If you still need the load function afterwards you could do the following:
var oldLoad = jQuery.fn.load
var undesiredCallback = "function() {
window.setTimeout(function() {
window.location.replace(window.location.href);
}, 180E3);
}"
jQuery.fn.load = function(callback) {
if(callback.toString() !== undesiredCallback) {
oldLoad(callback);
}
}
But it's browser dependent and very unreliable
Another way would be adding a onbeforeunload event, but that would pop a prompt on your tab:
window.onbeforeunload = function() {
return "Stay here please";
}
You can also override setTimeout functionallity.
var oldSetTimeout = window.setTimeout;
window.setTimeout = function(func,interval){
if(typeof func === "function" && func.toString().indexOf('window.location.replace(window.location.href)') > -1){
/*do nothing*/
}else{
oldSetTimeout(func,interval)
}
}

How do I make a JS function that works onolad not work on the first page load.?

I have a html page which has a function that would work once the page loads.
<body onload="startNow()">
This startNow function has a part that refreshes the page if a certain condition is not met and thus causes the function to run again.
function startNow() {
var warning_check = document.getElementsByClassName("warning");
if (warning_check.length == 0) {
checkAll(); //another function call
} else {
window.location.reload();
}
}
Is there a way i can make this startNow function not run the first time this page loads?
Easily done with a localStorage
function startNow(){
var warning_check = document.getElementsByClassName("warning");
if(warning_check.length == 0) {
checkAll(); //another function call
} else {
if (!!localStorage.returningUser){
window.location.reload();
}
}
localStorage.returningUser = 'true';
}
EDIT
the above function still runs for first time users but it won't reload if the code reaches to the reload point. If you want to code to stop running at all then
function startNow(){
if (!localStorage.returningUser){
localStorage.returningUser = 'true';
return false;
}
var warning_check = document.getElementsByClassName("warning");
if(warning_check.length == 0) {
checkAll(); //another function call
} else {
window.location.reload();
}
}

Problem with Flash and JavaScript Communication

I have an AS2 Flash SWF that is calling another AS2 Flash File using loadMovieNum("flash.swf",2) and a JavaScript file that calls a function on page using a timer. This is what I get in Firefox with Flash 10 (IE8 gives no error message):
uncaught exception: Error calling
method on NPObject! [plugin exception:
Error in Actionscript. Use a try/catch
block to find error.].
What is going wrong? I can't see a problem. It is suppose to clear the contents of the embedded swf and use a Flash alert dialog to confirm Yes or No.
Flash:
import flash.external.ExternalInterface;
import mx.controls.Alert;
System.security.allowDomain("mydomain.com");
function getTimeOut()
{
// Show alert dialog box
_level2._visible = false;
Alert.show("You are about to Timeout. Do you want to continue using Courseware?", "Timeout", Alert.YES |
Alert.NO, this, myClickHandler);
}
ExternalInterface.addCallback("timeOut", this, getTimeOut);
this.onMouseDown = function(){
//if not on login
getURL("javascript:startTimer();");
};
var myClickHandler:Function = function (evt_obj:Object) {
switch (evt_obj.detail) {
case Alert.YES :
getURL("javascript:buttonEvent('yes');");
break;
case Alert.NO :
getURL("javascript:buttonEvent('no');");
break;
}
_level2._visible = true;
};
//load courseware
loadMovieNum("embedded.swf",2);
JavaScript:
<script type="text/javascript">
// <![CDATA[
var so = new SWFObject("main.swf", "mainMovie", "100%", "100%", "9", "#083770");
so.addParam("scale", "noscale");
so.addParam("quality", "high");
so.addParam("allowScriptAccess","always");
so.write("flashcontent");
var timerMin = '<?php echo($timerMinutes); ?>';
var timer;
var timer2;
function startTimer()
{
var timerMill = 0;
clearTimeout(timer);
timerMill = getMillis();
timer = setTimeout ( 'stopTimer()', timerMill );
}
function stopTimer()
{
clearTimeout(timer);
timer2 = setTimeout( 'redirectPage()', 60000);
//call flash function
getFlashMovie("mainMovie").timeOut();
}
function buttonEvent(evt)
{
if(evt == 'yes')
{
clearTimeout(timer2);
startTimer();
}
else
{
clearTimeout(timer2);
redirectPage();
}
}
function getMillis()
{
var milliseconds = 300000;
if(timerMin == parseInt(timerMin))
{
//convert to milliseconds
//60000 milliseconds in 1 minute
milliseconds = (parseInt(timerMin)) * 60000;
}
return milliseconds;
}
function getFlashMovie(movieName)
{
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
//return document.getElementById(movieName);
}
function redirectPage()
{
top.location = "timeout.php?t=<?php echo($timerMinutes); ?>";
}
// ]]>
</script>
Same old story - NPObject.
I took Flash out of the picture and was able to achieve the same thing using CSS and JavaScript. The fix for this is to create a policy file for Flash but for something so simple I just went another direction so not to debug.

Categories

Resources