我正在寻找有关如何在用户由于浏览器设置而禁用sessionStorage时如何防止Web表单损坏的建议。例如,当浏览器设置阻止第三方Cookie时,Chrome中出现以下错误:

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

我有两个问题:


当第三方Cookie被阻止时,该例外会破坏我的表单在Chrome上的功能。我希望用户仍然能够使用表单,而仅使用备用。
我的测试条件不起作用,因为它没有获取虚假的值,因此我无法显示消息。我想向用户提供有关如何更改设置的说明,以便他们可以根据需要获得完整的功能。有没有一种方法可以为DOMexception编写测试条件?


这是我正在测试的代码:

// 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"));
}

最佳答案

编辑-我先前的答案无法处理您的情况,因此将需要进行异常处理。

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

10-07 12:51
查看更多