Today I Learned - Rocky Kev

TIL how to get the location of the user with the Geolocation API

POSTED ON:

TAGS:

You can get the user's location in the browser.

First, the user has to accept this. As it's a security request.

Second, you use the Geolocation API.


function getLocation() {
if (!navigator.geolocation) {
console.log('Geolocation API not supported by this browser.');
} else {
console.log('Checking location...');

//fire the geolocation with callback functions navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
}

// the two callbacks
function locationSuccess(position) {
console.log(position);
}

function locationError(position) {
console.error('Geolocation error!');
}

You can also set it to watch using the

Geolocation.watchPosition()

the MDN

via Nathan Pasko's How to Check a User's Location with JavaScript


Related TILs

Tagged:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.