localStorage gets empty when i refresh the page.
What i have done in code is :-
1)I have store the authToken in localStorage
2)I have store isReloaded value in sessionStorage to check if page is new open or is postback
If browser tab is first time open then increment the browser tab count value in tabCount localStorage and if browser is reloaded then no value should be added in tabCount and if i close all the tabs without logout of page all localStorage should get clear.
Purpose of code to achieve : -
1) page should clear the localStorage values if all the browser tabs are closed without logout of the page.
2) instance of page should open in multiple tabs
$(window).load(function () {
if(!sessionStorage.getItem('isReloaded'))
{
//first time call
if(localStorage.getItem('tabCount') == null || localStorage.getItem('tabCount') == undefined)
{
var tabCount = 1;
localStorage.setItem('tabCount',tabCount.toString());
}
else
{
var tabCount = parseInt(localStorage.getItem('tabCount'));
tabCount += 1;
localStorage.setItem('tabCount',tabCount.toString());
}
}
else
{
// postback code here
console.log('in postback...')
}
sessionStorage.setItem('isReloaded',true);
});
$(window).unload(function(){
var tabCount = parseInt(localStorage.getItem('tabCount'));
if(tabCount > 0)
{
tabCount -= 1;
if(tabCount == 0)
{
//RemoveLocalStorage('tabCount,authToken,userId,userName,userFullName,caseNo,consumerName, consumerFirstName, consumerLastName, consumerList, userData,timeStamp');
localStorage.setItem('tabCount',tabCount.toString());
localStorage.clear();
}
else
{
localStorage.setItem('tabCount',tabCount.toString());
}
}
});
Related
I want to disconnect all my users when the tab is closing or the browser is getting closed, so far so good. But when I refresh the page, all my users get disconnected too, this should not happen on refresh. Is it possible to avoid to execute this event on refresh? I saw some users doing with localStorage, but I still didn't get the point.
componentDidMount() {
this.beforeUnloadListener();
}
beforeUnloadListener = () => {
window.addEventListener("beforeunload", (ev) => {
ev.preventDefault();
// code to logout user
});
};
The way beforeunload works, you can not differentiate weather it's a page refresh or a browser close. beforeunload it is a quite confusing event avoid using this.
Hence for cases where you are dealing with the session you should use session storage. The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
Have done this on react application and its work for me on index.html file write this in script tag.
<script type="text/javascript">
window.addEventListener("beforeunload", (event) => {
window.localStorage.isMySessionActive = "true";
});
window.onunload = function (e) {
const newTabCount = localStorage.getItem("tabsOpen");
if (newTabCount !== null) {
localStorage.setItem("tabsOpen", newTabCount - 1);
}
};
</script>
Then go on main file and write this code.
useEffect(() => {
// define increment counter part
const tabsOpen = localStorage.getItem("tabsOpen");
if (tabsOpen == null) {
localStorage.setItem("tabsOpen", 1);
} else {
localStorage.setItem("tabsOpen", parseInt(tabsOpen) + parseInt(1));
}
// define decrement counter part
window.onunload = function (e) {
const newTabCount = localStorage.getItem("tabsOpen");
if (newTabCount !== null) {
localStorage.setItem("tabsOpen", newTabCount - 1);
}
};
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
window.localStorage.isMySessionActive = "false";
} else {
const newTabCount2 = localStorage.getItem("tabsOpen");
let value = localStorage.getItem("isMySessionActive");
if (value == "true") {
if (newTabCount2 - 1 == 0) {
localStorage.clear();
window.localStorage.isMySessionActive = "false";
} else {
window.localStorage.isMySessionActive = "false";
}
}
}
}, []);
I'm creating a popup that will show when the user scrolls. However when the user clicks on the close button and refreshes the page and scrolls, I need to make a popup to show up after 10 minutes.
var popUp= document.getElementById("popup");
var closePopUp= document.getElementsByClassName('popup-close');
var halfScreen= document.body.offsetHeight/2;
var showOnce = true;
//show when scroll
window.onscroll = function(ev) {
if ((window.innerHeight+window.scrollY) >= halfScreen && showOnce) {
if(popUp.className === "hide"){
popUp.className = "";
}
showOnce = false;
}
};
//close button
for(var i = 0; i<closePopUp.length; i++){
closePopUp[i].addEventListener('click', function(event) {
if(popUp.className === ""){
popUp.className = "hide";
}
});
}
First you should detect whether the user has refreshed the page.You can achieve this using navigator object.Refer this question for implementation.
Secondly, once the user refreshes the page all the variables gets destroyed and initialized again.Hence you must use cookies or server side sessions to store whether user has already closed it once.But I always recommend you to setup sessions since cookies can be disabled by users.
To sum it up,setup an ajax request once the user refreshes the page,and if already he has closed the popup once, start a timeout for 10 minutes.
Adding a sample prototype for this :
var refreshed = false;
if (performance.navigation.type == 1) {
console.info( "This page is reloaded" );
refreshed = true;
} else {
console.info( "This page is not reloaded");
refreshed = false;
}
if(refreshed) {
//implement this ajax function yourself.
ajax('path/to/yourserver','method','data',function(response) {
if(response == "showed") {
var time = 10 * 60 * 1000;//10 minutes.
setTimeout(function() {
//show your popup.
},time);
}else {
//immediately show once scrolled.
}
});
}
You should use cookie for this and set cookie expiration time for 10 minutes take a look at this cookie plugin hope it helps
Set a cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
Get a cookie
alert( $.cookie("example") );
Delete the cookie
$.removeCookie("example");
Or there is an example which is given in this answer take a look at this also
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.
I have a JS that plays a notification sound on the arrival of any new notifications. It works completely fine when a new notification comes, it should play the sound and it does play.
The notification I am talking about is only an integer which is returned from a query through an ajax call. I set this integer into my <asp:label.../> through the script.
The problem is : I have written the script on MasterPage. So every time I open a new page, or a refresh the same one the <asp:Label.../> gets cleared which I set from my script using .html(value) causing the script to run the sound again as every time the page refreshes or another page is loaded.
The problem may be is , that the value is not persistent ?
I want that the value should be set to the html of the label and also its value should be persistent on all the pages . What should I do for this persistence ?
My Script is :
myFunction();
function myFunction() {
$.get("AjaxServicesNoty.aspx", function (data) {
var recievedCount = parseInt(data);
alert(recievedCount);
var existingCount = $(".lblEventCount").text();
if (existingCount == "") {
existingCount = 0;
alert(existingCount);
} else {
existingCount = parseInt($(".lblEventCount").text());
alert(existingCount);
}
// if (existingCount == "" && recievedCount != 0) {
// $(".lblEventCount").html(recievedCount);
// $(".lblAcceptedCount").html(recievedCount);
// var sound = new Audio("Sound/notificationSound.wav");
// sound.play();
// }
if ((parseInt(recievedCount) > parseInt(existingCount)) && existingCount == 0) {
$(".lblEventCount").html(recievedCount);
$(".lblAcceptedCount").html(recievedCount);
var sound = new Audio("Sound/notificationSound.wav");
sound.play();
} else {
$(".lblEventCount").html(existingCount);
$(".lblAcceptedCount").html(existingCount);
}
});
}
setInterval(myFunction, 5000);
use DIV ID instead of selecting via class
$("#divID").html(existingCount);
I have an application that has a "parent" window. In the parent window there are menu items, like the following (using PHP here):
// sample link
echo "<li><a href=\"#\" onclick=openurl('covershift.php');>Shift Coverage</a></\
li>";
// logout link
echo "<li><a href=\"#\" onclick=openurl('logout');>Logout</a></li>";
Each link opens the appropriate page in a different "child" window. When the parent closes all of the child windows must close. I have implemented this functionality with Javascript, here is the function:
var childWindow = new Array();
var windowCount = 0;
function openurl(url)
{
if(url != 'logout') {
childWindow[windowCount]=window.open(url,'_blank','height=600,width=800,scr\
ollbars=1');
windowCount++;
if (window.focus) {
childWindow.focus();
}
} else {
var iCount;
for (iCount=0; iCount < windowCount; iCount++) {
if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) {
childWindow[iCount].close();
}
}
window.location='logout.php';
}
}
Here is my problem, when a user reloads the parent window and then clicks logout, the child windows remain open. This makes sense as the childWindow array is lost when the parent reloads.
How can I make the childWindow array persistent through a reload?
Thanks!
I don't think you can make a JavaScript object persist through a window load. Instead, could you make an unload event handler that closes your pages?
window.onunload = myCloseFunction;
function myCloseFunction()
{
// Just copying your code...
var iCount;
for (iCount=0; iCount < windowCount; iCount++) {
if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) {
childWindow[iCount].close();
}
}
}
Another option might be to have the child windows poll for the existence of the parent.
In the child window:
// Checks every 1 second for valid window.opener
var parentChecker = setInterval(function(){
if(!opener){
// Is this good practice? I don't know!
clearInterval(parentChecker);
window.close();
}
}, 1000);
You can save that array in the LocalStorage or in a cookie