3

What is the way to test if something exists in ClojureScript ? For instance, I am trying to access the browser geolocation API. In javascript, I would do a simple check like that :

// check for Geolocation support
if (navigator.geolocation) {
  console.log('Geolocation is supported!');
}
else {
  console.log('Geolocation is not supported for this Browser/OS version yet.');
}

But translating it to ClojureScript, I get an error :

(if (js/navigator.geolocation)  ;; Uncaught TypeError: navigator.geolocation is not a function
   (println "Geolocation is supported")
   (println "Geolocation is not supported"))

What is the proper way to check browser capabilities in ClojureScript ?

2 Answers 2

7

There is multiple options:

  1. exists?: http://dev.clojure.org/jira/browse/CLJS-495

Only exists in clojurescript and not clojure. If you look at the macro in core.cljc you'll see it's just a if( typeof ... !== 'undefined' ). Example use :

   (if (exists? js/navigator.geolocation)
      (println "Geolocation is supported"))
      (println "Geolocation is not supported"))
  1. (js-in "geolocation" js/window) which expands to "geolocation" in windows.

  2. (undefined? js/window.geolocation) which expands to void 0 === window.geolocation

IMO, the right one is js-in.

Sign up to request clarification or add additional context in comments.

1 Comment

I added an example use, as it was the first use of :require-macro for me. Hope that's ok, thanks.
1

For now, I am using :

(if (not (nil? js/navigator.geolocation))
    (println "Geolocation is supported")
    (println "Geolocation is not supported"))

Not sure if this idiomatic/cover all use cases, I would gladly accept another answer with a proper explanation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.