hotwired / hotwire-native-android

Hotwire Native for Android
MIT License
39 stars 5 forks source link

Location access via JavaScript #28

Open joemasilotti opened 7 months ago

joemasilotti commented 7 months ago

This PR configures the web view and WebFragment to access the user's location via JavaScript.

The first time the user's location is accessed the following appears:

Xnapper-2024-04-05-11 13 05

If accepted, WebFragment reloads the page. When the location is accessed a second time the following appears:

Xnapper-2024-04-05-11 13 25

If the permissions in the manifest file are commented out the following appears when accessing the user's location:

Xnapper-2024-04-05-11 13 15

Note that this only works against HTTPS websites, so you will need to tunnel via ngrok for Chrome to expose the user's location.

The following Stimulus controller was used to test the location access:

// public/javascript/controllers/location_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  request(event) {
    event.preventDefault()

    navigator.geolocation.getCurrentPosition(
      this.success.bind(this),
      this.failure.bind(this),
      {enableHighAccuracy: true}
    )
  }

  success(position) {
    const {latitude, longitude} = position.coords
    alert(`${latitude}, ${longitude}`)
  }

  failure(error) {
    alert(`Could not get your location: ${error.message}.`)
  }
}