Rails 5: Access to geolocation was blocked over insecure connection to http://localhost:3000

Viewed 9230

I'm using html5 geolocation for my rails app, but when I click on the try it button the following error appears inside the safari browser console under the show web inspector console :

getLocation — localhost:83[blocked] Access to geolocation was blocked over insecure connection to http://localhost:3000.

and here is the code:

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
    var x = document.getElementById("demo");

    function getLocation() {
        if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    function showPosition(position) {
        x.innerHTML = "Latitude: " + position.coords.latitude +
            "<br>Longitude: " + position.coords.longitude;
    }
</script>
1 Answers

Safari (unlike Chrome and Firefox) does not allow access to geolocation over the HTTP protocol - only HTTPS. Even for localhost. Thanks a lot Apple.

The solution is to either use another browser in development or serve Rails over HTTPS. You can do that by generating a self-signed certificate and setting up the Rails development server (Webrick or Puma) to serve over HTTPS.

Rails 5 defaults to Puma, while earlier versions used Webrick.

The exact approach varies depending on your OS and which server is in use.

Related