admin管理员组

文章数量:1297077

I'm looking for suggestions for how to keep my web form from breaking when users have sessionStorage disabled due to browser settings. For example, I get the following error in Chrome when browser settings block 3rd party cookies:

Uncaught DOMException: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.

I have two problems:

  1. The exception breaks the functionality of my form on Chrome when 3rd party cookies are blocked. I would like the user to still be able to use the form and just use a fallback.

  2. My test condition isn't working because it isn't picking up a falsey value so I can't display a message. I would like to give the user instructions on how to change the settings so they can get full functionality if they want. Is there a way to write a test condition for a DOMexception?

Here is the code I'm testing with:

// Test if sessionStorage available
if(!sessionStorage) {
  alert("Sorry, your browser does not support session storage.");

} else {
  // Store data
  sessionStorage.setItem("name", "John Smith");

  // Retrieve data
  alert("Hi, " + sessionStorage.getItem("name"));
} 

I'm looking for suggestions for how to keep my web form from breaking when users have sessionStorage disabled due to browser settings. For example, I get the following error in Chrome when browser settings block 3rd party cookies:

Uncaught DOMException: Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.

I have two problems:

  1. The exception breaks the functionality of my form on Chrome when 3rd party cookies are blocked. I would like the user to still be able to use the form and just use a fallback.

  2. My test condition isn't working because it isn't picking up a falsey value so I can't display a message. I would like to give the user instructions on how to change the settings so they can get full functionality if they want. Is there a way to write a test condition for a DOMexception?

Here is the code I'm testing with:

// Test if sessionStorage available
if(!sessionStorage) {
  alert("Sorry, your browser does not support session storage.");

} else {
  // Store data
  sessionStorage.setItem("name", "John Smith");

  // Retrieve data
  alert("Hi, " + sessionStorage.getItem("name"));
} 
Share asked Sep 29, 2019 at 4:27 dumdum3000dumdum3000 3353 gold badges7 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Edit - My previous answer won't handle your scenario, hence exception handling will be required.

try {
    var storage = window.sessionStorage || {};  
} catch (e) {
    var storage = {};  
}

use try catch.

try {
  sessionStorage.setItem("name", "John Smith");
  alert('Hi, ' + sessionStorage.getItem("name"));
} catch(e) {
  console.log('Session Storage is disabled');
}

本文标签: javascriptWhat to do when sessionStorage access denied due to browser settingsStack Overflow