Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript browser navigator permissions else section not triggering

Have a small javascript piece of code which calls navigator.geolocation.

I have an if statement, which works, to show the latitude and longitude if the user the user allows the call. However, the else section is not running.

If I run the code below I get prompted by the browser to allow; if I allow it then coordinates are shown. However, if I hit block instead nothing happens even though there is an else section.

<body>
  <br> <p id="ChangeSring">Test</p>
  <script>
  var x = document.getElementById("ChangeSring");
  if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(SavePosition);
  } else { 
      x.innerHTML = "Geolocation is not supported by this browser.";
      document.cookie = 'location=false;path=/form_handler';
  }

  function SavePosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
    document.cookie = 'location=true;path=/form_handler';
    document.cookie = 'latitude='+ position.coords.latitude +';path=/form_handler';
    document.cookie = 'longitude='+ position.coords.longitude +';path=/form_handler';
  }
  </script>

  <form action="/form_handler" _lpchecked="1">
    Enter value:
    <input type="text" name="SomeVar"><br>
    <input type="submit" value="search">
  </form>
</body>
like image 961
Francisco1844 Avatar asked Sep 09 '26 20:09

Francisco1844


1 Answers

You cannot use else to check for permissions.

The navigator method getCurrentPosition takes a success and error callbacks. The error callback will be called if permission is denied.

if (navigator.geolocation) { // this checks if navigator is supported at all
  navigator.geolocation.getCurrentPosition(console.log, () => {
    console.log('Permission denied')
  });
} else {
  console.log('Geolocation is not supported by this browser.');
}
like image 129
nem035 Avatar answered Sep 12 '26 09:09

nem035



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!