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
3 Answers
Reset to default 3Can 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.