Prevent loss of variables when browser reload button is pressed [duplicate] - javascript

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
Is it possible to keep my (global) variables when the page is reloaded? If yes, how?
Thanks for any help.
Best regards.

Try this cookie-less javascript function.
It basically store your data in the window.name property which does not clear the value when you reload the page or goes to another site.

You can persist data across page reloads via something like window.localStorage, window.sessionStorage (proprietary Mozilla extension) or database abstraction (window.openDatabase) provided by some of the WebKit -based browsers. See this article on MDC for a nice overview of Storage interfaces and this WebKit article on their database introduction.

In the same style you can store string values in the hash key.
Using the property:
window.location.hash = 'flight/105';
Then when refreshing the page you initialize back your variables.

The JavaScript environment will be reset when the browser leaves your page. However, you could register an onUnload handler to serialise your array to a cookie, then check for this every time the page is loaded and unserialise it if present.

Does your browser have a reset button, or do you mean the reload button?
When the page loads, everything is loaded fresh. There is nothing left from any previous page. The only place to store anything that survives loading a page is in a cookie.
Note that the amount of data that you can put in cookies is limited to a few kilobytes per site. The exact limit varies from browser to browser, but you can't expect to be able to put more than perhaps a kilobyte or two worth of data in cookies.

Are you talking about Cookies? If so you might want to review this open-source module
This will easily allow you to store cookies, that is data, even after a browser reload click. This makes doing it really easy and it is what I use.
var cookie = new HTTP.Cookies();
cookie.write('mydata', 'myvalue', '+1y');
//later on you can get that data EVEN AFTER a reload
var x = cookie.read('mydata');
You probably shouldn't try to make a cookies implementation from scratch though because it is very painful and you have to do a lot of testing across web browsers, such as to make sure Internet Explorer works.

Related

sessionStorage cleaned up unexpectedly on Android

I have a website which saves a stringified JavaScript object into the sessionStorage. It works well on desktop browsers - data survives over page reloads as per described on MDN.
On Android phones, it is not uncommon that a tab is reloaded when user switches back from another tab or when the browser is brought back from background to foreground, and I expect the sessionStorage will persist. This doesn't however seem to be the case. The sessionStorage is gone missing, as if a new session is created.
I have thought of using localStorage instead, which will not expire even if the session is closed. It doesn't really sort out all my problems though - as I expect a user can open it multiple times on multiple tabs, and do different things on each of them.
So my questions are:
Is the sessionStorage behavior described above as expected? If not, what can I do to rectify it?
If the behavior is as expected, and I have to rely on localStorage, how can I identify the object stored for each individual tab?
Thanks in advance for your help!
As others commented, SessionStorage is temporary by design. Mobile browser lifecycle is highly geared towards reducing resource usage and tabs are teardown more aggressively.
To workaround this issue, you can push a random tab ID to the URL and then prefix all LocalStorage keys with this ID. When tab is refreshed you simply read the tab ID from the URL and use it for accessing data in LocalStorage.
LocalStorage has a very simple API, so you could write a wrapper hiding the key prefixing away from your other code.
Yes, that is how sessionStorage works. The behavior is expected.
sessionStorage is unique per tab. If the user closes the tab the sessionStorage gets deleted.That is, the session storage is saved only as long as user stays on the tab.
Whatever you store in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
So, yes, it'd be better to use localStorage and clear it out at the end of the session.

Does chrome extension has it's own document.cookie?

I'm writing a chrome extension. I want to store some data in the browser cookie so that I can use it later. Cookie is a perfect way to do that. Does chrome extension have it's own document cookie for this like all the websites?
I got this result when I did some research https://developer.chrome.com/extensions/cookies
But it mostly talks about cookie API and getting cookies of other websites hence the question. Also does chrome storage have any advantages over using a cookie? I just need to store 2/3 key value pairs. https://developer.chrome.com/apps/storage
I will say Just one line and you will understand it.
Cookies are always related to a website/domain.
It does not make sense to ask if Chrome extension has a cookie. You can have a cookie for every domain.
Some more information to help you solve your problem. If you see chrome extension model, you can see there are
Background Scripts
Content Scripts
Popup Page/Scripts
If you want to store cookie in a background script/ popup script, then you can definitely do it. But that cookie will be saved for the domain of your background script which is essentially your chrome extension id.
If you store cookie in a content script, then you are storing information in cookie which belongs to the domain on which your content script is injected.
One one hand, yes, cookies are available in Chrome extensions. But this is a very unorthodox method of storing data in extensions.
As you correctly pointed out, chrome.cookies API is for manipulating other pages' cookies. The common way of working with cookies in JS is document.cookie.
What are the common ways to store persistent data?
Two classic ways are localStorage and chrome.storage.
I've answered about them before; see this answer for comparison between them, and this answer for a usage example.
To decide what you need, the most important question is: do you need to access data from a content script?
If no, using localStorage may be simpler.
If yes, you will need to use either chrome.storage, or message passing.

Cross tab variable in javascript without server interaction

I am developing a chat system and got a question that I would like to ask you.
I dont think this is possible but since I see similar behaviour in some websites, I would like to know How to access a variable defined/modified in an other tab? I mean I don't want to send it to a server. How to do something like
var myvalue=getValueInAvailableTab(varName);
If it is not possible, how does facebook know if the chat dialog has been closed in another tab? Do they post this event on their server and then retrieve it?
I am sorry I am not stealing behaviours but this is a best example to explain what I want to do.
In most circumstances, the answer to your question is that you cannot access a Javascript variable in another tab. There are other ways to pass data between tabs, however:
You may create a browser extension that has the functionality that you want. Though different browser frameworks have different limitations upon accessing the code of pages that are open.
If the windows are guaranteed to be opened by the same parent window, you may use window.parent or window.opener
If both tabs are from the same origin site, you may have one tab store the value in the cookie, and have the other tab retrieve that value.
These are all ways in which you may accomplish what you need without server interaction. I'm not sure what method Facebook uses, however.
As long as the browser tabs are from the same domain, you can keep track of them by keeping a reference to the return value of window.open(...):
var wins = {};
wins.someTab = window.open(...);
wins.someOtherTab = window.open(...);
Then to access global variables in that tab:
wins.someTab.someVar
And from inside that sub-tab:
opener.wins.someOtherTab.anotherVar

Chrome Extension Saving Data

I am working on a Chrome extension that needs to save some information (tabs info mainly) that will exist throughout the lifetime of the extension (e.g , since the user starts using it until he closes the browser).
One option is to use localstorage, however localstorage can only save Strings and that makes it very uncomfortable for me (since I have a bunch of data to save - dates , URLs , integers etc). What I'm looking for is using my own javascript objects that will live throughout the time of the extension.
Now the problem is that defining these objects in a script in some javascript files will erase them each time the user clicks on the browser action . In other words I have a browser action called popup.html that includes a javascript file (in which I want to save my objects) and every time the user clicks on the browser action all the objects I defined in the JS file are lost, yet I want everything to be persisted .
What option do I have to keep data that persists through many clicks on the browser action and that is NOT localstorage?
You really should use localStorage (you may use JSON.stringify and JSON.parse).
If you really don't want to use localStorage nor a server side storage, use IndexedDb : https://developer.mozilla.org/en/IndexedDB/Using_IndexedDB
Try using the Filesystem API's persistent storage. That is more reliable than localStorage. localStorage will be cleared once the user clears the cache, cookies etc. Filesystem is more reliable.
This answer about using chrome.storage worked for me far better than the others.
https://stackoverflow.com/a/14009240/766115
It's like localStorage, but works between the popup / background and content scripts.

Block people from returning to site?

I'm tasked with coming up with a way to determine if a person has reached our site via using their back button (meaning they left our site and came back) and log them out if so.
I've come up with some options, but am wondering what other options I may be missing.
FYI, we do have a session state, so server-side we're covered for long absences, but they want an additional check on the client side.
option 1: set a cooking via onunload that expires in x seconds. On each page of our site, I check for said cookie. If it exists, I assume they came from another page on our site and do nothing. If it's not there, I assume they have been gone from our site more more than x seconds and redirect out. Con: Blackberry devices running OS5 don't support onunload.
option 2: same as #1 but instead of setting cookie onunload, we set it on every click of every link that goes to another page on our site. con: messy
option 3: check browser history on every load of every page of our site. If the previous URL is not one of ours, we log them out. Cons: browser support? It looks like previous/next history objects are now blocked in modern browsers due to security.
Option 4: Via JS, every x seconds, check for a cookie. If it's there, reset it to expire in x seconds. If it's not there, assume they've returned from somewhere else. Con: Not sure if the JS cookies would be set while that page may be in the background (app switching on an iPhone, or using a different tab in a desktop browser).
Any other options I should consider? Is there a 'proper' way to handle this? Is this just grasping at straws trying to prevent normal browser behavior?
You could keep the current page name/action/identifier in a session variable, then use a javascript onChange/load/keyup/keydown to request the current state of the user from the server. If it does not match, redirect or otherwise block them from viewing the current page.
This is a method that I've used, but it has it's downsides.... for example, onload doesn't always seem to work when the user uses the back button. OnChange, etc on certain form fields definitely works. Timers are pretty straightforward, as well, but a quick user can get input through the page regardless.
It's not that complicated... Use javascript history object
history.next gives you the complete url of the page in the forward button. A simple regex can tell if it's from your domain or not.
I just don't know if it's supported by all browsers

Categories

Resources