I'm trying to use basic localStorage methods. They work perfectly fine in HTML, but do not work in a stand-alone Javascript file.
HTML Code (Works):
<!DOCTYPE html>
<html>
<head>
<title>Test Javascript</title>
<meta name="description" content="Our first page">
<meta name="keywords" content="html tutorial template">
<script>
document.addEventListener("DOMContentLoaded", function(event) {
localStorage.setItem("Name", "Jeff");
console.log(localStorage.getItem("Name"));
});
</script>
</head>
<body>
Content goes here.
</body>
</html>
JS Code (Doesn't Work):
document.addEventListener("DOMContentLoaded", function(event) {
localStorage.setItem("Name", "Jeff");
console.log(localStorage.getItem("Name"));
});
or
document.addEventListener("load", function() {
localStorage.setItem("Name", "Jeff");
console.log(localStorage.getItem("Name"));
});
or
document.addEventListener("DOMContentLoaded", function() {
localStorage.setItem("Name", "Jeff");
console.log(localStorage.getItem("Name"));
}, false);
or
window.onload = function() {
localStorage.setItem("Name", "Jeff");
console.log(localStorage.getItem("Name"));
}
Here are the solutions I have tried:
Using document.addEventListener("DOMContentLoaded", function(event) {});
Using document.addEventListener("load", function() {});
Using document.addEventListener("DOMContentLoaded", function() {}, false);
Using window.onload = function() {}
Using window.onload = function() {} (again)
Using window.onload = function() {} (again...)
I still end up with the same result when running the js file: Nothing happens in localStorage, and I see nothing in the console.
I'm not sure where to go from here, any help would be appreciated.