Count how many times user has loaded a page on my site? - javascript

I'm wondering if I can count the times user loads pages on my site, with JavaScript. Probably like this?
var pageloads = 1;
$(document).ready(function(){
var pageloads =++
});
But where would I store it? In a cookie?

If older browsers like IE7 and below are'nt an issue, you can use local storage:
$(function(){
var loaded = parseInt(localStorage.getItem('loaded'), 10),
loaded_numb = loaded?loaded+1:1;
localStorage.setItem('loaded', loaded_numb);
$('body').append('<p>This page was loaded by you '+loaded_numb+' times !');
});
FIDDLE

Easier to just do it with cookies (especially since there's no reason to totally block out IE7 and lower)
var numLoads = parseInt(getCookie('pageLoads'), 10);
if (isNaN(numLoads) || numLoads <= 0) { setCookie('pageLoads', 1); }
else { setCookie('pageLoads', numLoads + 1); }
console.log(getCookie('pageLoads'));
getCookie/setCookie simple get/set functions (can be found in the jsFiddle)
jsFiddle Demo

You could store it in a database. If you are looking for monitoring the traffic on your web page you should look at Google Analytics http://www.google.com/analytics/.
They show you how many people visited your site, whether they are new or returning, the path they took through your site, bounce rate etc. Best part is it's free.

Why would you want to do this with Javascript? Whatever server you're using should have access logs that store all requests, IPs that make the requests, and a lot more. There are even free log file analyzers like awstats and Google Analytics. You should do this on the server side, not the client side.
If you really want to store it with JavaScript, then your only options are a cookie and LocalStorage -- both of those are quite transient.

It's not possible - edit: to track an actual user.
You can only ever track a particular instance of a browser using cookies.
There is no such thing as tracking a "user" using javascript alone. You can reliably count things like user logins though.

Related

Can you prevent users editing the chrome.storage.local values in a Chrome extension? What is the best way to store persistent values for an extension?

So I'm working on a Chrome extension for someone else. I don't want to give away specific details about the project, so for I'll use an equivalent example: let's assume it's an extension to run on an image/forum board. Imagine I have variables such as userPoints, isBanned etc. The later being fairly self-explanatory, while the former corresponding to points the user acquires as they perform certain actions, hence unlocking additional features etc
Let's imagine I have code like:
if(accountType !== "banned"){
if(userPoints > 10000) accountType = "gold";
else if(userPoints > 5000) accountType = "silver";
else if(userPoints > 2500) accountType = "bronze";
else if(userPoints <= 0) accountType = "banned";
else accountType = "standard";
}else{
alert("Sorry, you're banned");
stopExtension();
}
Obviously though, it becomes trivial for someone with the knowledge to just browse to the extensions background page and paste chrome.storage.local.set({'userPoints': 99999999}) in the console, hence giving them full access to all the site. And, with the Internet, someone can of course share this 'hack' on Twitter/YouTube/forums or whatever, then suddenly, since all they'd need to do is copy and paste a simple one-liner, you can have 1000s of people, even with no programming experience, all using a compromised version of your extension.
And I realise I could use a database on an external site, but realistically, it would be possible that I would be wanting to get/update these variables such as userPoints 200+ times per hour, if the user was browsing the extentions target site the entire time. So the main issues I have with using an external db are:
efficiency: realistically, I don't want every user to be querying the
db 200+ times per hour
ease-of-getting-started: I want the user to just download the
extension and go. I certainly don't want them to have to sign up. I
realise I could create a non-expiring cookie with for the user's ID
which would be used to access their data in the db, but I don't want
to do that, since users can e.g. clear all cookies etc
by default, I want all features to be disabled (i.e. effectively
being considered like a 'banned' user) - if, for some reason, the
connection with the db on my site fails, then the user wouldn't be
able to use the extension, which I wouldn't want (and just speaking
from experience of my parents being with Internet providers whose
connection could drop 10 times per hour, for some people, failed
connections could be a real issue) - in contrast, accessing data from
the local storage will have like a 99.999% success rate I'd assume,
so, for non-critical extensions like what I'm creating, that's more
than good enough
Still, at least from what I've found searching, I've not found any Chrome storage method that doesn't also allow the user to edit the values too. I would have thought there would be a storage method (or at least option with chrome.storage.local.set(...) to specify that the value could only be accessed from within the extension's context pages, but I've not found that option, at least.
Currently I'm thinking of encrypting the value to increment by, then obfuscating the code using a tool like obfuscator.io. With that, I can make a simple, like 30 character js file such as this
userPoints = userPoints + 1000;
become about 80,000...still, among all the junk, if you have the patience to scroll through the nonsense, it's still possible to find what you're looking for:
...[loads of code](_0x241f5c);}}}});_0x5eacdc(),***u=u+parseInt(decrypt('\u2300\u6340'))***;function _0x34ff36(_0x17398d)[loads more code]...
[note that, since it's an extension and the js files will be stored on the user's pc, things like file size/loading times of getting the js files from a server are irrelevant]
Hence meaning a user wouldn't be able to do something like chrome.storage.local.set({'userPoints': 99999999}), they'd instead have to set it to the encrypted version of a number - say, something like chrome.storage.local.set({'userPoints': "✀ເ찀삌ሀ"}) - this is better, but obviously, by no means secure.
So anyway, back to the original question: is there a way to store persistent values for a Chrome extension without the user being able to edit them?
Thanks

