Exploring the Ways to Share sessionStorage Across Multiple Browser Tabs Using JavaScript

I have recently started exploring client-side data storage and have successfully implemented an onkeyup search function. The goal is to retrieve the city name via AJAX and display it at the top within the header of the page. To store the city name, I have utilized sessionStorage. However, I noticed that the session does not persist when opening the link in a new tab. Is there a way to synchronize the session across multiple tabs so that the same value is displayed in all opened tabs?

Below is the script I use to set and retrieve the city from the sessionStorage:

function addcity() {
            var citydata = [], searchcity = "";
            var cityid = document.getElementById('hcity').value;
            var cityname = document.getElementById('forsearchcity').value;
            if(cityid != null && cityname != null) {
                searchcity = {cityid : cityid, cityname : cityname};
                citydata.push(searchcity);
            }
            var city = sessionStorage.setItem("city", JSON.stringify(citydata));
        } 
function getcity() {
        var city = sessionStorage.getItem("city");
        var citydata = JSON.parse(city);
        var id = "", name = "", div = "";
        if(citydata != null && citydata.length != 0) {
            for(var i = 0; i < citydata.length; i++) {
                id = citydata[i].cityid;
                name = citydata[i].cityname;
                if(name != null) {
                    div = div + "<div id='user-selected-city-input'>"
                                    +"<a href='<%=WebUrl.searchcity%>'>"
                                    +"<h6>Delivery In</h6>"
                                    +"<h5 style=\"color: #330000;\">"+name+"</h5>"
                                    +"</a>"
                                +"</div>";
                }
            }
        }else{
                div = div + "<div id='user-selected-city-input'>"
                                +"<a href='<%=WebUrl.searchcity%>'>"
                                +"<h6>Delivery In</h6>"
                                +"<h6 style=\"color: black;\">Choose City</h6>"
                                +"</a>"
                            +"</div>";
        }
        document.getElementById("city_pop").innerHTML = div;
    } 

I would appreciate any suggestions or advice.

https://i.stack.imgur.com/ZZE3v.png

Answer №1

One method to explore is storing items in localstorage and setting up an event listener for storage events. This way, you can transfer the content to the sessionstorage of another tab if necessary. Learn more about the StorageEvent interface here.

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

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

A guide on including a node as a parameter, alongside other data types, in a function using ajax within Umbraco

When attempting to pass a node and two strings as parameters to a JsonResult in Umbraco, I encountered an issue where the node variable had no value when debugging the method. Below is the JavaScript code: function newsSub() { if(validateForm('ne ...

"Encountering issues while upgrading Polymer project version from 0.5 to 1.0

I am in the process of upgrading my project from polymer .5 to polymer 1.0. After installing the new version of the polymer library, iron element, and paper element, I encountered the following error: polymer-micro.html:63 Uncaught TypeError: prototype ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object: var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5, "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ]; Given the condition ...

Whenever I find myself being redirected to the login page, my goal is to eliminate the bottomTab from view

I'm looking to eliminate the bottom tab when I land on the login page, even though I've set it up for all pages. However, whenever I click on the login button, the tab remains visible. Here is my current code: import React, { useContext } from & ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

Utilizing JQuery to recycle data post-load

I've got this function: // AJAX MESSAGES DISPLAYING show_msg.on('click', function(e){ var $this = $(this), url = $this.attr('href'), url_info = url + ' .basic_info > *', url_msg = url + ' .cont ...

Unusual JavaScript Variable Glitch

I've been developing a Rock, Paper, Scissors game on JSFiddle, and I'm facing an unusual issue. Regardless of user input or the actual game outcome, two losses are being incorrectly added to the loss counter. I've been unable to pinpoint the ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...

needed a bean of class 'com.supriya.banking.repository.AccountRepository' but could not locate one

APPLICATION FAILED TO START Description: Field accountRepository in com.supriya.banking.service.AccountService required a bean of type 'com.supriya.banking.repository.AccountRepository' that could not be found. The injection point has the foll ...

height detection is not functioning

Here is a straightforward script that I'm using: var element = document.getElementById("container"); if (element.clientHeight == "372") { element.style.height = "328px"; element.style.marginBottom = "44px"; } else { element.style.height = "21 ...

The resume button is failing to activate any functions

I recently encountered an issue with a JS file that is associated with a Wordpress Plugin, specifically a Quiz plugin featuring a timer. I successfully added a Pause and resume button to the quiz, which effectively pauses and resumes the timer. However, I ...

Exploring Highcharts Pie Chart with AJAX for Real-time Data Updates

Looking for some guidance with implementing AJAX in my code to make my chart dynamic based on data from the database. Although the code is error-free, the chart is not refreshing automatically. Any help, comments, or suggestions would be greatly appreciate ...

jQuery does not trigger the error event for a 403 status code when loading a new image src

Currently working on a project that involves implementing a static Google map on a webpage. The challenge I am facing is resizing the map dynamically when the page size changes. In order to achieve this, I have created a function that triggers on page resi ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...

Keystrokes may not consistently register in Firefox

I created a compact web application where users can interact by clicking on a button to trigger a modal dialog. Within this dialog, users have the ability to choose from various options. To enhance user experience, I implemented the utilization of the jQue ...

React Hooks: In useEffect(), unable to modify parent component's state

Within my component, I have a form for users to input a title, description, and images. This component is nested within its parent component, and I want the form data to be saved if the user switches sections and returns later without losing their progress ...

Custom template for prefetched data is not displaying in Typeahead.js

I'm currently utilizing Twitter's typeahead.js plugin for displaying autocomplete suggestions. Here is the code snippet: $.ajax({ url:'/getlocals/', success: function(data){ $('.local-type').typeahead({ ...

Custom-designed background featuring unique styles

I have implemented the following code to create a continuous running banner: <style> #myimage { position: fixed; left: 0%; width: 100%; bottom: 0%; background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bild ...