4

JavaScript undefined Check in Go

 3 years ago
source link: http://siongui.github.io/2017/12/30/js-undefined-test-in-go/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sometimes we need to check if something exists or not in JavaScript. For example, old browsers may not support localStorage API, so we need to check before we use. In this post, we will show you how to do undefined check in Go/GopherJS.

Test if It's Undefined

Use localStorage as example, we will check if it is undefined in the browser.

JavaScript

if (window.localStorage === undefined) {
  console.log("Your browser does not support localStorage API");
} else {
  console.log("Your browser supports localStorage API");
}

Open your console and you will know if your browser support it or not.

GopherJS

GopherJS provides js.Undefined Object for undefined test. The above code in Go/GopherJS is as follows:

import (
      "github.com/gopherjs/gopherjs/js"
)

if js.Global.Get("localStorage") == js.Undefined {
      println("Your browser does not support localStorage API")
} else {
      println("Your browser supports localStorage API")
}

Run Code on GopherJS Playground

The full code example of this post is on my GitHub.

For real-world example, see [3].


References:

[1][Golang] undefined Test in GopherJS

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

[4][GopherJS] null Test

[5][GopherJS] HTML Web History API Example


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK