store temporary data on indexedDB for current session - javascript

Is there a way to store temporary data on indexedDB the same way as sessionStorage:no available to other sessions (tabs) of the same domain and expire when the session is closed (affect some items on an storeObject or the whole storeObject)?
I can create a storeObject with a random name and add unload event listener to delete this storeObject when the user is exiting the page. but the problem here is that the storeObject will be deleted even if the user is just changing from a page to an other on the same domain or refreshing the page,... (same session).
I know there is some implementations of sessionStorage-like storages based on document.cookie API which is not a perfect solution for my case.

I'm not sure if there is a way to do what you want to do. I believe that indexDB is persistent until deleted. You could delete based on a timestamp, this can only happen after the user returns, or logoff button.
This may help you may be able to user localStorage if your not storing to much data:
http://www.sitepoint.com/an-overview-of-the-web-storage-api/
If you are worried about concurrent data overrides you can implement locks:
http://balpha.de/2012/03/javascript-concurrency-and-locking-the-html5-localstorage/#comments

Related

How to detect if sessionStorage is going to die?

Obviously, we are able to store user data in sessionStorage.
Also, we can watch changes to sessionStorage:
window.addEventListener('storage', function(e) {
But what if we are also, for example, sending some info to our db and we need to do some important actions when user is done with our website, and he is closing all opened browser tabs of our website, and sessionStorage is about to die?
There is the event onbeforeunload, but it doesn't fit our issue, because many tabs of the same website can be open at once, and we cant be sure it is the last one.
So question is - can we detect when sessionStorage is about to die?
The goal is to detect when the last tab accessing a specific site is closing.
Assuming each tab is associated with a unique session ID, the following method should work:
Upon page load:
obtain session ID
retrieve array of active session IDs from localStorage
if session ID is not present in array, add it
store array to localStorage
Upon page unload:
retrieve array of active session IDs from localStorage
find and remove current session ID from array
update array to localStorage
if array is empty, perform your "last tab closing" action
What About Browser Crashes?
This scheme doesn't handle when a browser crashes. In that case, the page unload will never be detected, and localStorage will never have its array of active session IDs cleared.
One way to accommodate a crash is to set a timestamp with each session ID stored, then remove old session IDs.
let sessionArr = [
{ sessionId, timestamp },
...
]

Reset variable on every new session using localstorage

I am trying to run something only once at the beginning of the user session spanning multiple pages.
I was trying to use sessionStorage to test if a variable exists which defaults to false initially, but it is not persisting in some browsers due to a JavaScript redirect in the script:
window.location.href
Is there a way to mimic this with localstorage which persists more reliably?
i.e. to do something only once at the beginning of each new user session. The session may have multiple pages so a single javascript variable won't work.
update: as requested in the comments, the basic logic is:
new session opened.
redirect once to last page viewed.
set redirected to true. to prevent this from happening again.
I realize there are other ways to do this besides localstorage. would be nice to use that though if possible.
you could check if the item already exists or if it is null with:
localStorage.getItem("itemname");
If it doesnt exists (== null) it is the first "run" so you could set it to prevent further loop execution. use:
localStorage.setItem("itemname", "notNull");

How to set offline a User in the DB when it closes the browser?

i have a logout function that sets the User offline in my DB (mysql), but if it just closes the browser, in my DB the User is still online despite it's not , How can i manage this? How can i set the User Offline without press the logout botton? Cheers in advance !
Ps: Yes, i'm using SESSION
You can do it in following ways.
1) send the Ajax request to server every 5 seconds to update the current time.
2) and where you want to show offline just get records where current time is more than 5 seconds ago.
HI the only reliable way is to set an interval that calls the server and logs it in a database
var timeout = 15000; //milliseconds
setInterval( function(){
$.post('yoursite/keepalive' );
}, timeout );
Then you check the session on the server side you need a simple database table with the user id and a timestamp of the last time keepalive was called, then you just get the current time an there id ( from the session ) and save that. Then you can check if its been more then say like 20 seconds you will know they are gone ( should be updated every 15 sec ). Obviously you would need to have this interval on every page of your site to accurately track a user.
Things such as checking the session time, and unload are not accurate enough,
Unload is fired when any page is closed, so for example,
we have a user that has 2 pages open, they close one of them. the other page is already loaded so there is no traffic between client and server, and no way to know that page is still open
for Session time we have a similar problem, say someone is reading a long post on your page, They need to use the facilities and leave the page open. 30 minutes go by the come back and continue reading the post for another 10 minutes. now maybe the session has expired maybe it hasn't the fact remains they are still looking at your site, and you have no way to know it.
An interval will continue as long as the page is open and there are no javascript issues. A disadvantage of this is it will also keep their session updated ( you can get around this by sending the user id along with the ajax and not using the session, but that has other complications ) because you have that 15 second update you can check anytime if it has been more then 15 seconds. Say you want to display a list of online users to your other forum users, you just query for everyone with a current timestamp from that table, easy beazy.
As for the amount of time for the interval, you have to strike a balance between performance ( network traffic ) and how granular you need to know the information, if it's ok to only know if they logged off within the last minute then use that, if you can wait 5 minutes to know etc....
Really the Crux of the problem is how the server, and a client communicate. Right there is no two way communication like if your on the phone. It's more like a walkies talky where you have to say 10-4 and let go of the button for the other guy to talk. Essentially a client will make a request, that request is fulfilled by the server. that is the end of the communication and the state. Subsequent request state is maintained by using session so the next request uses that session to 'remember' the client. other then that there is no communication between client and server. There is no way to know they hung up the phone, for example, but to ask them if they are still there. ( this is an oversimplification because you cant send a request from the server to ask, more like they have to tell you they are not there, unless you use node.js or something like that ).
As #David has mentioned you could track this based on last activity, for that you would just need to know when the session was last updated. One of the easiest ways is to move the session into a database handler via http://php.net/manual/en/function.session-set-save-handler.php that way you can access when they were last active.
Using this vs ajax really depends on what you need to know, and how accurately. There is also the content of your page to weigh in. If you have a site that makes requests frequently it would be a better approach because you save on network traffic, for example. However, if you have long post someone could be reading for 20-30 minutes but want to know more frequent then that use ajax.
You can do it in many ways:
Launch an AJAX call on onbeforeunload javascript event. Prompting for a confirmation "Windows is closing, are you sure? YES/NO" should give you enough time to set the flag in the db, just be sure that if the user clicks "NO" you should unset your flag
Check session time... Add a var in your PHP_SESSION that is updated at every user event. If it becomes older than a preset threshold (i.e. 5 minutes), you can safely assume the user is gone
Example for onbeforeunload
function myConfirmation() {
return 'Are you sure you want to quit?';
}
window.onbeforeunload = myConfirmation;
You can try the javascript beforeunload event:
window.onbeforeunload = function() {
// Some AJAX request to logout.php or whatever script handles the logout
}
It will trigger when the user attempts to close the current window.
Watch out though, even if the user closes a single tab (your page), the event will be triggered, so if there are other tabs opened, so the browser will be, and you'll still get your users logged out.
Also, if several tabs of your website are opened, and you close one of them, you'll get your users logged out, which may not be what you want, so you'll probably have to find a way around to fix it.

Save controller state on page refresh

I'm trying to implement a gmail like save message as draft functionality in my form.
Use Case: There is one form with certain fields which includes some text box, some image uploads, etc. My problem is how can I retain the values of these if these have been filled by user on a page refresh. Remember page is not yet submitted by user. If it has been submitted then I could have retrieved the values from server but how can I store values in input box now in case no submit button is clicked.
Should there be some api which will save the values regularly or can there be some api which can be invoked only when user is about to close the page or refresh it ?
I have no idea about this and would appreciate any pointers in this.
Update:
Based on the suggestions, I tried to explore some tutorials/blogs which can show the preoper design and implementation for using local storage. I found following good links:
http://yeoman.io/codelab/local-storage.html
https://domantasjovaisas.wordpress.com/2014/09/05/angularjs-saving-global-variable-in-localstorage/
Few doubts:
It seems we can store a JSON object in local storage but how can I store a given object for a given user.
Use Case: A user can create multiple messages. I just want to keep the last message which was not saved neither sent. How can I design this so that storage works fine ? For a given userId I want to keep some data in local storage. Is it safe to store a db Id in local storage ?
Please suggest
I suggest using a library that abstracts over localStorage and defers to cookies if you are looking to support older browsers. Use JSON.stringify and pass it to your storage service. You can also append usernames to the key if you are likely to have multiple users on one machine. It would be good practice anyways.
Examples include:
https://github.com/grevory/angular-local-storage
http://ngmodules.org/modules/ngStorage
You can hook into ng-change, watches, event listeners or use a timer as someone else suggested.
UPDATE: You can find a trivial implementation here, http://scionsoftware.com/Blog/saving-form-state-with-angular-js/
If you're looking to do it for only one string value as you implied, simply remove the JSON.parse and JSON.stringify pieces from the javascript.

How to add javascript to page on login and logout in Drupal 6

I'm working on a module and am trying to add some javascript to the next page a user sees after logging in or out. Calling drupal_add_js() on hook_user (op == login) doesn't seem to work; I'm assuming this is because drupal_goto is called after the login is completed and a fresh page request is initiated.
I've considered using hook_user to set session variables which I can then respond to on the next page load but that seems somewhat fragile. Any suggestions?
If you want something to be carried over to a new page you only have a few options:
Alter the url.
Store in the database.
Store in session.
Altering the url, would probably be quite hard and messy. Storing in the session or database is basically the same thing. So you would probably want to use the Drupal session system instead of making your own.
You could add something in the session and then in hook_init check for it and if it's there add the js and delete it from the session.
I don't think you will find a much better solution, though it would be nice if there were.

Categories