Navigating through the window.location

After fetching lat and lng values from sessionStorage, my goal is to send them to the browser using window.location. However, I'm encountering an infinite loop issue.

    var lat = sessionStorage.getItem('lat');
    var lng = sessionStorage.getItem('lng');       
    window.location = '?lat='+lat+'&lng='+lng;
   

I have seen similar questions about this problem but none of the solutions seem to work for me. I have tried different methods such as window.location.hash / href, but the outcome is not what I anticipated.

Does anyone have a proper solution for implementing this function correctly? Thank you very much.

Answer №1

Always double-check the location before finalizing it to avoid getting stuck in a continuous loop.

const urlParams = new URLSearchParams(window.location.search);
const latQS = urlParams.get('lat');
const lat = sessionStorage.getItem('lat');
cost lng = sessionStorage.getItem('lng');       
if (!latQS && lat && lng) {
  const lat = sessionStorage.getItem('lat');
  cost lng = sessionStorage.getItem('lng');       
  window.location = '?lat='+lat+'&lng='+lng;
}

Alternatively, you can update the history using pushstate.

const lat = sessionStorage.getItem('lat');
cost lng = sessionStorage.getItem('lng');
if (lat && lng) { 
  const url = new URL(window.location);
  url.searchParams.set('lat', lat);
  url.searchParams.set('lng', lng);
  window.history.pushState({}, '', url);
}

Answer №2

Check out this handy self-invoked function that can help you achieve your goal:

const customRedirect = (() => {
  var latitude = sessionStorage.getItem("latitude");
  var longitude = sessionStorage.getItem("longitude");
  const parameters = new URLSearchParams(window.location.search);
  !parameters.get("lat") ? (window.location.href = `?lat=${latitude}&lng=${longitude}`) : null;
})();

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

"Exploring the best method to utilize a for loop for updating an array of objects in

I'm looking to update a nested mongo document using a for loop with my node.js code below: //loop starts var update = { "rate":mainRate, "classifierCategories."+e+".rate":temiz[i].slice(0,2) }; classifier.update({"classifierS ...

What could be causing the dropdownlist value not to be selected or checked while using "Select2.js"?

1-Description I have implemented a select2 filter for a dropdown list in my project. (Tools used: Bootstrap 5 & .Net 7.0 Core) When I choose a client name and click submit, an error occurs stating that the 'clientId' is null (indicating no ...

Steps to sending a parameter to an AngularJS $http success callback

In my AngularJS application, I have implemented the following code: $http.get('/plugin/' + key + '/js').success(function (data) { if (data.length > 0) { console.log(data); // Here, I also need to retrieve the val ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Purging the database using Django's `manage.py` command

Is it possible to use Django's manage.py to reset the database completely, restoring it to its initial state when it was first created? ...

Dynamic route fails to return value for ID search

Currently, I am testing by creating an array of users containing their respective IDs and names. There is also a button that triggers an onclick function to add the element's ID to the page's URL in order to establish a dynamic route. However, wh ...

Adding a question mark at the top of the content in a txt file using node.js's

When I use the fs.readFile() function to retrieve data from a .txt file, I notice that the content begins with "?Alex libman". Here is the code snippet: fs.readFile(__dirname+"/txts/generate/titles0.txt", "utf-8", function (ex, titles) { var titlesArr = ...

Scroll a div using JavaScript/jQuery

I'm currently facing some challenges in resolving this issue. My goal is to pan a DIV using jQuery. The process is quite straightforward - on mouseDown, I capture X & Y coordinates and then subtract them from the newly obtained X & Y values during mou ...

Tips for organizing sequence in Django Related Models (Generic relationships)

Here are my models: HitCounter: hits = models.PositiveIntegerField(default=0) object_pk = models.TextField('object ID') content_type = models.ForeignKey(ContentType, verbose_name="content cype", ...

A guide on invoking a function within a nested or local function

When the code below is executed in a local function, such as the one inside s3.getObject, it throws an error stating that setState is not a function. s3.getObject({ Bucket: bucket, Key: key }, function (error, data) { if (error != ...

Article: Offering CoffeeScript and JavaScript Assets Simultaneously

Currently, my web app is up and running using Node and Express. I initially developed it in JavaScript but now want to transition over to CoffeeScript. My goal is to have both file1.js and file2.coffee coexisting in the application (with both being served ...

How can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

Having difficulty displaying TIFF images and incorporating them into a Fabric Object

I have gone through the tutorials available at: and also familiarized myself with the Fabric Objects documentation. While I was successful in loading JPG and PNG images onto the canvas, my current project requires me to load TIFF images and apply filters ...

Strip out the script tag from the data received in the AJAX response

I'm currently developing a single-page application using jQuery. The entire HTML pages are sent to the browser as an AJAX response. $.post(url, function (data) { $("#resp").html(data); $("#resp").find("script").each(function (i) { ...

What kind of function should we create to return an array of promises?

I have a function that returns an array of Promises. What should be the return type of this function? Here's the code snippet: const makeLabelNodesRequest: Promise<K8sResourceKind> = (selectedNode: NodeKind[]) => { const labelPath = '/m ...

What is the method to pass raw strings via a jQuery POST request?

Attempting to use jQuery.ajax() to POST a raw string. For example: contact_list=352345 Here's the code snippet: $.ajax({ beforeSend: function(xhr){ xhr.setRequestHeader('Content-Type', header); } }, ...

Examining the values of context variables within a custom template tag block in Django

Looking to create a customized template tag in Django with specific functionality: Retrieve all context variables between the start and end tags If all variables contain valid, non-empty values (not None or ''), return the entire block If any v ...

Using Jade language in a standard web application without the need for Node.js

Can Jade be utilized in a traditional web application without reliance on Node.js? This question might seem unconventional considering Jade is built for Node, but I'm curious to know if its functionality can extend beyond the Node environment. ...

"Obtaining table row values by clicking a button in Angularjs - a step-by-step guide

I am seeking guidance on extracting the table row values of the selected row in the provided Plunkr. When a row is selected using the checkbox in the table and the update button is clicked, I require the row ID, name, and values. You can access the Plunk ...

Enhance a portion of your text with some flair

Is it possible to apply styles to specific parts of text that are within an <input> value or a <span> element? For instance, I have the following data: {text text} an other text... I want to add styles to the text enclosed within {}. Here i ...