LocalStorage only shares the same space in the same domain. Both protocol and port are affected. Note:
http://a.com
和https://a.com
并Do not share;http://a.com:80
和http://a.com:8080
Do not share;http://a.com
和http://a.com:80
Shared;
✔ commonly used API
localstorage.setItem(key, value)
Save the data,key
value
Will be converted to a string, in order to prevent unexpected situations, it is best to convert it to a string before storing;localstorage.getItem(key)
Get the data,key
Is converted to a string;localstorage.clear()
Clear the current domainlocalStorage
Stored data;localstorage.length
Get the number of items stored under the current domain;localstorage.key(n:number)
Gets the display paneln
The articlekey
, feel more chicken ribs;
✔ Limit the capacity of the browser to localStorage
After testing, Chrome, FireFox and Edge are all 5M (IE is ignored).
Below is the capacity detection code, accurate to 1K.
const add10KStr = new Array(1024).fill('0000000000').join('') // 10240 Byte => 10K const add1KStr = new Array(1024).fill('1').join('') // 1024 Byte => 1K const storageKey = 'QuotaTest' function localStorageQuota() { localStorage.clear() function setText(str) { console.log(str) } let total = '' let interval = null interval = SetInterval (() => {try {setText(' Data insert => ${total.length / 1024}K ') localStorage.removeItem(storageKey) localStorage.setItem(storageKey, total + add1KStr) total += add10KStr } catch (e) { clearInterval(interval) if (e && e.code === 22) { ${total.length / 1024}K ') Interval = setInterval(() => {try {setText(' insert data => ${total.length / 1024}K`) localStorage.removeItem(storageKey) localStorage.setItem(storageKey, total + add1KStr) total += add1KStr } catch (ee) { clearInterval(interval) if (ee && ee.code === 22) { SetText (' more than capacity increase (1 K)) setText (` currently stored at ${1024}. The total length/K `)}}}, 0)}}}, 0)}Copy the code
For example, Chrome will raise an exception if it cannot be inserted. The value of E.code is 22.
✔ Storage Event
A Storage event can be used to broadcast between pages in the same domain. The event is raised on the window. This event is not triggered by the current page (TAB) that causes data changes (if the browser opens multiple pages under a domain name at the same time, when one of the pages changes the data of localStorage, the storage event of all other pages will be triggered, but the original page does not trigger the storage event).
The event contains the following key information:
event.key
alteredkey
;event.oldValue
Change the previous value;event.newValue
The changed value;
There are two trigger conditions:
- Not triggered by current TAB, same
url
It also fires on two different tabs; localstorage.setItem(key, value)
Only when set last timevalue
Different times will trigger this event, the same words do not need to trigger;
For example, https://a.com/a.html has the following code:
localStorage.setItem('name'.'lx')
window.addEventListener('storage', e => {
console.log('e', e)
})
Copy the code
At this point, the following is done at https://a.com/b.html:
localStorage.setItem('name'.'lxfriday')
Copy the code
Then page A will print the following:
➤ Other uses for stocking localStorage
ref
- Iammapping.com/the-other-w…
- Cache static files;
- As the front-end DB storage medium;
- Flexible access to JSON data: github.com/typicode/lo…
- CURD operations using SQL: github.com/agershun/al…
✔ sessionStorage
It is similar to localStorage except that data stored in localStorage does not have an expiration date, while data stored in sessionStorage is cleared at the end of the page session (it is cleared when the current page is closed).
The page session remains as long as the browser is open, and the original page session remains when the page is reloaded (refreshed) or restored. Open up a page in a new TAB or window when copying the top browsing session context as the context of a new session, it is not good understanding, mean to click on the current page < a target = “_black” > < / a > tag, in the new page sessionStorage values for the current page is copied, Notice it’s not shared.
✔ sessionStorage application
- Storage user input content, when the page refresh can be immediately displayed before the refresh of the content;
- For browser Historay deployed single-page applications, you can use sessionStorage in front to achieve route matching (404 will not be reported), do not need to use nginx to do a forwarding;
The process for automatically matching routes looks like this: When accessing the a.com/page1 page, the server returns 404.html (the browser’s current route is still a.com/page1) because it does not have the page. 404. HTML:
sets the sessionStorage.redirect to the current URL, and
immediately redirects the page to /. The browser executes the code in
Set up a 404.html with the following contents in the head
<head>.<script>
sessionStorage.redirect = location.href;
</script>
<meta http-equiv="refresh" content="0; URL='/'"></meta>
</head>
Copy the code
In the single page application template index.html, fill in the following code:
<body>
<div id="root"></div>
<script>
// This code should be placed in front of other js; (function(a) {
var redirect = sessionStorage.redirect
delete sessionStorage.redirect
if(redirect && redirect ! = location.href) { history.replaceState(null.null, redirect)
}
})()
</script>
</body>
Copy the code
demo
Follow the public account, reply to add group, add the main wechat account, will pull you into the communication group, any questions will reply, welcome to join.
Thank you for reading, welcome to follow my public account Yunying Sky, take you to interpret the front-end technology, master the most essential skills.