JavaScript – Is WebStorage/DomStorage Enabled?

Definition

First what is Web Storage/Document Object Model Storage (DOM)?

https://en.wikipedia.org/wiki/Web_storage
Web storage and DOM storage (Document Object Model storage) are web application software methods and protocols used for storing data in a web browser. Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. There are two main web storage types: local storage and session storage, behaving similarly to persistent cookies and session cookies respectively.

Background

So for now I have a fairly consistent feedback loop; and that is to review WordPress Stats and see what posts people are viewing; especially when it comes from community forums.

This morning here is one originating page.

localStorage not working in Edge?

The ‘Stack Overflow’ participant said one can use the JavaScript statement below to determine whether DomStorage is enabled.


if('undefined'==typeOf(window.Storage){alert('Storage turned off...');}

Trial

So I thought to myself we have a potential nice addition to our now empty JavaScript toolbox, let us go try it out.

Steps

  1. Launched Notepad++
    • Posted Code
    • Saved Code
  2. Launched IE
    • Turned off DomStorage
    • Loaded Code through File Manager
    • Nothing

BTW, here is what the code looks like:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	
		<script type="text/javascript">

			function validateWindowsStorage()
			{
				if('undefined'==typeOf(window.Storage){alert('Storage turned off...');}
			}
			
			window.onload = validateWindowsStorage;
			
		</script>	
		
    </head>
    <body>
    
    </body>
</html>

 

Enable Debug

I.E.

In I.E, make sure script debugging is not disabled
EnabledDebug

Lint

Unfortunately, I.E. is not showing any error, and so thought of Lint.

Tools

Here are some good online JavaScript  Lint Tools

  1. JavaScriptLint.com

Pasted the code unto JavaScriptLint.com.

Pasted Code

code

 

Results

Results

 

typeof is undefined

Code

Corrected the code to now read:

 
<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	
		<script type="text/javascript">

			function validateWindowsStorage()
			{
				if('undefined'==typeOf(window.Storage)){alert('Storage turned off...');}
			}
			
			window.onload = validateWindowsStorage;
			
		</script>	
		
    </head>
    <body>
    
    </body>
</html>


 

 

Error

Text

Line: 11
Error: 'typeOf' is undefined

Image

typeofIsUndefined

 

Working Code

Here is a working code courtesy of:

Mathias Bynens
LocalStorage Pattern

Code


<!DOCTYPE html>
<html>
<head>
<title>Validate Local Storage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript">


	function isEmpty(obj) 
	{

		for(var prop in obj) 
		{
			if(obj.hasOwnProperty(prop))
			{
				return false;
			}
		}	
		return (true);
    }


	function validateStorage()
	{	

		var showSuccess = false;
		var showError = true;		
		var item = "item";
		var value = "value";
		var localStorageIsEmpty = false;
		var skipShortCircuit = true;
		
		if (skipShortCircuit === false)
		{
			localStorageIsEmpty = isEmpty(localStorage);
			
			if (localStorageIsEmpty === true)
			{
				if (showError)
				{
					alert
					(
						"Local Storage is not supported or is disabled"
					);		
				}	
				
				return (false);
			}

		} //skip short circuit
		
		try 
		{
			localStorage.setItem(item, value);
			localStorage.removeItem(item);
			
			if (showSuccess)
			{
				alert
				(
					"Local Storage enabled"
				);					
			}	
			return true;
		} 
		catch(ex) 
		{
			if (showError)
			{
			
				var errHeader = "Local Storage not enabled\n" 

				var vDebug = ""; 
				for (var prop in ex) 
				{  
				   vDebug +=   
							   "property: "+ prop+ " \n"
							 + "value: "+ ex[prop]
							 + "\n\n"; 
				} 
			
				alert
				(
					errHeader 
					  + "\n" 
					  + vDebug 
					
				);
			}
			return false;
		}

	}

	window.onload = validateStorage;

</script>	


</head>
<body>

</body>
</html>

Lint

Lint – Warnings

There are some warnings…

warnings

But, no errors

Try Code

We are set to display error, when Local Storage is disabled.

Here are what things look like on familiar browsers.

Internet Explorer

IE

Chrome

Chrome

If the short-circuit part of our test is enabled and thus we skip actually trying to place data in the Storage, we will only get a very soft hint:

Alert

 

Firefox

firefox

 

Incomplete Codes

There are some sample codes from very popular web sites that are a bit inconclusive.

W3Schools

Screen Shot

W3Schools

Code


<!DOCTYPE html>
<html>
<head>
<title>Validate Local Storage Using typeof</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script type="text/javascript">

	function validateStorageUsingTypeof()
	{	


		if(typeof(Storage) !== "undefined") {
		// Code for localStorage/sessionStorage.
		     alert("Good! Web Storage support..");
		} else {
		  alert("Sorry! No Web Storage support..");
		}	
	}	
	
	window.onload = validateStorageUsingTypeof

</script>


Quick Explanation

  1. I think the code checks for Browser supportability
  2. But, not as to whether the feature has been disabled by the user

 

Browser Supportability

Both Internet Explorer and Firefox have explicit tooling for enabling and disabling DOM Storage.

Unfortunately Chrome’s support is only available through the Cookie Interface.

Google Chrome Settings

ChromeSettings

Summary

Much gratitude to John Brinkman at Adobe for placing the code for exposing Exception Object properties.  That code is available at http://blogs.adobe.com/formfeed/2009/03/handling_javascript_exceptions.html.

To Adam Zerner on how to test JavaScript script objects for whether they are empty.  (link)

And, of course to the Belgian, Mathias Bynens.

Also, please note that though this is a JavaScript code, the code has to be sourced from a Web Server and not simply loaded through the File System.

 

References

Web Storage

  1. HTML5 Web Storage, Using localStorage and sessionStorage Objects by James Litten
    http://html5.litten.com/html5-web-storage-using-localstorage-and-sessionstorage-objects/

Browsers

Configuration

  1. How to enable DOM Storage
    https://sites.google.com/a/khanacademy.org/forge/for-developers/how-to-enable-dom-storage

 

Sample Code

  1. W3 Schools – HTML/5 – Web Storage
    http://www.w3schools.com/html/html5_webstorage.asp

JavaScript Type Detection

  1. Typeof
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
  2. JavaScript Tutorial – Type Detection
    http://javascript.info/tutorial/type-detection
  3. Angus Croll – Fixing the JavaScript typeof operator
    https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
  4. Determine the existence of a variable
    http://www.javascriptkit.com/javatutors/determinevar2.shtml

 

JavaScript Exception Handling

  1. Handling JavaScript exceptions
    http://blogs.adobe.com/formfeed/2009/03/handling_javascript_exceptions.html

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s