Reid  Rohan

Reid Rohan

1643118000

Everything You Need to Know About Client-side Storage

awesome-web-storage

Everything you need to know about Client-side Storage.

Table of Contents

Introduction

What is Web Storage

Web storage, sometimes known as DOM storage (Document Object Model storage), provides web application software methods and protocols used for storing data in a web browser.

Web storage is being standardized by the World Wide Web Consortium (W3C). It was originally part of the HTML5 specification, but is now in a separate specification.

Modern websites and web applications these days are becoming smarter than before and to achieve such smartness, the data storage system plays a very crucial role. Be it storing visitors' data & settings or any kind of information, web-storage is a breakthrough in the history of web applications. It offers a very basic need of storing persistent data in the browser itself which has literally spurred up its application from game-changing novelty to must-have features.

Usually, this kind of data doesn't need a well-organized backend database. The purpose of the data varies as per the website/webapp requirements. Different pages of the same website need to share data among themselves to behave alike and perfectly. This sharing of data among windows/tabs is very common these days and most of the sites or web apps use it for various jobs like User Authentication, Personalization (showing different views to a new visitor and on subsequent visits), Tracking user behavior, etc.

Before HTML5, storing application level data was possible only using cookies. Cookies can store up to 4KB of data, including the bytes consumed by the cookie name. This domain-specific data is sent along with every browser request. With the advent of HTML5, it's much easier now to store structured data on the client-side securely and faster than ever. HTML5 introduced the concept of Web Storage. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. HTML5 introduces two such web storage mechanisms: LocalStorage and SessionStorage. There are so many limitations in using cookies which can now be overcome using web storage.

There's no term as "Perfectly Secured Persistent Storage" available in the browsers as any type of storage system( persistent or non-persistent) can be manually tweaked by the end-user(assuming she knows a bit of geeky stuff :P).

Web Storage concepts and usage

The two mechanisms within Web Storage are as follows:

  1. sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  2. localStorage does the same thing, but persists even when the browser is closed and reopened.

Web Storage interfaces

Storage

Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)

Window

The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage — which provide access to the current domain's session and local Storage objects respectively, and a Window.onstorage event handler that fires when a storage area changes (e.g. a new item is stored.)

StorageEvent

The storage event is fired on a document's Window object when a storage area changes.

Browser Support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
IE8+, Edge12+3.5+4+4+11.5+

Different Storage APIs

Following are various storage techniques which HTML5 storage provides. Each technique has its own pros and cons.

Cookies

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. Typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.

Pros:

  • Session Management - Easy to use with logins, shopping carts, game scores, or anything else the server should remember

Cons:

The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

Typically, the following are allowed:

  • 300 cookies in total
  • 4096 bytes per cookie
  • 20 cookies per domain
  • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)

API

Read

Reading all cookies accessible from the domain

var allCookies = document.cookie;

Write

Writing a new cookie on a domain

document.cookie = newCookie;

As mentioned in the mdn docs, any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:

