When the browser is first opened, a cookie is read only once

I am currently working on an application that customizes results based on the user's location, specifically the city they are browsing from. The location information will only be used for displaying relevant content and nothing else. I came across a helpful resource on this which I have integrated into my app.

In order to implement this functionality, I added the following code snippet to my _header partial:

<%- unless @lat_lng %>
  <script>
    getGeoLocation();
  </script>
<%- end %>

This JavaScript code is included in my application.js file:

function getGeoLocation() {
  navigator.geolocation.getCurrentPosition(setGeoCookie);
}

function setGeoCookie(position) {
  var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
  document.cookie = "lat_lng=" + escape(cookie_val);
}

In my controller's index action, I have added the following code:

if cookies().key?("lat_lng")
  lat_lng = cookies[:lat_lng].split("|")

  geo_localization = "#{lat_lng[0]},#{lat_lng[1]}"
  query = Geocoder.search(geo_localization).first
  @city = query.state

else
  @city = "nocity"
end

Currently, the cookie is read every time a page loads. I would like to optimize this process by:

  • Detecting the presence of the cookie on the initial page load,
  • If the cookie exists, retrieve the location data,
  • If the cookie does not exist, display the page content without location information,
  • Once the user grants permission for location access, create the cookie, fetch the location data, and reload the page with this new information (potentially using ajax),
  • Maintain the same location information until the user closes the browser tab, avoiding the need to read the cookie repeatedly on each page load.

Although I am not very familiar with JavaScript, I am exploring ways to achieve this functionality.

Answer №1

Consider incorporating the previously interpreted data into the cookie itself for better clarity. Update your JavaScript code to include a condition that verifies this information moving forward.

Another option is to encode this detail in the QueryString URL and retrieve it from there instead.

Best regards,

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

The exception is being thrown in RxJs retryWhen before all retry attempts have been made

I have been working on implementing an API call that needs to be retried a few times in case of errors, after a specific time delay, and based on certain conditions such as checking if the success response JSON has any null fields. I came across this helpf ...

Using CDN to load the STLLoader in Three.js

After deciding to have some fun by creating an STL loader, I've hit a roadblock. Despite trying various solutions found online, I'm still facing issues, mainly due to CDN errors. Currently, I'm following the tutorial on the Three.js site and ...

What is the best way to highlight selected navigation links?

Recently, I implemented a fixed navigation bar with relevant links on a website. The navbar includes a jquery script for smooth scrolling when clicked. However, I am struggling to add a selected class to the clicked link. Despite trying various solutions f ...

Sequelize Authentication is unable to finalize

As I delve into the world of node.js and sequelize, I am encountering a persistent error: /home/cbaket/test/test.js:9 .complete(function(err) { ^ TypeError: undefined is not a function at Object.<anonymous> (/home/cbaket/test/test.js:9: ...

Retrieve data using jQuery.ajax method without page refreshing

Having an issue where I don't want the page to refresh when searching and pressing enter. Can anyone help with this? Here is a sample of my webpage: Is my jQuery script correct? Should I use AJAX to prevent page refreshing? $(function(){ $('in ...

What is the best way to extract the value from a textangular editor within an ng-repeat loop

I am using the TextAngular editor within an ng-repeat loop. Within the HTML <ul ng-repeat="lecture in section.lectures"> <div class="col-md-12 article-show" > <form ng-submit="lecture_content('article', $index + 1, l ...

Issues encountered with jQuery Form Plugin failing to pass a string value to PHP

I'm currently experimenting with the jQuery form plugin (http://jquery.malsup.com/form) to handle photo uploads and previews. However, I'm encountering an issue where the data strings expected to be sent to PHP using the ajaxForm function are com ...

Is there a way to verify if a variable is a generator function, for example, a function with the asterisk symbol and

Is there a foolproof method to determine if a function is a generator, like in the example below: let fn = function* () { yield 100; } if (fn instanceof ??) { for (let value in fn()) { ... } } I have only been able to come up with fn.to ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

Javascript Flickering Effect in HTML5

Currently, I am in the process of creating a simple game using javascript without jQuery. However, I am facing an issue with flickering on the canvas due to the clearing command. After researching solutions online, I came across suggestions for implementin ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values ...

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

Tips on stopping the treeview in the MasterPage from collapsing after clicking a node

Within my setup, I have two views that are nested inside each other. The parent view contains a treeview where each node is a link. Upon clicking a node, the child view undergoes changes (either by updating its content or replacing it entirely with anoth ...

Setting up custom permissions for users in a Discord bot using Discord.js

Currently, I am trying to configure specific commands for myself and my friend who are the bot owners. Initially, I set up commands exclusively for MYSELF with this code: var owner = ("487218875138572298") if (msg.startsWith (prefix + " ...

Using window.location.href to Submit an Array in ASP.NET MVC

What is the correct approach for sending data to a Controller in order to Post data without using a form? Currently, I am only needing to send an array of parameters. The line of code below is what I am currently using, however, I am aware that it is ty ...

Apply the child's style if the parent's sibling contains the specified class

I am struggling to add the class "bold" to a child element (span) of a parent element (button.usa-nav-link). This parent element has a sibling (ul li.active) with the class .active. When the sibling is active, I want the child element's text to be bol ...

Incorporating Google Material Icons into Your UWP Application

I am currently in the process of developing a JavaScript based UWP app for the Windows Store. I've been transferring code from Angular 2 used in my web app directly into the UWP app. However, I've hit a roadblock as none of the material icons I&a ...

The attempt to perform a 'put' operation on the Cache with workbox and nuxt was unsuccessful

Encountering an unexpected error in my console while working on Nuxtjs version 2.15.7: https://i.sstatic.net/pvjv9.png https://i.sstatic.net/A3nrF.png Upon investigation, it seems to be related to the @nuxt/pwa module, even though I don't have it i ...

It is not possible to assign values to a typed array buffer

Why is the value not being assigned as anticipated without any errors being thrown? const fs = require('fs'); let file = "data.dat"; let readStream = fs.createReadStream(file,{highWaterMark:1024*1024*128}) let stats = fs.statSync(file); let stre ...