最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught (in promise) TypeError: localStorage.setItem is not a function - Stack Overflow

programmeradmin2浏览0评论

I want to create a project with localstorage, but when I save it with setItem error show up like this:

Uncaught (in promise) TypeError: localStorage.setItem is not a 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

I want to create a project with localstorage, but when I save it with setItem error show up like this:

Uncaught (in promise) TypeError: localStorage.setItem is not a 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

Share Improve this question asked Aug 20, 2020 at 8:46 Abed PutraAbed Putra 1,2152 gold badges21 silver badges40 bronze badges 1
  • From what scheme? file:// http://? In a private tab? What browser? Have you enabled some security settings preventing tracking/storage of cookies? Do you use an extension that could do this? – Kaiido Commented Aug 20, 2020 at 8:50
Add a ment  | 

3 Answers 3

Reset to default 3

Can you try invoking localStorage from the window object...

window.localStorage.setItem("data", JSON.stringify(dataPerson));

This worked for me.

Check your code again if you've redefined the localStorage on somewhere else.

The code is pletely working. https://stackblitz./edit/js-jpzvta?embed=1&file=index.js

from https://developer.mozilla/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). 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

Uncaught (in promise) TypeError: localStorage.setItem is not a function

in https://developer.mozilla/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

Feature-detecting localStorage

To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.

发布评论

评论列表(0)

  1. 暂无评论