[英]localStorage is not working on google chrome
我使用瀏覽器localStorage
來存儲一個值,但是在使用谷歌瀏覽器時,當我們使用window.location.reload()
刷新頁面時, localStorage.value
被刷新。 例如
localStorage.value1=true
重新加載后,我沒有在 localStorage 中獲得這個 value1 對象。
相同的代碼適用於 mozila firefox,但不適用於 chrome。 使用 firefox 時,localstorage 值是持久的。
LocalStorage 僅支持字符串值,不支持布爾值或其他值。
存儲和檢索值的方法:
將價值存入
localStorage.setItem('value1', 'true');
從存儲中檢索值
var val1 = localStorage.getItem('value1');
// main.go
package main
import (
"encoding/json"
"fmt"
"log"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
// Article - Our struct for all articles
type Article struct {
Id string `json:"Id"`
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
var Articles []Article
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the HomePage!")
fmt.Println("Endpoint Hit: homePage")
}
func returnAllArticles(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint Hit: returnAllArticles")
json.NewEncoder(w).Encode(Articles)
}
func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
for _, article := range Articles {
if article.Id == key {
json.NewEncoder(w).Encode(article)
}
}
}
func createNewArticle(w http.ResponseWriter, r *http.Request) {
// get the body of our POST request
// unmarshal this into a new Article struct
// append this to our Articles array.
reqBody, _ := ioutil.ReadAll(r)
var article Article
json.Unmarshal(reqBody, &article)
// update our global Articles array to include
// our new Article
Articles = append(Articles, article)
json.NewEncoder(w).Encode(article)
}
func deleteArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
for index, article := range Articles {
if article.Id == id {
Articles = append(Articles[:index], Articles[index+1:]...)
}
}
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/articles", returnAllArticles)
myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")
myRouter.HandleFunc("/article/{id}", returnSingleArticle)
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
func main() {
Articles = []Article{
Article{Id: "1", Title: "Hello", Desc: "Article Description", Content: "Article Content"},
Article{Id: "2", Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
}
handleRequests()
}
嘗試一下
window.localStorage.setItem("value1", true);
var yourvar = window.localStorage.getItem("value1");
我剛剛解決了在頁面重新加載時沒有讀取本地存儲的問題,我有一個選擇:
if ('darkMode') === 'true') {
enableDarkMode();
}
它不起作用,重新加載時它是真的,但是enableDarkMode()
沒有調用自己。 所以我期待着一個答案,發現改變if選項中的一個語句實際上解決了我的問題,所以答案是: if (localStorage.getItem('darkMode') === 'true') { enableDarkMode() }
;
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.