How to detect if browser supports HTML5 Local Storage - javascript

The following code alerts ls exist in IE7:
if(window.localStorage) {
alert('ls exists');
} else {
alert('ls does not exist');
}
IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?
Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.

You don't have to use modernizr, but you can use their method to detect if localStorage is supported
modernizr at github
test for localStorage
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('localstorage', function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
});
updated with current source code

if(typeof Storage !== "undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}

This function works fine:
function supports_html5_storage(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
Source: www.diveintohtml5.info

Also I don't want to use Modernizr since I am using only a few HTML5
features and loading a large script isn't worth it just to detect
support for those few things.
To reduce Modernizr file size customize the file at http://modernizr.com/download/ to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.

Try window.localStorage!==undefined:
if(window.localStorage!==undefined){
//Do something
}else{
alert('Your browser is outdated!');
}
You can also use typeof window.localStorage!=="undefined", but the statement above already does it

I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.
If you use jQuery, you can do:
var _supportsLocalStorage = !!window.localStorage
&& $.isFunction(localStorage.getItem)
&& $.isFunction(localStorage.setItem)
&& $.isFunction(localStorage.removeItem);
Or, with pure Vanilla JavaScript:
var _supportsLocalStorage = !!window.localStorage
&& typeof localStorage.getItem === 'function'
&& typeof localStorage.setItem === 'function'
&& typeof localStorage.removeItem === 'function';
Then, you would simply do an IF to test the support:
if (_supportsLocalStorage) {
console.log('ls is supported');
alert('ls is supported');
}
So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.

Try catch will do the job :
try{
localStorage.setItem("name",name.value);
localStorage.setItem("post",post.value);
}
catch(e){
alert(e.message);
}

Try:
if(typeof window.localStorage != 'undefined') {
}

if (window.localStorage){
alert('localStorage is supported');
window.localStorage.setItem("whatever", "string value");
}

Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
function script(){
if(ls){
alert('Yes');
} else {
alert('No');
}
}
<button onclick="script()">Local Storage Support?</button>

I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.
Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.
So without further ado here is my code:
/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */
if (typeof isSessStorageAllowed !== 'function')
{
function isSessStorageAllowed()
{
if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
var ss_test_val = 'ss_test_val_' + String(cur_tm);
sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));
if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
{
return true;
}
else
{
return false;
};
sessionStorage.removeItem(ss_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'session storage' support. [END] */
/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */
if (typeof isLclStorageAllowed !== 'function')
{
function isLclStorageAllowed()
{
if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
var ls_test_val = 'ls_test_val_' + String(cur_tm);
localStorage.setItem(ls_test_itm_key, String(ls_test_val));
if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
{
return true;
}
else
{
return false;
};
localStorage.removeItem(ls_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'local storage' support. [END] */
/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */
/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */
if (typeof isWebStorageAllowed !== 'function')
{
function isWebStorageAllowed()
{
if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
{
return true;
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'web storage' support. [END] */

Related

Unexpected token operator «=», expected punc «,»

i am getting the following error
Parse error: Unexpected token operator «=», expected punc «,» Line
159, column 26
This is my code
function fitBounds(type="all", shape=null) {
var bounds = new google.maps.LatLngBounds();
if ( type == "all" ){
if ((circles.length > 0) | (polygons.length > 0)){
$.each(circles, function(index, circle){
bounds.union(circle.getBounds());
});
$.each(polygons, function(index, polygon){
polygon.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
});
}
}
else if ( (type == "single") && (shape != null) ) {
if (shape.type == google.maps.drawing.OverlayType.MARKER) {
marker_index = markers.indexOf(shape);
bounds.union(circles[marker_index].getBounds());
}
else {
shape.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
}
}
if (bounds.isEmpty() != true)
{
map.fitBounds(bounds);
}
}
You are trying to use Default parameters, which are a bleeding edge feature of JavaScript with limited support.
JS Lint rejects them unless you turn on the ES6 option.
#Quentin is exactly right: You need the es6 option.
There's lots more that fails JSLint, however, particularly your use of ==, which is a "coercing operator" -- check JSLint on equality -- and the bitwise option in the jslint section (there's no link directly to jslint directives, I don't think, so I linked just above it). As #AxelH suggests, there's likely more you really want to ask us. ;^)
Here's a version that lints on JSLint.com as it stands today. Note the /*jslint directive line at the top that includes the es6 tag:
/*jslint es6, white, browser */
/*global google, $ */
// These weren't declared, so I'm assuming they're
// within scope in your snippet's context.
// I put others that felt like globals (google, $)
// into globals, above.
var marker_index;
var markers;
var circles;
var polygons;
var map;
function fitBounds(type="all", shape=null) {
var bounds = new google.maps.LatLngBounds();
if ( type === "all" ){
// not sure why you're using bitwise `|` here.
// I think this'll be equivalent, though you should
// be able to set `bitwise` as an option if it's not.
// Still, you're evaluating to booleans, so `|` doesn't
// seem appropriate here.
if ((circles.length > 0) || (polygons.length > 0)){
$.each(circles, function(ignore, circle){
bounds.union(circle.getBounds());
});
$.each(polygons, function(ignore, polygon){
polygon.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
});
}
}
else if ( (type === "single") && (shape !== null) ) {
if (shape.type === google.maps.drawing.OverlayType.MARKER) {
marker_index = markers.indexOf(shape);
bounds.union(circles[marker_index].getBounds());
}
else {
shape.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
}
}
if (!bounds.isEmpty())
{
map.fitBounds(bounds);
}
}
#Quentin is right with his answer. You get syntax error due to reasons that he mentioned. What I can add to it is that you might try to drop EC6 syntax, and rewrite your function to old good JS.
// change from
function fitBounds(type="all", shape=null)
// change to
function fitBounds(type="all", shape)
A workaround to this issue could be this:
function fitBounds(type, shape_aux) {
var bounds = new google.maps.LatLngBounds();
if(typeof type === "undefined") {
type = "all";
}
if(typeof shape_aux !== undefined) {
shape = shape_aux;
} else {
shape = null;
}
if ( type == "all" ){
if ((circles.length > 0) | (polygons.length > 0)){
$.each(circles, function(index, circle){
bounds.union(circle.getBounds());
});
$.each(polygons, function(index, polygon){
polygon.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
});
}
}
else if ( (type == "single") && (shape != null) ) {
if (shape.type == google.maps.drawing.OverlayType.MARKER) {
marker_index = markers.indexOf(shape);
bounds.union(circles[marker_index].getBounds());
}
else {
shape.getPath().getArray().forEach(function(latLng){
bounds.extend(latLng);
});
}
}
if (bounds.isEmpty() != true)
{
map.fitBounds(bounds);
}
}

JavaScript files.length not working in ie9 need alternative approach

I have the following JavaScript function which is failing in internet explorer 9 on the line which declares the variable filesattached.
function VesselDetails() {
insurancestart = $('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').val();
insuranceend = $('#ctl00_ContentPlaceHolder1_datetimepickerinsend').val();
filesattached = $("input:File")[0].files.length;
//set up JS objects
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').datetimepicker({ format: 'd/m/Y H:i a' });
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').datetimepicker({ format: 'd/m/Y H:i a' });
//subscribe to change events
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').change(function () {
insurancestart = $("ctl00_ContentPlaceHolder1_datetimepickerinsstart").val();
});
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').change(function () {
insuranceend = $("ctl00_ContentPlaceHolder1_datetimepickerinsend").val();
});
$("input:File").change(function () {
filesattached = $("input:File")[0].files.length;
});
ins_client();
}
The ins_client method looks like this:
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
This all works perfectly well in chrome and ie 11 but the length property is returning an undefined for ie 9. I am using the length because I only want the page to be valid for a new vessel request once a document has been submitted, is there another way of doing this which will work in ie 9 onwards and chrome, apologies if this has already been answered elsewhere but I cannot find a workaround anywhere that enables this to continue working in the same way but in ie9 onwards and chrome.
I replaced:
filesattached = $("input:File")[0].files.length;
With:
var areFilesAttached = document.getElementById('ctl00_ContentPlaceHolder1_fuAttachment').value ? true : false;
Within the VesselDetails function.
Then replaced the if statement within ins_client with the following:
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && areFilesAttached == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
This was an alternative approach which enabled me to check whether or not a file had been provided without using the files.length property which is not compatible with IE9.
I'm afraid this can't be achieved, IE9 does not support HTML5 File API and therefore it returns undefined value for files property.
Take a look at FILE API

error in javascript or no clue

I got the following javascript code.
And Basically, it works on FF, and IE with developer Tools.
$(function(){
console.log("it is ok");
var mybutton="";
alert("ready1");
$('button[name="delorder"]').click(function(){
console.log($(this).val()+"hay i got a click");
mybutton=$(this).val();
alert("a click1");
$.ajax({
type:'POST',
url:'deleteorderitem.php',
data:mybutton,
success:function(result){
if((result.indexOf("t") < 3) && (result.indexOf("t") >= 0)){
$('#orderresult').html(result);
console.log("i am 3 ");
console.log("index of t is "+result.indexOf("t"));
}else{
console.log("i am 4");
console.log("index of t is "+result.indexOf("t"));
$('#divOrderButton').hide();
$('#orderresult').html("");
$('#divNoinfo').html("There is no record to display at the moment.");
$('#divNoinfo').show();
$('#divOrder').hide();
}
}
});
});
});
</script>
But , it does NOT WORK on IE (without developer tools).
so, any advice will be appreciated.
Thanks
It is mostly because of
console.log()
Windows IE8 and below has no console object when the Developer tools is not open.
Either comment out the lines that says console. Or create the console object beforehand.
Try this ... Not sure if this is the correct way around..
var alertFallback = true;
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
if (alertFallback) {
console.log = function(msg) {
alert(msg);
};
} else {
console.log = function() {};
}
}
This will create the console object if it is not present.
If you're saying it doesn't work without developer tools open, (unless I'm mistaken) it is because you have all those console.log's and that must be what's blowing it up.
Try something like this at the very top of a master JS file to prevent that in IE.
if (typeof (console) === 'undefined' || !console) {
window.console = {};
window.console.log = function () { return; };
}
I use this function to write logs for cross browser console log :
/**
*Log into the console if defined
*/
function log(msg)
{
if (typeof console != "undefined") {
console.log(msg);
}
}

IndexedDB getAll in non-Firefox browsers

I am aware that IDBObjectStore.getAll is not part of the IndexedDB standard and that it might never be. But it is implemented in FireFox, and it makes your code prettier if you do have to retrieve a lot of objects from the database.
Would it be possible to make some kind of polyfill or something to allow getAll to work in other browsers that support IndexedDB? The actual functionality of getAll is simple, but I don't know how to deal with the asynchronous nature of IndexedDB in the context of replicating its precise syntax in non-Firefox browsers.
I made a GitHub repo for a shim to support getAll in other browsers, which seems to work well enough in Chrome. The code is repeated below for posterity:
(function () {
"use strict";
var Event, getAll, IDBIndex, IDBObjectStore, IDBRequest;
IDBObjectStore = window.IDBObjectStore || window.webkitIDBObjectStore || window.mozIDBObjectStore || window.msIDBObjectStore;
IDBIndex = window.IDBIndex || window.webkitIDBIndex || window.mozIDBIndex || window.msIDBIndex;
if (typeof IDBObjectStore.prototype.getAll !== "undefined" && typeof IDBIndex.prototype.getAll !== "undefined") {
return;
}
// https://github.com/axemclion/IndexedDBShim/blob/gh-pages/src/IDBRequest.js
IDBRequest = function () {
this.onsuccess = null;
this.readyState = "pending";
};
// https://github.com/axemclion/IndexedDBShim/blob/gh-pages/src/Event.js
Event = function (type, debug) {
return {
"type": type,
debug: debug,
bubbles: false,
cancelable: false,
eventPhase: 0,
timeStamp: new Date()
};
};
getAll = function (key) {
var request, result;
key = typeof key !== "undefined" ? key : null;
request = new IDBRequest();
result = [];
// this is either an IDBObjectStore or an IDBIndex, depending on the context.
this.openCursor(key).onsuccess = function (event) {
var cursor, e, target;
cursor = event.target.result;
if (cursor) {
result.push(cursor.value);
cursor.continue();
} else {
if (typeof request.onsuccess === "function") {
e = new Event("success");
e.target = {
readyState: "done",
result: result
};
request.onsuccess(e);
}
}
};
return request;
};
if (typeof IDBObjectStore.prototype.getAll === "undefined") {
IDBObjectStore.prototype.getAll = getAll;
}
if (typeof IDBIndex.prototype.getAll === "undefined") {
IDBIndex.prototype.getAll = getAll;
}
}());

determine whether Web Storage is supported or not

I need to verify that Web Storage API is supported and available (it may be disabled due to security issues).
So, I thought it would suffice to check whether the type sessionStorage or localStorage is defined or not:
if (typeof sessionStorage != 'undefined')
{
alert('sessionStorage available');
}
else
{
alert('sessionStorage not available');
}
However, I was wondering if it could be possible that the type exists, but I wouldn't been able to use the Web Storage API anyway.
Remarks:
I know Firefox will throw a security error if cookies are disabled and sessionStorage or localStorage are accessed.
Why don't you use the Modernizr library to detect if local storage is supported or not? Any differences between browers will be taken care of for you, you can then just use code like this:
if (Modernizr.localstorage) {
// browser supports local storage
} else {
// browser doesn't support local storage
}
I think you're on the right track with your original code, no need to make this too fancy.
Using the KISS principle with no additional dependencies in your code:
var storageEnabled = function() {
try {
sessionStorage.setItem('test-key','test-value');
if (sessionStorage.getItem('test-key') == 'test-value'){
return true;
}
} catch (e) {};
return false;
};
alert(storageEnabled() ? 'sessionStorage available' : 'sessionStorage not available');
try{
ssSupport = Object.prototype.toString.call( sessionStorage ) === "[object Storage]";
}
catch(e){
ssSupport = false;
}
So, because Modernizr.localstorage respectively Modernizr.sessionstorage will return true while Firefox might be used with disabled Cookies (which will lead into an security error) or any other proprietary (unexpected) behavior could occur: I've written my own webStorageEnabled function which seems to work very well.
function cookiesEnabled()
{
// generate a cookie to probe cookie access
document.cookie = '__cookieprobe=0;path=/';
return document.cookie.indexOf('__cookieprobe') != -1;
}
function webStorageEnabled()
{
if (typeof webStorageEnabled.value == 'undefined')
{
try
{
localStorage.setItem('__webstorageprobe', '');
localStorage.removeItem('__webstorageprobe');
webStorageEnabled.value = true;
}
catch (e) {
webStorageEnabled.value = false;
}
}
return webStorageEnabled.value;
}
// conditional
var storage = new function()
{
if (webStorageEnabled())
{
return {
local: localStorage,
session: sessionStorage
};
}
else
{
return {
local: cookiesEnabled() ? function()
{
// use cookies here
}() : null,
session: function()
{
var data = {};
return {
clear: function () {
data = {};
},
getItem: function(key) {
return data[key] || null;
},
key: function(i)
{
var index = 0;
for (var value in data)
{
if (index == i)
return value;
++index;
}
},
removeItem: function(key) {
delete data[key];
},
setItem: function(key, value) {
data[key] = value + '';
}
};
}()
};
}
}
Hope this will be useful for someone too.
My version (because IE 9 running in IE 8 more on an intranet site is broken).
if (typeof (Storage) != "undefined" && !!sessionStorage.getItem) {
}
a longer version that adds setObject to allow storing objects:
var sstorage;
if (typeof (Storage) != "undefined" && !!sessionStorage.getItem) {
Storage.prototype.setObject = function (key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function (key) {
return JSON.parse(this.getItem(key));
};
if (typeof sessionStorage.setObject == "function") {
sstorage = sessionStorage;
}
else {
setupOldBrowser();
}
}
else {
setupOldBrowser();
}
function setupOldBrowser() {
sstorage = {};
sstorage.setObject = function (key, value) {
this[key] = JSON.stringify(value);
};
sstorage.getObject = function (key) {
if (typeof this[key] == 'string') {
return JSON.parse(this[key]);
}
else {
return null;
}
};
sstorage.removeItem = function (key) {
delete this[key];
};
}
Here's what I do to use session storage if available if it's not, use cookies..
var setCookie;
var getCookie;
var sessionStorageSupported = 'sessionStorage' in window
&& window['sessionStorage'] !== null;
if (sessionStorageSupported) {
setCookie = function (cookieName, value) {
window.sessionStorage.setItem(cookieName, value);
return value; //you can introduce try-catch here if required
};
getCookie = function (cookieName) {
return window.sessionStorage.getItem(cookieName);
};
}
else {
setCookie = function (cookieName, value) {
$.cookie(cookieName, value);
return value; // null if key not present
};
getCookie = function(cookieName) {
console.log("using cookies");
return $.cookie(cookieName);
};
}

Categories

Resources