[英]Uncaught (in promise) TypeError: localStorage.setItem is not a function
I want to create a project with localstorage, but when I save it with setItem
error show up like this:我想用 localstorage 创建一个项目,但是当我用setItem
保存它时,错误显示如下:
Uncaught (in promise) TypeError: localStorage.setItem is not a function未捕获(承诺)TypeError:localStorage.setItem 不是 function
This is my code:这是我的代码:
var dataPerson = {
name: "Jhon",
old: 20,
family: "Doe",
};
console.log(dataPerson);
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("data", JSON.stringify(dataPerson));
} else {
alert("Sorry, your browser does not support Web Storage...");
}
I use jQuery v3.4.1, Thank you我用的是jQuery v3.4.1,谢谢
Can you try invoking localStorage
from the window
object...您可以尝试从window
object 调用localStorage
...
window.localStorage.setItem("data", JSON.stringify(dataPerson));
This worked for me.这对我有用。
Check your code again if you've redefined the localStorage on somewhere else.如果您在其他地方重新定义了 localStorage,请再次检查您的代码。
The code is completely working.该代码完全有效。 https://stackblitz.com/edit/js-jpzvta?embed=1&file=index.js https://stackblitz.com/edit/js-jpzvta?embed=1&file=index.js
from https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage :来自https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage :
Exceptions例外情况
SecurityError The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). SecurityError 请求违反了策略决定,或者源不是有效的方案/主机/端口元组(例如,如果源使用文件:或数据:方案,就会发生这种情况)。 For example, the user may have their browser configured to deny permission to persist data for the specified origin.例如,用户可能将其浏览器配置为拒绝为指定来源保留数据的权限。
so you should envelope your code with a try-catch, that will solve your所以你应该用 try-catch 包裹你的代码,这将解决你的问题
Uncaught (in promise) TypeError: localStorage.setItem is not a function未捕获(承诺)TypeError:localStorage.setItem 不是 function
in https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API you have an example of it, and given your particular exception, I'd start by在https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API中,你有一个例子,考虑到你的特殊例外,我首先
Feature-detecting localStorage特征检测localStorage
To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.要能够使用localStorage,我们首先要验证它在当前浏览session中是否被支持和可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.