How would you count a user's accumulated visits to your site client-side?

I want to keep track how many times a user has visited my site/domain.
For example, say I wanted to display a message to the user after their 10th visit to the site.
Each pageload should not count as a new visit. A visit in this case is more like a session. Browse all you want in one sitting, that's one visit. Close your browser and come back, that's a second visit.
I thought it would be good to do this by utilizing localStorage and sessionStorage. I put a value in sessionStorage to show that a user is on a "currentVisit" so that I don't count them on every pageload. This gets wiped out when their session ends. Then I have a value in localStorage that tallies up the total amount of visits by the user, "visitCount". If a user loads a page and doesn't have a "currentVisit" value, give them one and increment "visitCount".
I'm worried about using local/session storage though because I've read it is not consistently supported across all browsers, specifically mobile ones.
I'm considering using indexedDB in place of localStorage and session cookies in place of sessionStorage in my approach.
What do you think is the right tool for the job?
While using a polyfill as I mentioned above, you can define a simple function like this to keep track of a user's visits assuming they're not in incognito or private browsing mode, and they don't clear or disable cookies for your site:
function visitCount() {
var visits = Number(localStorage.getItem('visitCount'));
var current = Boolean(sessionStorage.getItem('session'));
if (!current) {
visits++;
}
localStorage.setItem('visitCount', visits);
sessionStorage.setItem('session', true);
return visits;
}
If you're concerned with any of the caveats of trusting client-side storage (for example, security) then you should use a server-side solution and a browser fingerprinting script to keep track of anonymous visits in a more robust manner.

Storing a variable to web server

I have a page on my site where you can play a game. When you die in the game, a function called "playerIsDead();" is called, then the game closes (The game screens are prompt();s and confirm();s shown one after another, so by "the game closes", I mean the page stops showing popup messages.). The playerIsDead(); Function:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
};
I want to make the function increase a variable, totalDeathCount, by one each time, like this:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
totalDeathCount++;
};
So, my question is, how can I store totalDeathCount to the server, so I can display it on the page? I don't want it to show how many deaths have happened locally, I want it to show how many worldwide deaths have occurred.
Any help would be much appreciated!
You could use a MySQL database and store the value using PHP. Or you could simply use javascript's localStorage to store them locally on the device.
var newDeathCount = localStorage.getItem('totalDeathCount') + 1;
localStorage.setItem('totalDeathCount',newDeathCount);
Then you basically stored how many times they have died. Not in a web server but this is an alternate solution.
1) Decide how and create something to persist the information. E.g. write it to a file, store it in a database, etc.
2) Write a simple php script to store the data. (or implement it as part of your existing php backend if available)
3) Make an ajax post request to send the data to the script.
For implementation details use google and your imagination. ;)

