What steps should be taken to execute a function based on whether a user grants or denies access to their "Physical Location"?

The functionality of my app relies on jQuery mobile and geolocation services.

Once the app requests the user's location, a prompt appears in the (Chrome) browser:

Example.com is requesting to access your physical location [allow] [deny]

My objective is to:

  1. If the user selects "Allow", function 1 will be triggered (location data will be used by the app).
  2. If the user selects "Deny", function 2 will be triggered (an address form will be displayed).

Is there a way to attach a function to handle the event triggered when the user clicks either the "Allow" or "Deny" button?

Answer №1

When you use the getCurrentPosition function, it requires two different functions as arguments. The first one will be executed when permission is granted, while the second will be triggered if permission is denied!

To learn more, check out the documentation.

For a practical example, visit this JSFiddle demo.

navigator.geolocation.getCurrentPosition(function(position) {
    alert('Permission granted');
}, function() {
    alert('Permission denied');
});

Answer №2

Click here for Documentation

function managePermission() { navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
  displayStatus(result.state);
  geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
  displayStatus(result.state);
  geoBtn.style.display = 'none';
  navigator.geolocation.getCurrentPosition(showPosition,positionRejected,geoSettings);
} else if (result.state == 'denied') {
  displayStatus(result.state);
  geoBtn.style.display = 'inline';
}
result.onchange = function() {
  report(result.state);}});}function displayStatus(state) {
 console.log('Permission status: ' + state);}

Fingers crossed that it does the trick.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After using JSON.parse(), backslashes are still present

Recently Updated: Received server data: var receivedData = { "files":[ { "filename": "29f96b40-cca8-11e2-9f83-1561fd356a40.png", "cdnUri":"https://abc.s3.amazonaws.com/" ...

Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN const btt = document.querySelector('.btt'); btt.addEventListener('click', function(){ this.classList.toggle('anime'); }); Is there a way to achieve the desired effect with just one click? ...

Utilizing JQuery to Modify XML File Content

Looking to retrieve data from an XML file using jQuery and display it in a textbox? If you want changes made in the textbox to reflect back in the original XML file, there are ways to achieve this. Here is some code that can help: <html><head&g ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

Extending the declaration of JavaScript native methods is not possible when using TypeScript

When attempting to enhance the JS native String class by adding a new method, I encounter error TS2339. interface String { transl(): string; } String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'St ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

What is the best way to maintain a Tampermonkey script within Selenium?

I'm trying to execute a JavaScript script before the page loads, so I've placed it in Tampermonkey. However, the script doesn't persist after closing the driver. Whenever I run the code again, the saved script is no longer there. This code u ...

Is it possible to extract my current location from one website and then access another website based on that location?

I am currently experimenting with an HTML5 script that loads a globe requiring users to click on it to determine the location. Once a location is clicked, another site opens displaying a map of the chosen location. Here is an example of the site with the i ...

Stop touchCancel during scrollStart action

When using an Android device, a scroll event triggers a `touchcancel` event, which prevents the touch up event from being triggered after scrolling. To avoid the `touchcancel` event, I implement a `preventDefault` on `touchStart` within the scrolling div. ...

What is the best way to transfer a value to the database using a distinct module?

I have recently set up a basic express project and added a file named lib/userhandler.js in the main directory. //lib/userhandler.js exports.addUser = function(req, res){ // Accessing our internal database variable var db = req.db; // Retrieving ...

Utilizing Javascript and CSS for horizontal alignment from left to right

I have a JavaScript function that generates a list of store locations and creates a DIV beneath the map. Currently, the items are displayed top to bottom on the page. However, I would like to change the layout so that the items are shown as 3 in a row fro ...

Retrieve all items on the webpage using the pattern "_ followed by 10 random characters" through JavaScript

On my webpage, there is a table containing table rows in the following format: <tr id="_C15DKNWCSV">text</tr> I am attempting to scan the webpage and extract all table rows that have an id in the format: id="_(10 RANDOM CHARACTERS)" I want ...

AngularJS: Error message stating that '$scope is undefined'

Encountering '$scope is not defined' console errors in this AngularJS controller code: angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Au ...

What is the best way to separate one dropdown area from another dropdown area?

I have two dropdown menus where, when an option with the value "other" is clicked, it generates a text area just below the dropdown menu. Both sections are functioning correctly, but I had to create separate parent wrappers for each in order to do so. How ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

The most effective method for adding data to a <pre /> element is through VueJS

I have an electron app that executes a program and stores the output when data is received. My goal is to showcase the content of this output within an html pre element. One approach I can take is to create a variable and continuously add the output data ...

Comparing values inputted from JavaScript using PHP

I am passing values from PHP to a script. <img src=\"images/add.jpg\" onclick='add_program_user(".$value['id_program'].",".$value['min_age'].",".$value['max_age'].")' onmouseover=\"this.style.curso ...

Having trouble manipulating DOM elements in Node.js with JSDOM?

Feeling a bit lost here - I'm a newbie to Node JS and I'm attempting to manipulate a DOM element within index.js, my main Node.js file. After reading up on the jsdom module, which supposedly allows you to interact with HTML elements in Node, I t ...

Is there a way to get a Chrome extension to run automatically in the background?

I am looking to develop a custom chrome extension with a countdown timer functionality that automatically runs in the background. However, I am facing an issue where my background.js file is unable to access the popup.html file. How can I execute scripts i ...