;path=path - (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location.

;domain=domain - (e.g., 'example.com' or 'subdomain.example.com').

;max-age=max-age-in-seconds - (e.g., 60*60*24*365 or 31536000 for a year)

;expires=date-in-GMTString-format - If not specified it will expire at the end of a session.

;secure - Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.

Resources - more on cookies

localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

Pros:

If you look at the Mozilla source code it can be seen that 5120KB (5MB which equals 2.5 Million characters on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.

The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

Structured data can be stored but it has to be stringified before storing.

Simple API to save, update, and delete data.

Cons:

It works on same-origin policy. So, data stored will only be available on the same origin.

It stores everything as a string.

API

setItem

setItemDescription
methodlocalStorage.setItem(key, value)
paramskey(String/Number),
value(Number/String),
though it accepts other types, the value is always stored as a string, so, stringifying data before storing is preferred and the best way to avoid errors while reading
descriptionadds the key to the storage with the value, or update the key's value if it already exists.
examplelocalStorage.setItem('test', document.getElementById('js-btn').value);

getItem

getItemDescription
methodlocalStorage.getItem(key)
paramskey(String/Number)
descriptionreturns the value of the key passed.
examplelocalStorage.getItem('test')

removeItem

removeItemDescription
methodlocalStorage.removeItem(key)
paramskey(String/Number)
descriptionremoves the key from the storage.
examplelocalStorage.removeItem('test')

clear

clearDescription
methodlocalStorage.clear()
paramsNone
descriptionempties all the keys out of the storage.
examplelocalStorage.clear()

key

keyDescription
methodlocalStorage.key(n)
paramsn(a Number)
descriptionreturns the name of the nth key in the storage.
examplelocalStorage.key(0)

length

lengthDescription
propertylocalStorage.length
descriptionreturns the length of all the keys
examplelocalStorage.length

Resources - more on localStorage

sessionStorage

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

Pros:

Same as localStorage

Data can only be saved per window (or tab in browsers like Chrome and Firefox). Data saved is available for the current page, as well as for the future visits to the site on the same window. Once the window is closed, the storage is deleted.

Cons:

The data is available only inside the window/tab in which it was set.

The data is non-persistent i.e. it will be lost once the window/tab is closed.

Like localStorage, it also works on same-origin policy. So, data stored on one protocol/domain/port will not be available for different protocol/domain/port.

API

setItem

setItemDescription
methodsessionStorage.setItem(key, value)
paramskey(String/Number),
value(Number/String),
though it accepts other types, the value is always stored as a string, so, stringifying data before storing is preferred and the best way to avoid errors while reading
descriptionadds the key to the storage with the value, or update the key's value if it already exists.
examplesessionStorage.setItem('test', document.getElementById('js-btn').value);

getItem

getItemDescription
methodsessionStorage.getItem(key)
paramskey(String/Number)
descriptionreturns the value of the key passed.
examplesessionStorage.getItem('test')

removeItem

removeItemDescription
methodsessionStorage.removeItem(key)
paramskey(String/Number)
descriptionremoves the key from the storage.
examplesessionStorage.removeItem('test')

clear

clearDescription
methodsessionStorage.clear()
paramsNone
descriptionempties all the keys out of the storage.
examplesessionStorage.clear()

key

keyDescription
methodsessionStorage.key(n)
paramsn(a Number)
descriptionreturns the name of the nth key in the storage.
examplesessionStorage.key(0)

length

lengthDescription
propertysessionStorage.length
descriptionreturns the length of all the keys
examplesessionStorage.length

Resources - more on sessionStorage


Comparison Table

Web StoragecookieslocalStoragesessionStorage
Size limitMax 4kb (~2K chars)Max 5mb (~2M chars)Max 5mb (~2M chars)
Data StorageFileSytemFileSytemFileSytem
PayloadIn every HTTP reqNothingNothing
APIFairSimpleSimple
PersistentYesYesNo
Data FormatStringStringString
Same-originYesYesYes
Cross-originNoNoNo
Browser SipportAllIE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+IE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+
Size limits infolimitlimitlimit

Worth mentioning API for tackling cross-origin restriction

postMessage

One very interesting API, PostMessage is not a web-storage technique but it's the most efficient and reliable way of communicating between cross-origin browser windows/tabs. Along with web-storage APIs, it overcomes the web-storage restrictions of cross-origin.

Pros:

Safely enables cross-origin policy communication.

As a data point, the WebKit implementation (used by Safari and Chrome) doesn't currently enforce any limits (other than those imposed by running out of memory).

Cons:

Need to open a window from the current window and only then can communicate as long as you keep the windows open.

Security concerns - Sending strings via postMessage is that you will pick up other postMessage events published by other JavaScript plugins, so be sure to implement a targetOrigin and a sanity check for the data being passed on to the messages listener.

API:

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow - A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on Window.frames, if you're trying to start the communication from iframe to parent window then parent is also a valid reference

message - Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1]

targetOrigin - Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.

transfer(Optional) - Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

Security concerns

If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a completely foolproof way to avoid security problems.

If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.

Always specify an exact target origin, not *, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage.

Resources - more on postMessage:

FAQs

How to store data that works Cross-Origin too?

A combination of postMessage and localStorage / sessionStorage

Using postMessage to communicate between multiple tabs and at the same time using localStorage/sessionStorage in all the newly opened tabs/windows to persist data being passed. Data will be persisted as long as the tabs/windows remain open in case of sessionStorage and in the case of localStorage unless the data is deleted by the system or manually flushing it using dev tools. So, even if the opener tab/window gets closed, the opened tabs/windows will have the entire data even after getting refreshed.

  • across-tabs - Easy communication between cross-origin browser tabs

Contributing Guidelines

Please ensure your pull request adheres to the following guidelines:

  • Search previous suggestions before making a new one, as yours may be a duplicate.
  • Make sure the list is useful before submitting. That implies it has enough content and every item has a good succinct description.
  • Make an individual pull request for each suggestion.
  • Use title-casing (AP style).
  • Use the following format: [List Name](link)
  • Link additions should be added to the bottom of the relevant category.
  • New categories or improvements to the existing categorization are welcome.
  • Check your spelling and grammar.
  • Make sure your text editor is set to remove trailing whitespace.
  • The pull request and commit should have a useful title.
  • The body of your commit message should contain a link to the repository.

Author: Softvar
Source Code: https://github.com/softvar/awesome-web-storage 
License: 

#javascript #cookies #localstorage 

What is GEEK

Buddha Community

Everything You Need to Know About Client-side Storage
Zachary Palmer

Zachary Palmer

1555901576

CSS Flexbox Tutorial | Build a Chat Application

Creating the conversation sidebar and main chat section

In this article we are going to focus on building a basic sidebar, and the main chat window inside our chat shell. See below.

Chat shell with a fixed width sidebar and expanded chat window

This is the second article in this series. You can check out the previous article for setting up the shell OR you can just check out the chat-shell branch from the following repository.

https://github.com/lyraddigital/flexbox-chat-app.git

Open up the chat.html file. You should have the following HTML.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Chat App</title>
    <link rel="stylesheet" type="text/css" media="screen" href="css/chat.css" />
</head>
<body>
    <div id="chat-container">
    </div>
</body>
</html>

Now inside of the chat-container div add the following HTML.

<div id="side-bar">
</div>
<div id="chat-window">
</div>

Now let’s also add the following CSS under the #chat-container selector in the chat.css file.

#side-bar {
    background: #0048AA;
    border-radius: 10px 0 0 10px;
}
#chat-window {
    background: #999;
    border-radius: 0 10px 10px 0;
}

Now reload the page. You should see the following:-

So what happened? Where is our sidebar and where is our chat window? I expected to see a blue side bar and a grey chat window, but it’s no where to be found. Well it’s all good. This is because we have no content inside of either element, so it can be 0 pixels wide.

Sizing Flex Items

So now that we know that our items are 0 pixels wide, let’s attempt to size them. We’ll attempt to try this first using explicit widths.

Add the following width property to the #side-bar rule, then reload the page.

width: 275px;

Hmm. Same result. It’s still a blank shell. Oh wait I have to make sure the height is 100% too. So we better do that too. Once again add the following property to the #side-bar rule, then reload the page.

height: 100%;

So now we have our sidebar that has grown to be exactly 275 pixels wide, and is 100% high. So that’s it. We’re done right? Wrong. Let me ask you a question. How big is the chat window? Let’s test that by adding some text to it. Try this yourself just add some text. You should see something similar to this.

So as you can see the chat window is only as big as the text that’s inside of it, and it is not next to the side bar. And this makes sense because up until now the chat shell is not a flex container, and just a regular block level element.

So let’s make our chat shell a flex container. Set the following display property for the #chat-window selector. Then reload the page.

display: flex;

So as you can see by the above illustration, we can see it’s now next to the side bar, and not below it. But as you can see currently it’s only as wide as the text that’s inside of it.

But we want it to take up the remaining space of the chat shell. Well we know how to do this, as we did it in the previous article. Set the flex-grow property to 1 on the #chat-window selector. Basically copy and paste the property below and reload the page.

flex-grow: 1;

So now we have the chat window taking up the remaining space of the chat shell. Next, let’s remove the background property, and also remove all text inside the chat-window div if any still exists. You should now see the result below.

But are we done? Technically yes, but before we move on, let’s improve things a little bit.

Understanding the default alignment

If you remember, before we had defined our chat shell to be a flex container, we had to make sure we set the height of the side bar to be 100%. Otherwise it was 0 pixels high, and as a result nothing was displayed. With that said, try removing the height property from the #side-bar selector and see what happens when you reload the page. Yes that’s right, it still works. The height of the sidebar is still 100% high.

So what happened here? Why do we no longer have to worry about setting the height to 100%? Well this is one of the cool things Flexbox gives you for free. By default every flex item will stretch vertically to fill in the entire height of the flex container. We can in fact change this behaviour, and we will see how this is done in a future article.

Setting the size of the side bar properly

So another feature of Flexbox is being able to set the size of a flex item by using the flex-basis property. The flex-basis property allows you to specify an initial size of a flex item, before any growing or shrinking takes place. We’ll understand more about this in an upcoming article.

For now I just want you to understand one important thing. And that is using width to specify the size of the sidebar is not a good idea. Let’s see why.

Say that potentially, if the screen is mobile we want the side bar to now appear across the top of the chat shell, acting like a top bar instead. We can do this by changing the direction flex items can flex inside a flex container. For example, add the following CSS to the #chat-container selector. Then reload the page.

flex-direction: column;

So as you can see we are back to a blank shell. So firstly let’s understand what we actually did here. By setting the flex-direction property to column, we changed the direction of how the flex items flex. By default flex items will flex from left to right. However when we set flex-direction to column, it changes this behaviour forcing flex items to flex from top to bottom instead. On top of this, when the direction of flex changes, the sizing and alignment of flex items changes as well.

When flexing from left to right, we get a height of 100% for free as already mentioned, and then we made sure the side bar was set to be 275 pixels wide, by setting the width property.

However now that we a flexing from top to bottom, the width of the flex item by default would be 100% wide, and you would need to specify the height instead. So try this. Add the following property to the #side-bar selector to set the height of the side bar. Then reload the page.

height: 275px;

Now we are seeing the side bar again, as we gave it a fixed height too. But we still have that fixed width. That’s not what we wanted. We want the side bar (ie our new top bar) here to now be 100% wide. Comment out the width for a moment and reload the page again.

So now we were able to move our side bar so it appears on top instead, acting like a top bar. Which as previously mentioned might be suited for mobile device widths. But to do this we had to swap the value of width to be the value of height. Wouldn’t it be great if this size was preserved regardless of which direction our items are flexing.

Try this, remove all widths and height properties from the #side-bar selector and write the following instead. Then reload the page.

flex-basis: 275px;

As you can see we get the same result. Now remove the flex-direction property from the #chat-container selector. Then once again reload the page.

Once again we are back to our final output. But now we also have the flexibility to easily change the side bar to be a top bar if we need to, by just changing the direction items can flow. Regardless of the direction of flex, the size of our side bar / top bar is preserved.

Conclusion

Ok so once again we didn’t build much, but we did cover a lot of concepts about Flexbox around sizing. 

#css #programming #webdev 

Ian  Robinson

Ian Robinson

1624434540

Everything You Need to Know about Apache Storm

The ever-increasing growth in the production and analytics of Big Data keeps presenting new challenges, and the data scientists and programmers gracefully take it in their stride – by constantly improving the applications developed by them. One such problem was that of real-time streaming. Real-time data holds extremely high value for businesses, but it has a time-window after which it loses its value – an expiry date, if you will. If the value of this real-time data is not realised within the window, no usable information can be extracted from it. This real-time data comes in quickly and continuously, therefore the term “Streaming”.

Analytics of this real-time data can help you stay updated on what’s happening right now, such as the number of people reading your blog post, or the number of people visiting your Facebook page. Although it might sound like just a “nice-to-have” feature, in practice, It is essential. Imagine you’re a part of an Ad Agency performing real-time analytics on your ad-campaigns – that the client paid heavily for. Real-time analytics can keep you posted on how is your Ad performing in the market, how the users are responding to it, and other things of that nature. Quite an essential tool if you think of it this way, right?

Looking at the value that real-time data holds, organisations started coming up with various real-time data analytics tools. In this article, we’ll be talking about one of those – Apache Storm. We’ll look at what it is, the architecture of a typical storm application, it’s core components (also known as abstractions), and its real life-use cases.

Let’s go!

Table of Contents

#big data #data #technical skills #technology #everything you need to know about apache storm #apache storm

Reid  Rohan

Reid Rohan

1643118000

Everything You Need to Know About Client-side Storage

awesome-web-storage

Everything you need to know about Client-side Storage.

Table of Contents

Introduction

What is Web Storage

Web storage, sometimes known as DOM storage (Document Object Model storage), provides web application software methods and protocols used for storing data in a web browser.

Web storage is being standardized by the World Wide Web Consortium (W3C). It was originally part of the HTML5 specification, but is now in a separate specification.

Modern websites and web applications these days are becoming smarter than before and to achieve such smartness, the data storage system plays a very crucial role. Be it storing visitors' data & settings or any kind of information, web-storage is a breakthrough in the history of web applications. It offers a very basic need of storing persistent data in the browser itself which has literally spurred up its application from game-changing novelty to must-have features.

Usually, this kind of data doesn't need a well-organized backend database. The purpose of the data varies as per the website/webapp requirements. Different pages of the same website need to share data among themselves to behave alike and perfectly. This sharing of data among windows/tabs is very common these days and most of the sites or web apps use it for various jobs like User Authentication, Personalization (showing different views to a new visitor and on subsequent visits), Tracking user behavior, etc.

Before HTML5, storing application level data was possible only using cookies. Cookies can store up to 4KB of data, including the bytes consumed by the cookie name. This domain-specific data is sent along with every browser request. With the advent of HTML5, it's much easier now to store structured data on the client-side securely and faster than ever. HTML5 introduced the concept of Web Storage. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. HTML5 introduces two such web storage mechanisms: LocalStorage and SessionStorage. There are so many limitations in using cookies which can now be overcome using web storage.

There's no term as "Perfectly Secured Persistent Storage" available in the browsers as any type of storage system( persistent or non-persistent) can be manually tweaked by the end-user(assuming she knows a bit of geeky stuff :P).

Web Storage concepts and usage

The two mechanisms within Web Storage are as follows:

  1. sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  2. localStorage does the same thing, but persists even when the browser is closed and reopened.

Web Storage interfaces

Storage

Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)

Window

The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage — which provide access to the current domain's session and local Storage objects respectively, and a Window.onstorage event handler that fires when a storage area changes (e.g. a new item is stored.)

StorageEvent

The storage event is fired on a document's Window object when a storage area changes.

Browser Support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
IE8+, Edge12+3.5+4+4+11.5+

Different Storage APIs

Following are various storage techniques which HTML5 storage provides. Each technique has its own pros and cons.

Cookies

An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. Typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.

Pros:

  • Session Management - Easy to use with logins, shopping carts, game scores, or anything else the server should remember

Cons:

The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

Typically, the following are allowed:

  • 300 cookies in total
  • 4096 bytes per cookie
  • 20 cookies per domain
  • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)

API

Read

Reading all cookies accessible from the domain

var allCookies = document.cookie;

Write

Writing a new cookie on a domain

document.cookie = newCookie;

As mentioned in the mdn docs, any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:

