The .NET Core web page is refreshing as expected with the meta "Refresh" tag, but I would like to separate certain JavaScript functions to prevent them from causing

Working on a project in .NET Core, I have set up a page to reload every 1-5 seconds using the meta http="Refresh" tag, which is functioning perfectly:

<meta http-equiv="Refresh" content="1" />

However, I want to separate out a piece of JavaScript code (prompting users for geolocation permission) like this:

navigator.geolocation.getCurrentPosition(position => {
const {latitude, longitude} = position.coords;
// Display map centered at latitude / longitude.
});

This section sits in the site.js file. Is there a way to prevent this code from executing during the automatic refresh, so that geolocation is only requested once when the page loads initially?

Thank you and hope this explanation makes sense!

Answer №1

-> make changes to your code :-

document.addEventListener('DOMContentLoaded', function() {
 
    navigator.permissions.query({name:'geolocation'}).then(permissionStatus => {
        if (permissionStatus.state === 'granted') {
            // Geolocation permission already granted, proceed to get current position
            navigator.geolocation.getCurrentPosition(position => {
                const {latitude, longitude} = position.coords;
              
            });
        } else {
            // Geolocation permission not granted, prompt the user for permission
            navigator.geolocation.requestPermission().then(permissionResult => {
                if (permissionResult === 'granted') {
                
                    navigator.geolocation.getCurrentPosition(position => {
                        const {latitude, longitude} = position.coords;
                  
                    });
                } else {
                    // User denied geolocation permission
                    console.log('Geolocation permission denied.');
                }
            }).catch(error => {
                console.error('Error requesting geolocation permission:', error);
            });
        }
    }).catch(error => {
        console.error('Error querying geolocation permission:', error);
    });
});

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

Verify if the username is already in use

Is it possible to validate the existence of a username while the user is entering it in a textbox or immediately after they finish typing? Should I use Jquery or Ajax for this task? Does anyone have any examples demonstrating how this can be done? ...

Enhancing an options tag with Dojo Framework

I am experiencing difficulties updating the label of a selected option in a Dojo-created select field, despite having a form to 'rename' the selected option. Various methods have been attempted: var selectDropdown = registry.byId("stateSelect") ...

Issues with AJAX Load functionality

As a beginner in jQuery, I am experimenting with an AJAX load function. However, I am encountering difficulties in making it work. Despite trying different approaches and file formats (.php, etc.), I ended up using the first method I attempted. My goal is ...

Converting a three.js scene into SVG or alternative vector format for export

Can an SVG- or other vector-formatted image be exported from a scene rendered using three.js's WebGLRenderer? What about from a scene derived from CanvasRenderer? If not, how can one set up SVGRenderer with three.js? Creating a new THREE.SVGRenderer( ...

Clicking a button in Angular JS to refresh a specific ID element

Just diving into AngularJS for my mobile web app development. I have different id divs for each view, as that's how AngularJS operates with one HTML page. My goal is to use specific javascript for each id page, as they need to retrieve JSON data objec ...

Javascript/AJAX functions properly on the homepage, but encounters issues on other pages

For a client, I have recently created 4 websites using Wordpress. Each site includes a sidebar with a script that utilizes the Google Maps API to estimate taxi fares. Strangely, the script works perfectly on the home page of each site, but fails to funct ...

What could be causing this empty Ajax ResponseText?

$("b_xml").onclick=function(){ new Ajax.Request("books.php", { method:"GET", parameters: {category:getCheckedRadio(document.getElementsByName("category"))}, onSuccess: showBooks_JSON, onFailure: ajaxF ...

Retrieving data from the array properties in a JSON object

I am facing a challenge with an array of elements, each element is quite complex as it contains nested arrays as properties. My goal is to extract specific attributes from these elements, but I have been struggling to achieve this using the forEach functio ...

Having trouble retrieving the accurate count of buttons with a particular class identifier

I have a task where I need to count the number of buttons within a dynamically created div using JavaScript. The buttons are added from a separate JS file and when I view the code in the browser's inspection tool, everything appears to be correct. How ...

Using " " to split a name into two lines is not being recognized

My issue involves the display of tab names in two lines within multiple tabs. You can view the demonstration here. I attempted to use the \n character while setting the tab name but it was not recognized. Any suggestions on how to achieve this? Here ...

Unlock the secrets of creating an interactive chat room effortlessly by harnessing the power of J

In search of implementing a unique chat room using PHP and JavaScript (Jquery) offering group chat as well as private chat functionalities. The challenge lies in finding a way to continuously update the interface seamlessly, while also displaying 'X ...

Using PHP to make an Ajax call that takes users to an action page when they submit a form

I'm struggling with an ajax call in my PHP code that keeps navigating to the action page instead of staying on the same page and only updating a specific part. Can anyone point out what I might be doing wrong here? <form method="post" id="holderSa ...

Hiding Div with JavaScript (Quick and Easy)

Hey there, I'm looking to make regStart and regPage alternate visibility based on a click event. I'm still getting the hang of JavaScript so any simple answers would be appreciated. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/x ...

Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label. Check out this JSBin function I created to map the array, but I'm unsure ...

Looking for the time trigger feature in jQuery using typeahead search?

Is there a way to trigger an event every 3 seconds in Laravel Vue.js? I am currently using jQuery in my script. The issue is that when I type something in the search input field, the event is triggered after each character I type. What I want is for the ev ...

Dynamic item addition feature activated by button on contact form

I am looking to create a form that includes the standard name, phone, email fields as well as a dropdown for selecting products and a text box for inputting quantity. The unique aspect is allowing users to add multiple products (dropdown and quantity textb ...

Excessive delay in executing Javascript loops

While developing an EMI calculator for a hybrid mobile app, I encountered a performance issue. The execution within one of the loops takes too long, resulting in the page becoming unresponsive. Here is my code snippet: var EMICalculator = { basicEMI: fun ...

Dynamic Formatting with Vue JS: Enhancing Phone Number Input

I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3? ...

Adjust the height of a div based on the font size and number of lines

I'm trying to create a function that automatically sets the height of a div by counting lines. I managed to get it partially working, but then it stopped. Can someone please help me with this? function set_height() { var div_obj=document.getEleme ...

Issue: `TypeError: store middleware is not a valid function`

In my React-Redux code, I have successfully combined the store and reducer in previous apps, possibly due to different versions of React and React-Redux. However, when setting up a new React project with the latest versions, I encountered an error: T ...