[Golang] Test if Item Exist in Web Storage by GopherJS


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:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]Search undefined Results in GopherJS repo · GitHub
[3]GitHub - go-humble/locstor: localstorage bindings for go and gopherjs
[4]Google Search: localstorage
[5]Storage - Web APIs | MDN
[6]Using the Web Storage API - Web APIs | MDN