Check if an item exists (is populated) in web storage (localStorage or
sessionStorage) by GopherJS. Use js.Undefined in your if test.
In the beginning, I use the following code:
if js.Global.Get("localStorage").Call("getItem", "demoSetting") == js.Undefined {
// demoSetting not exist
}
But it did not work as expected. After trial and error, the correct way is:
if js.Global.Get("localStorage").Get("demoSetting") == js.Undefined {
// demoSetting not exist
}
You can try it by yourself on
GopherJS Playground.
package main
import (
"fmt"
"github.com/gopherjs/gopherjs/js"
)
func main() {
if js.Global.Get("localStorage").Get("demoSetting") == js.Undefined {
fmt.Println("demoSetting not in localStorage API")
}
if js.Global.Get("localStorage").Call("getItem", "demoSetting") == js.Undefined {
fmt.Println("demoSetting not in localStorage API")
}
}
References: