Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser capabilities - check if object exists in ClojureScript

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 ?

like image 691
nha Avatar asked Feb 27 '26 15:02

nha


1 Answers

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.

like image 181
ClojureMostly Avatar answered Mar 01 '26 04:03

ClojureMostly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!