preface

Good Friday, brothers, after the recent wave of layoffs in big factories, the boys who study together have stopped the motivation to continue to roll, we continue to rush today with an interview question!!

For the technology of the current situation of the community now, I feel most of the analysis of user’s portrait users is more like a short article frequency fast rhythm, so it is a simple interview questions, try to use the shortest time mining will be behind the knowledge share with everyone, like in a subsequent interview, hope to help you, if is just their intellectual blind area might as well to help support the thumb up

background

Recently, in the process of interviewing candidates, it is often difficult to get the parts he is good at or familiar with from the resume for in-depth communication. Therefore, I have to ask some basic eight-part essay to see the depth of the candidate’s understanding of a simple point. This time we start from the front-end common Web storage API local storage, to ask about the difference between these two common features

Storage API usage

Note that both have the same prototype object, Storage. I’m sure it would be a plus if you could answer this during the interview!

Web Storage has the following two mechanisms:

  • sessionStorageFor each given Origin, a separate storage area is maintained that is available for the duration of the page session (that is, as long as the browser is open, including page reloads and resumes).
  • localStorageSame functionality, but data remains after the browser closes and then opens again.

As an interface of the Web Storage API, a Storage provides the function of accessing session Storage or local Storage under a specific domain name. For example, you can add, modify, or delete stored data items.

attribute

  • Storage. Length read-only

    Returns an integer representing the number of data items stored in a Storage object.

methods

  • Storage.key()

    This method takes a number n as an argument and returns the NTH key name in the store.

  • Storage.getItem()

    This method takes a key name as an argument and returns the value of the key name.

  • Storage.setItem()

    The method takes a key name and value as arguments, adds the key-value pair to the store, and updates the corresponding value if the key name exists.

  • Storage.removeItem()

    The method takes a key name as an argument and removes the key name from storage.

  • Storage.clear()

    Calling this method clears the store of all key names.

LocalStorage and sessionStorage are the most obvious differences

The stored data is saved in the browser session. LocalStorage is similar to sessionStorage, but the difference lies in that: Data stored in localStorage can be retained for a long time. When the page session ends — that is, when the page is closed, the data stored in sessionStorage is erased.

This point mentioned above, most of the students should know the difference, the two application business scenarios are different.

When clicking a link to open a new Tab page, sessionStorage will not inherit to the new Tab page, even if the new Tab page complies with the same origin policy, sessionStorage is associated with the current Tab page

Compatibility difference

Verify that the current browser is available

As you can see from the screenshot of Caniuse above, there are different browser compatibility differences, and in order to be able to use localStorage, we should first verify that it is supported and available in the current browsing session.

Browsers that support localStorage will have a property called localStorage on the window object. However, simply asserting that the property exists may throw an exception. If localStorage does exist, there is still no guarantee that it will actually be available, as various browsers provide Settings to disable it. Therefore, the browser may support localStorage, but not scripts on the page.

function storageAvailable(type) {
    var storage;
    try {
        storage = window[type];
        var x = '__storage_test__';
        storage.setItem(x, x);
        storage.removeItem(x);
        return true;
    }
    catch(e) {
        return e instanceof DOMException && (
            // everything except Firefox
            e.code === 22 ||
            // Firefox
            e.code === 1014 ||
            // test name field too, because code might not be present
            // everything except Firefox
            e.name === 'QuotaExceededError' ||
            // Firefox
            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
            // acknowledge QuotaExceededError only if there's something already stored(storage && storage.length ! = =0); }}Copy the code

Call it here

if (storageAvailable('localStorage')) {
  // It can be used
}
else {
  // You can't use it
}
Copy the code

The storage space

Both localStorage and sessionStorage have storage space. In case the string length we set to save is too large, we need to count whether the current storage space has exceeded the limit. If the limit is exceeded, we need to prompt the user or clear the storage.

Verify 5MB storage space

var a = Array(5 * 1024 * 1024).fill(0).join(' '); // a string larger than 5MB

localStorage.setItem('a', a);
// VM1793:1 Uncaught DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'b' exceeded the quota.
Copy the code

Both comparisons

Here’s a summary of their differences

localStorage sessionStorage
grammar inheritanceStorageMethod of prototyping inheritanceStorageMethod of prototyping
usage Stored in thelocalStorageData can be retained for a long time When the page is closed, it is stored insessionStorageThe data will be erased
Storage size It’s usually 5Mb depending on the browser 5Mb
Compatibility difference Detailed see caniuse Detailed see caniuse
Storage Event Listening We can listen in when things change We can listen in when things change

summary

This article ends here, the level is limited inevitably have mistake, welcome correction error. Finally, I hope you can give me some compliments, which will be a great affirmation and motivation for my creation. I hope I can help you

This article refer to

Developer.mozilla.org/zh-CN/docs/… Developer.mozilla.org/zh-TW/docs/… Gist.github.com/paulirish/5…