Run different js on each user visit - javascript

I want to load javascript functions on a wordpress site based on user visit, if it's the first time, then one function will run, if its second visit another code will run., I found that using cookies and local storage we can set it, but only track user if visited or not., I want to count the user visit, and based on that run the functions.
var first_visit = false;
checkFirstVisit();
function checkFirstVisit(){
if(localStorage.getItem('was_visited')){
return;
}
first_visit = true;
localStorage.setItem('was_visited', 1);
}
console.log(first_visit);
this code is to track the first visit, How do I make it to track the number of visits?

You can use session storage in PHP (https://www.w3schools.com/php/php_sessions.asp) to store in a variable whether this is the user's first visit or not.
Then using an if-else statement, display the required code.
The good thing about PHP session storage is that it can retain the storage even after the user closes the browser.

it is the same thing
set a cookie for visiting
if it is not set so it is the first visit so set it to 1
if it is 1 so second visit so set it to 2
if it is n so it is n + 1 visit so incrment n

Related

Javascript cookie removed after leaving page

I'm attempting to create a cookie the first time a user visits a page on the website and store the pathname as the value of the cookie for that page for records.
I'm attempting on doing this by creating a function at the page load called GenerateCookie.
This function then checks to see if the cookie reportingpage exists or not and if it does not exist create the cookie. I would like the value to remain the same until the session is over. I am attempting to record the first page visited. So for example, if a user visits /testing-page/ I would like the cookie value to remain /testing-page/ even if they back out of the page and visit other pages, since that was the first page visited.
Currently, the cookie is created as expected with the pathname value as expected, but any time I back out of the page and visit a new page the cookie is then removed and set with the other pages pathname value. I've attempted to fix this issue by including the path= attribute when setting the cookie, but this has no effect.
How can I create a cookie and keep that same value for the entire session until the tab/browser is closed?
Here is a code snippet of my code:
GenerateCookie();
function GenerateCookie() {
// if cookie does not exist, create cookie reporting page
if (document.cookie.indexOf('reportingpage=') == -1) {
console.log('no cookie')
document.cookie = "reportingpage=https://www.testing.com" + window.location.pathname + "; path=/"
} else {
// if cookie exist, get value
console.log('cookie exist')
const name = "reportingpage"
const match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
console.log(match[1], 'value')
}
}
Storing a hundred cookies on someone's computer is really unethical, especially if it's for tracking their page visits. I'd be super annoyed if I visited a site and suddenly have a gazillion cookies to delete. But perhaps you have good reasons so if you really have to do it then use localStorage instead of cookies.
sessionStorage.setItem('someKey', window.location.pathname)

How to create global constant or variable whose value dont get reset after closing the app in reactjs [duplicate]

I'm trying to make a page on my tumblr that has a button on it, which counts how many times it's been pressed. I've gotten it to work, but a browser close or refresh clears the value, and clicks from different people don't stack. Here's what I have:
<body>
<div class="main">
<h3>Click Counter</h3>
<button id="clickme">Click me: 0</button>
<h5>Filler Text</h5>
</div>
<script>
var button = document.getElementById("clickme"),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
</script>
</body>
This makes the button count up when pressed, but I want it to behave like so:
User #1 clicks twice. Counter reads two.
User #2 visits the page, counter is already at two, user clicks 3 times. Counter is at 5.
User #3 visits, counter is still at 5 for them as well, etc.
As of right now, each user visits the page and the value starts at zero. Help?
Depending on your needs, you could use localStorage.
count = localStorage.getItem('count');
count = parseInt(count); // because localstorage stores everything in strings
// First time the value does not exist...
if(count == null) {
count = 0;
}
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
localStorage.setItem("count", count);
};
This is not a server side solution. It's also less reliable as it can be cleared by the user anytime.
javascript runs on the browser and store all the variable in the browser so the scope of a variable is in the browser. you can use local storage but if all user uses the same browser which is not your need so only way to persist data is to save count (data) into the server and fetch count (data) on a load of the page.
you can use firebase real-time database if you don't have any server.
Getting started with Firebase real-time database for the web
As I have understant form your question you want to retain the user click count, there is 3 scenerio
User visits form Single machine Single browser (rare situation)
in this you can use local storage
User visits form Single machine multiple browser
In this case you have to save it in server side
User visits form multiple machine multiple browser
In this case you have to save it in server side
Both case 2,3 are same , you need to save it in server.
A common way to do this , put you counter in db and an REST end point and call that endpoint on page each page load to take the counter form the server and also after clicking update on the server by similar end point
Suggesting learning: Client side : AJAX (Jquery) , Server side : REST API , DB (MySql,ets)