;path=path - (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location.

;domain=domain - (e.g., 'example.com' or 'subdomain.example.com').

;max-age=max-age-in-seconds - (e.g., 60*60*24*365 or 31536000 for a year)

;expires=date-in-GMTString-format - If not specified it will expire at the end of a session.

;secure - Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.

Resources - more on cookies

localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

Pros:

If you look at the Mozilla source code it can be seen that 5120KB (5MB which equals 2.5 Million characters on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.

The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

Structured data can be stored but it has to be stringified before storing.

Simple API to save, update, and delete data.

Cons:

It works on same-origin policy. So, data stored will only be available on the same origin.

It stores everything as a string.

API

setItem

setItemDescription
methodlocalStorage.setItem(key, value)
paramskey(String/Number),
value(Number/String),
though it accepts other types, the value is always stored as a string, so, stringifying data before storing is preferred and the best way to avoid errors while reading
descriptionadds the key to the storage with the value, or update the key's value if it already exists.
examplelocalStorage.setItem('test', document.getElementById('js-btn').value);

getItem

getItemDescription
methodlocalStorage.getItem(key)
paramskey(String/Number)
descriptionreturns the value of the key passed.
examplelocalStorage.getItem('test')

removeItem

removeItemDescription
methodlocalStorage.removeItem(key)
paramskey(String/Number)
descriptionremoves the key from the storage.
examplelocalStorage.removeItem('test')

clear

clearDescription
methodlocalStorage.clear()
paramsNone
descriptionempties all the keys out of the storage.
examplelocalStorage.clear()

key

keyDescription
methodlocalStorage.key(n)
paramsn(a Number)
descriptionreturns the name of the nth key in the storage.
examplelocalStorage.key(0)

length

lengthDescription
propertylocalStorage.length
descriptionreturns the length of all the keys
examplelocalStorage.length

Resources - more on localStorage

sessionStorage

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

Pros:

Same as localStorage

Data can only be saved per window (or tab in browsers like Chrome and Firefox). Data saved is available for the current page, as well as for the future visits to the site on the same window. Once the window is closed, the storage is deleted.

Cons:

The data is available only inside the window/tab in which it was set.

The data is non-persistent i.e. it will be lost once the window/tab is closed.

Like localStorage, it also works on same-origin policy. So, data stored on one protocol/domain/port will not be available for different protocol/domain/port.

API

setItem

setItemDescription
methodsessionStorage.setItem(key, value)
paramskey(String/Number),
value(Number/String),
though it accepts other types, the value is always stored as a string, so, stringifying data before storing is preferred and the best way to avoid errors while reading
descriptionadds the key to the storage with the value, or update the key's value if it already exists.
examplesessionStorage.setItem('test', document.getElementById('js-btn').value);

getItem

getItemDescription
methodsessionStorage.getItem(key)
paramskey(String/Number)
descriptionreturns the value of the key passed.
examplesessionStorage.getItem('test')

removeItem

removeItemDescription
methodsessionStorage.removeItem(key)
paramskey(String/Number)
descriptionremoves the key from the storage.
examplesessionStorage.removeItem('test')

clear

clearDescription
methodsessionStorage.clear()
paramsNone
descriptionempties all the keys out of the storage.
examplesessionStorage.clear()

key

keyDescription
methodsessionStorage.key(n)
paramsn(a Number)
descriptionreturns the name of the nth key in the storage.
examplesessionStorage.key(0)

length

lengthDescription
propertysessionStorage.length
descriptionreturns the length of all the keys
examplesessionStorage.length

Resources - more on sessionStorage


Comparison Table

Web StoragecookieslocalStoragesessionStorage
Size limitMax 4kb (~2K chars)Max 5mb (~2M chars)Max 5mb (~2M chars)
Data StorageFileSytemFileSytemFileSytem
PayloadIn every HTTP reqNothingNothing
APIFairSimpleSimple
PersistentYesYesNo
Data FormatStringStringString
Same-originYesYesYes
Cross-originNoNoNo
Browser SipportAllIE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+IE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+
Size limits infolimitlimitlimit

Worth mentioning API for tackling cross-origin restriction

postMessage

One very interesting API, PostMessage is not a web-storage technique but it's the most efficient and reliable way of communicating between cross-origin browser windows/tabs. Along with web-storage APIs, it overcomes the web-storage restrictions of cross-origin.

Pros:

Safely enables cross-origin policy communication.

As a data point, the WebKit implementation (used by Safari and Chrome) doesn't currently enforce any limits (other than those imposed by running out of memory).

Cons:

Need to open a window from the current window and only then can communicate as long as you keep the windows open.

Security concerns - Sending strings via postMessage is that you will pick up other postMessage events published by other JavaScript plugins, so be sure to implement a targetOrigin and a sanity check for the data being passed on to the messages listener.

API:

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow - A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on Window.frames, if you're trying to start the communication from iframe to parent window then parent is also a valid reference

message - Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1]

targetOrigin - Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.

transfer(Optional) - Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

Security concerns

If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a completely foolproof way to avoid security problems.

If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.

Always specify an exact target origin, not *, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage.

Resources - more on postMessage:

FAQs

How to store data that works Cross-Origin too?

A combination of postMessage and localStorage / sessionStorage

Using postMessage to communicate between multiple tabs and at the same time using localStorage/sessionStorage in all the newly opened tabs/windows to persist data being passed. Data will be persisted as long as the tabs/windows remain open in case of sessionStorage and in the case of localStorage unless the data is deleted by the system or manually flushing it using dev tools. So, even if the opener tab/window gets closed, the opened tabs/windows will have the entire data even after getting refreshed.

  • across-tabs - Easy communication between cross-origin browser tabs

Contributing Guidelines

Please ensure your pull request adheres to the following guidelines:

  • Search previous suggestions before making a new one, as yours may be a duplicate.
  • Make sure the list is useful before submitting. That implies it has enough content and every item has a good succinct description.
  • Make an individual pull request for each suggestion.
  • Use title-casing (AP style).
  • Use the following format: [List Name](link)
  • Link additions should be added to the bottom of the relevant category.
  • New categories or improvements to the existing categorization are welcome.
  • Check your spelling and grammar.
  • Make sure your text editor is set to remove trailing whitespace.
  • The pull request and commit should have a useful title.
  • The body of your commit message should contain a link to the repository.

Author: Softvar
Source Code: https://github.com/softvar/awesome-web-storage 
License: 

#javascript #cookies #localstorage 

David mr

David mr

1624305600

SAFEMOON UPDATE - ALL YOU NEED TO KNOW ABOUT SAFEMOON AND SAFEMOON PREDICTION

SAFEMOON UPDATE - ALL YOU NEED TO KNOW ABOUT SAFEMOON AND SAFEMOON PREDICTION

This is all you need to know about safemoon and I provide my safemoon prediction. This is a huge safemoon update so make sure to watch this video until the end.
📺 The video in this post was made by Josh’s Finance
The origin of the article: https://www.youtube.com/watch?v=ZtX7ZIVcXH4
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#bitcoin #blockchain #safemoon #safemoon #all you need to know about safemoon and safemoon prediction #safemoon update - all you need to know about safemoon and safemoon prediction

Einar  Hintz

Einar Hintz

1593244500

Storage in Android - How to save data and files in Android? - DataFlair

Storage in Android

Android uses a file system that is like a disk-based file system of other platforms. The Android system provides different options to save application data:

  • Application-specific storage in Android
  • Shared storage in Android
  • Preferences in Android
  • Databases in Android

Let us go through these all one by one.

1. Android Application-specific storage

In this, the stored data is meant only for a specific application’s use. It is stored either in a dedicated directory inside the internal storage or in external storage. The sensitive data, that is specific to the app and shall not be accessible to other apps is generally stored in Internal Storage. There are certain things about it that are:

a. To access it, we have two ways:

  • Internal Storage
  • getFilesDir() or getCacheDir()
  • External Storage
  • getExternalFilesDir() or getExternalCacherDir()

b. Permission is not required for Internal Storage as well as for External Storage. When considering external storage, we do not need permission for Android version 4.4(API level 19) or higher.

c. If the app data is in internal storage, other apps cannot access it. If the data is in external storage, files can be accessed by other apps.

d. If the application is uninstalled by any means, the data files also get deleted.

2. Shared Storage in Android

In this, the stored data is meant to be shared among other apps as well. It includes data such as multimedia, documents, etc. There are certain things about it that are:

a. Access the data with MediaStore API and Storage Access Framework.

b. To read the media file use these permissions: READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE for Android 10 or higher.

c. You can access the media files by other files through READ_EXTERNAL_STORAGE and the document files, through system file picker.

d. If you uninstall the app, the data would not be deleted from the External Storage.

3. Android Preferences

They store the data in a private database. It stores the data in the form of a key-value pair. There are certain things about it that are:

a. Data is stored in a key-value pair.

b. It can be accessed through the Jetpack preference library.

c. Data from this cannot be accessed through other applications.

d. When you uninstall the app, the data gets deleted.

4. Android Databases

In this, the data is stored as structured data in a private database. For that, it uses the Room persistence library. There are certain things about it that are:

a. It has structured data

b. To access the data use Room persistence library

c. No other application can access the data

d. On the uninstallation of the application, the data gets deleted too.

#android tutorials #android storage #external storage in android #internal storage in android #storage in android