What is the best way to implement idle time out for web application (auto log off)

I want to implement an idle time-out for the web application that we are building. I had earlier achieved this using AsynchronousSessionAuditor from codeplex, which essentially looks for the formsauthentication and session cookie timeout by constant polling.
But it has a draw back of not respecting the client side events, it will look for only last postback to decide when to log off.
The jquery plug jquery-idle-timeout-plugin from erichynds solves this issue of client side events but suffers from another drawback that is not able to recognise user is active on some other tab.
Is there anyone already fixed the TABBED browsing issue with jquery-idle-timeout-plugin already? Or is there any better approach of application time out for web applications (by the way this web app is build using asp.net f/w)
If I understand your question right, it is not possible, since there are no events triggered in javascript for activity outside of the current window/tab.
Unless you have a addon to go along with your website for each browser, which could monitor all activity in the browser, but that is not really a practical approach.
Well, you'd have to code it by hand, which is not really hard. You can use the onfocus and onblur functions to do something like this:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (!window.isActive) { /* Check for idle time */}
}
If you make a little search you can find that varaieties of this question have already been asked and answered, you can probably find a solution you can implement with one of the plugins you mentioned.
Try:
Run setTimeout only when tab is active
or
How to tell if browser/tab is active
EDIT--> ADDED:
Or I'd try a different approach. You could create a cookie with some hash and save that hash in your DB with a timestamp that updates whenever the window is active (you could check every 5 seconds or something, it's not an intensive request)
Then, do another check before(but in the same request) to see how much time has passed since the last timestamp and log them out if necessary.
it won't log them out isntantly when time has passed, but it will when they try to access the site either by opening it again or by focusing on the tab/window.

How to save recent searches with javascript?

When user perform a search, these search settings should be saved for future use.
User should fill some form fields and then perform a search. When he perform a new search, the old one should be able, etc, etc.
Im using javascript, jQuery.
How could I do this?
I mean save it in localmachine, not in database.
Use HTML5 Local Storage to store and read saved searches.:
// Write a local item..
localStorage.setItem("myKey", "myValue");
// Read a local item..
var theItemValue = localStorage.getItem("myKey");
// Check for changes in the local item and log them..
window.addEventListener('storage', function(event) {
console.log('The value for ' + event.key + ' was changed from' + event.oldValue + ' to ' + event.newValue);
}, false);
// Check for HTML5 Storage..
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
You might try this plugin https://sites.google.com/site/daveschindler/jquery-html5-storage-plugin
your goal is to just save the searches, once they enter them before you do the action, so onSubmit of the form, save it to local storage using the plug in, and then perform the search.
You also need to load from storage each time the user visits the page, to grab the last few searches.
You can use cookies or Web Storage. Cookies are supported by more browsers, but Web Storage is easier to use. If you use cookies, I recommend this jQuery plugin https://github.com/carhartl/jquery-cookie
To save a setting $.cookie('key', 'value');
To read a setting $.cookie('key');
Using Web Storage supported by latest versions of all major browsers:
localStorage.setItem(key, value);
localStorage.getItem(key, value);
You can use Google to find more details about the API
TL;DR I've written a library to handle this + it's edge cases, see https://github.com/JonasBa/recent-searches#readme for usage.
While all examples are technically ok, they do not cover any edge cases of storing recent searches such as implementing expiration, ranking or limits for LocalStorage space.
Examples
Expiration:
Consider that someone searches for a query iPhone, but has looked for a query repairing iPhone 1 month ago, that repairing iPhone query is likely obsolete.
Ranking of recent searches
Same goes for ranking when doing prefix search, if a user has made a query "apple television" 3h ago and a query "television cables" 8h ago, and they now search for "television", you want to probably implement a ranking system for the two.
Safely handling storage
Just writing to LocalStorage will result in a massive JSON that you'll need to parse every time, thus gradually slowing down your application until you hit the limit and loose this functionality.
Exactly because of that problem, I've built a recent-searches library which helps you tackle all that. You can use it via npm and find it here. It will help you with all of the above issues and allow you to build recent-searches really quickly!

Categories

Resources