Chrome extension - Background page and unread items

I'm making my first chrome extension and i'm stuck just before the end.
I'm getting a response from a server in json, outputing the html, cache it in localstorage check if there's cache if not getting again from server and then displaying.
Now. In the background.js I need to check every 30 mins if there're updates in the json file on the server... if any display a Badge, once clicked remove badge till next time. but I don't know what to do. Because if I make a setInterval it hits the server and always display a badge even if there's nothing new. Can you guy help me build the js, please?
<script>
setInterval(function(){
chrome.browserAction.setBadgeText({text:chrome.browserAction.setBadgeText({text: "!!!"});});
}, 1800000);
</script>
I've also tried this way, but nothing happens.
function getUnreadItems(callback) {
$.ajax(..., function(data) {
process(data);
callback(data);
});
}
function updateBadge() {
getUnreadItems(function(data) {
chrome.browserAction.setBadgeText({text:data.unreadItems});
});
}
var pollInterval = 1*60*60; // 60 min
var timerId;
function startRequest() {
updateBadge();
timerId = window.setTimeout(startRequest, pollInterval);
}
function stopRequest() {
window.clearTimeout(timerId);
}
background.js
onload='startRequest()'
It looks like you never reset the unread items to "read" on the server, so every time you will ping the server, it will reply with the same number and will thus display that number again.
So you can do a couple of things:
when you click your button and reset the badge to 0, you can send a request to the server to mark all the items as read. Which request will of course depend on your server and what it accepts. That way, the unread count on the server will always be up to date and your extension can be very "stupid": whatever is returned by the server is the current number of unread items.
if you can't do that, you'll have to save some information locally to your extension and figure out the unread count yourself. What I mean by that is that instead of just requesting the unread count you'll need to get information about the specific items like a unique ID. Then every time you poll the server for the list of items, you add the IDs to a list saved in localStorage for example (or chrome.storage.sync) with a viewed tag set to false if that ID is not known yet. The background script will then go through that list and count the number of items that have a viewed tag set to false and use that as an unread count. Whenever you open the popup, you go through your whole list and set the viewed tag to true for all your items.
I've done something similar for an extension to get your Hulu playlist. I did the first option when I delete a video from your playlist, so that it's removed locally and on the server as well. And I did the second option because I wanted to show a count for new videos, but Hulu doesn't keep track of that. (it knows played and unplayed, but not "you've been notified that this new video is available" which I wanted.
See in particular, this section:
// Testing that it's the first time I'm seeing this show
if (show_ids.indexOf(new_show.id) == -1) {
new_shows_number++;
new_show.seen = "no";
} else {
new_show.seen = "yes";
}
Here show_ids is the list of IDs I've already saved and marked as viewed locally. If new_show.id is not in this list, that means it's an unviewed item.

Counter Box, Visible for all clients

Hello I need a button for my website, that will start a countdown from 60 secounds to 0, then it should display some text (lets drink, cheers) and go back to start button.
All users must be able to see this countdown, so that when a user start the countdown other users can see this.
It should also display a counter, of howmany user have clicked the button, and joining in on the "button"
I have looked into this, but i need to do Ajax / javascript pulling.
Since my programming skill is still on copy/paste/edit level, I do not know howto get started, I can build the timer, but dont know howto do the pulling.
can anyone help me get started.
Regards
René
Well first of all, you need a stateful backend, to store a usercount. So php+any db.
you mentioned socket.io, build on nodejs.
With nodejs this aint this difficult, because its a single threaded runtime, so you can share variable values to different clients.
your nodejs have to listen to 3 urls:
for passing the basing page ( can be done without nodejs, just url to html)
ajax url for passing clicks on a button from client to backend, returns current count
ajax url to pass the current seconds, returns current count and connected users.
everytime the 2. channels gets called, you need to check , if the countdown is alrdy running. if not: start it, else increase clicked counter.
like this:
//nodejs code
var currendSeconds=60;
var connectedClients = 0;
var threadid;
function clientClickedButton(req, res){ // 2. url
if(currendSeconds==60 || ) {
threadid = setInterval(function(){
currendSeconds--;
if(currentSeconds == 0){
clearInterval(threadid);
}
}, 1000); //your counter
}
connectedClients++;
res.send(currendSeconds);
}
your clientside have to listen to click event on the button, send a ajax req to 2.url and display the returned seconds ( from now on our dont need to request the seconds, just set up a count down clientside, without requesting the current seconds. )

