Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using geolocation.getCurrentPosition while testing on local network

I am trying to access my phone's geolocation via navigator.geolocation.getCurrentPosition by connecting to a website hosted on a local machine via local IPv4 address. Problem is, when running the code from my phone I get the error "Origin does not have permission to use Geolocation service". After researching, I believe my phone is blocking that browser method because I am not hitting my local website over HTTPS or localhost.

Does anyone know of a way for me to test this locally? Do I have to publish my in-development code to a web server with HTTPS just to test this?

Any help would be very appreciated. Thanks in advance!

like image 625
Darryl Huffman Avatar asked Oct 15 '25 10:10

Darryl Huffman


2 Answers

if you are using chrome browser on your phone which is recommended. Then you could head over to

chrome://flags

and search for these 2 options and Enable them.

Allow invalid certificates for resources loaded from localhost.

and

Insecure origins treated as secure

like image 67
sourabhR4ikwar Avatar answered Oct 18 '25 01:10

sourabhR4ikwar


You can easily run a local HTTPS server using http-server NPM package. You just generate your own certificate using openssl in the same directory with your site using something like this:

openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

and it will work starting the server by executing:

http-server -S -C cert.pem -o -p 80

inside the directory with your local website. Take care of the filenames of the key and the certifacate because http-server default key filename is key.pem but of course you can change that using the -K <filename> parameter.

You can even use that certificate to other local servers (Apache, Express, Nginx, etc.) to serve the site with HTTPS using that cert. The site will get flagged as unsecure by Chrome because you'll have a self-signed certificate, but that does not affect the usage of the Geolocation API and you should be able to test it out. And as you have found, you can even trust that self-signed certificate and add it to browsers like Chrome ("create a trusted self-signed SSL cert for localhost").

Also check if you have any other resources that are being served over single HTTP in that page because there will be issues if there are. You should create a simple page just containing the geolocation.getCurrentPosition code so to test it out.

like image 36
Christos Lytras Avatar answered Oct 17 '25 23:10

Christos Lytras



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!