⬆️ ⬇️

Alternative to cookies via java script

Search in Habra did not give a similar article, so I dare share with those who are not yet aware

Many of you have faced the problem of storing data on the client. First of all, cookies come to my head, but the data storage restriction of no more than 4kb does not make everyone happy, today if I may let you tell you how to store about 100kb on the client using Java Script.



The HTML5 specification describes several techniques for storing data on a client without using cookies. Consider some of them or their alternatives in more detail:



The sessionStorage attribute



This method is supported by Firefox since version two. This is a global object that is stored in the current session of the document and is stored while the document is open, reloaded or restored, but opening a new window or tab with the same address will generate a new session.

Example of use:

sessionStorage.text = “Habr remembers you,% username%” ;

alert ( “UFO:„ + sessionStorage.text);

* This source code was highlighted with Source Code Highlighter .




The disadvantage of this approach is that it cannot spread to other pages or windows, and works only in the limit of its session.

')

globalStorage



Due to the fact that HTML5 is still developing in Firefox there is a global object globalStorage, which allows you to store data in the browser for a long period of time without being tied to a session, which allows you to use and manipulate the saved data when opening a new window, tab, closing / opening a browser . Binding storage of this kind is carried out by domain.

Example of use:

// Initialize the repository

storage = globalStorage [ “habrahabr.ru” ];

// write the value

storage [ 'hello' ] = 'Hi habrahabr!' ;

// Display the value

alert (storage [ 'hello' ]);

// If necessary, delete

delete storage [ 'hello' ];



* This source code was highlighted with Source Code Highlighter .




This approach allows us to save up to 5 megabytes of information on a client in a specific domain, and use our storage within the domain and its subdomains. That is, it will act like habrahabr.ru , antyrat.habrahabr.ru , etc.



userData



But all that has been described above affects only Firefox (Gecko) browsers, what about IE?

Small-scale went the other way, but did not limit the developers to the excellent possibility of cookies.

Data storage on the client in the donkey is done by working with behavior. Specifications for working with this can be read here , but for now we will consider an example:

<! - First we need an item in which we will store data ->

<span id = "customStorage" > </ span>

<! - Next, we need to initialize our repository ->

<script language = "javascript" type = "text / javascript" >

if ( document .getElementById ( 'customStorage' )) {

storage = document .getElementById ( 'customStorage' );

storage.addBehavior ( "# default # userData" );

storage.load ( "habr" );

// Initialization has passed and now we can already work with our repository

storage.setAttribute ( “hello” , “Habraprivet!” ); // Set our variable

storage.save ( "habr" ); // And save it

// Now you can display the result

alert (storage.getAttribute ( "hello" ));

}

</ script>

* This source code was highlighted with Source Code Highlighter .


Also, our store as well as in cookies, you can set the time of life, but if necessary, you can read about how to do this.



Client-side Database Storage



The WebKit developers (Safari) came close to the HTML5 recommendations and made it possible to create a database on the client.

Let's go straight to the example:

// open our database

db = openDatabase ( "habrahabr" , "1.0" );

// Create a table if it does not already exist

db.transaction ( function (tx) {

tx.executeSql (

“CREATE TABLE IF NOT EXISTS habr (id TEXT, hello TEXT, unique (id))” , // Query to the database

[], // Here, if necessary, we transfer variables to our request; they replace the characters "?" In our request. in order

function (tx, result) {}, // processing if successful

function (tx, error) {alert ( “UFO:„ + error.message); } // processing in case of failure

)

});

// write the value

db.transaction ( function (tx) {

tx.executesql ( “insert into habr (id, hello) values ​​('1', 'Habri hi!')” , [],

function (result) {},

function (tx, error) {alert ( “UFO:„ + error.message); });

});

// Enter the result

db.transaction ( function (tx) {

id = 1;

tx.executesql ( “select hello from habr where id =?” , [id], function (result) {

// Display the result

alert (result.rows.item (0) .hello);

}, function (tx, error) {alert ( “UFO:„ + error.message); });

}); * This source code was highlighted with Source Code Highlighter .




The disadvantage of this approach is that the database can only work within the domain. Subdomains are not supported.

A lot of information about this is not found, here is this example of digging.



Local SharedObject



Opera users are the least fortunate of all, none of the above examples, the opera does not support, so you need to resort to tricks.

Starting with Flash Player 6.0.40.0, Flash supports Local SharedObject, here we will use it and we will.

How it looks from ActionScript:

// Create Local SharedObject

theLocalSharedObject = sharedobject.getLocal ( “habra” );

// Store the value

theLocalSharedObject.data.hello = “Habraprivet” ;

theLocalSharedObject.flush ()

// Get the value

hello = theLocalSharedObject.data.hello; * This source code was highlighted with Source Code Highlighter .


I’m not very strong in a flash, and now I don’t have the means to describe this method in more detail, so I’ll tell you the essence, all you need is to create a Flash <=> JS interaction bridge, to communicate with each other so that it is easy to transfer parameters flush and take them from his vault. This method is valid for the entire domain. Restrictions on size depends on the user's settings, the default is 100 kilobytes.



Silverlight Isolated Storage



If the user has Silverlight installed then you can use the Isolated Storage object. The specification for it can be found here .

Again, now there is no possibility to describe this method in more detail.






As a result, we received a means of storing information on the client in the amount of 100kb. You can use it for any purpose.

At the moment I am writing a cross-browser data storage script on the client, which would be able to synchronize the storage in browsers through a flash. A record read without a flash or when access is denied to use the built-in functions of browsers. If the article seems interesting then I will post this lib.



PS: Please do not kick much for the post, as this is my first post on Habré.

PPS: Do you also have this bad habit of highlighting text before reading?



UPD : The donquijote user provided a link to a script that is trying to implement the described mechanism, the only drawback I think is that when opening another browser, the data is transferred only if it was eaten, and there and there the storage worked via flash. In my article, I forgot to take into account 2 more very powerful data storage mechanisms on the client, this is Adobe AIR and Google Gears , the implementation of the latter is in the above script, thanks to shamaniac for the hint.



Source: https://habr.com/ru/post/29293/



All Articles