JavaScript Rating after refreshpage

I have a java script functions to display rating..
When user click on stars to rate I need to display the Thank you for rating message and when user refresh the page I need to display thank you for rating message instead of Rate this article.
Below is my code: could any one help me out?
<script type="text/javascript">
var sMax; // Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;
// Rollover for image Stars //
function rating(num){
sMax = 0; // Isthe maximum number of stars
for(n=0; n<num.parentNode.childNodes.length; n++){
if(num.parentNode.childNodes[n].nodeName == "A"){
sMax++;
}
}
if(!rated){
s = num.id.replace("_", ''); // Get the selected star
a = 0;
for(i=1; i<=sMax; i++){
if(i<=s){
document.getElementById("_"+i).className = "on";
document.getElementById("rateStatus").innerHTML = num.title;
holder = a+1;
a++;
}else{
document.getElementById("_"+i).className = "";
}
}
}
}
// For when you roll out of the the whole thing //
function off(me){
if(!rated){
if(!preSet){
for(i=1; i<=sMax; i++){
document.getElementById("_"+i).className = "";
document.getElementById("rateStatus").innerHTML = me.parentNode.title;
}
}else{
rating(preSet);
document.getElementById("rateStatus").innerHTML = document.getElementById("ratingSaved").innerHTML;
}
}
}
// When you actually rate something //
function rateIt(me){
if(!rated){
document.getElementById("rateStatus").innerHTML = document.getElementById("ratingSaved").innerHTML + " :: "+me.title;
preSet = me;
rated=1;
sendRate(me);
rating(me);
}
}
// Send the rating information somewhere using Ajax or something like that.
function sendRate(sel){
alert("Your rating was: "+sel.title);
}
</script>
<form id="form1">
<span id="rateStatus">Rate This Article:</span>
<span id="ratingSaved">Thank you for rating.</span>
<div id="rateMe" title="Rate Me...">
<a onclick="rateIt(this)" id="_1" title="ehh..." onmouseover="rating(this)" onmouseout="off(this)"></a>
<a onclick="rateIt(this)" id="_2" title="Not Bad" onmouseover="rating(this)" onmouseout="off(this)"></a>
<a onclick="rateIt(this)" id="_3" title="Pretty Good" onmouseover="rating(this)" onmouseout="off(this)"></a>
</div>
you need to save the cookie as soon as user rate the article and check that cookie value when you load the page again to confirm if the article is already loaded or not.
Or you can also fetch the current ratings of this article from the server if you are refreshing the page anyways
You have a few options here, and what you do is going to depend on your requirements.
The big issue is one of permanence. By that, if I rate something and get the Thank You message should I see that if I look at the same page from my phone browser, or a browser on another computer? Otherwise, is it simply a message that needs to show once and you don't care if I see the "Please rate" option again later?
Based on your question about saving state between page refreshes, it sounds like your needs are more on the side of saving permanence.
Ultimately, the only way to guarantee that the rating state is saved permanently is to tie it into a user account on the backend (server) application. That way, when I view the same page from other browsers, or after a long time, then the server can lookup in the database and see that "Geuis rated this, show the Thank You message".
If you only need to show the Thank You for a short amount of time, you can store a key in a temporary cache like memcache. On each page refresh, a short piece of javascript can make an xhr request to your cache server to check if I've rated the page or not. Eventually the key falls out of the cache, so maybe in an hour or a day when I go back to see the page then I'll be prompted to rate the page. This is a semi-permanent solution, but it does work across any device or browser as long as its tied into an account.
The most fragile, but easiest, solution to implement is purely client-side. Here, your options are to either a) store the rated/not rated value in a cookie, or b) use localStorage. In either situation, it will let store the state. But cookies and localStorage are not transferred between devices or browsers. localStorage won't expire, but eventually cookies will. Also, the user can eventually decide to clear out their cookies and localStorage caches and would set the state back to "Rate me".
I'm not providing any code samples because, as I hope you can see, the answer really lies first in exactly what you're trying to accomplish along the spectrum of permanence.
And just to say it, there's really no such thing as anonymous permanence. I.e. you can't have a user to be anonymous to your site yet save their voting state permanently in a way that transfers between browsers. You have to have something akin to a server-side account to do that.

Categories