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

ReactJs throws an error of "Uncaught SyntaxError: Unexpected token '<' while utilizing the map() function in ReactJs that produces JSX (specifically MaterialUi-icons) within an array

In the file constant.js, I have defined object names and icons as keys. The key icon contains the icon component from @mui/icons-material, but when I attempt to retrieve the value from the icon, I encounter an error. Uncaught SyntaxError: Unexpected toke ...

preventing firefox from highlighting text on a webpage

Similar Question: What's the most effective method to prevent text highlighting when clicking inside a div using JavaScript? Is there a way to prevent Firefox from highlighting content when a user clicks and drags? ...

Creating a dynamic 3D pie chart with Highcharts and JSON data

I am attempting to create a 3D pie chart using HighChart with JSON data. Despite enabling the 3D option, it only displays in 2D. Here is an example of the 3D pie chart I am trying to achieve: Could someone please help me identify what might be missing in ...

Get a URL from the JSON data returned by the Wikipedia API

How can I retrieve the image URL from a JSON response and store it in a variable? I found helpful information on the MediaWiki API help page Following this example to extract image information from a page: https://commons.wikimedia.org/w/api.php?action= ...

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

Returning to the initial state after clicking on an element within a repeated set in AngularJS?

I'm currently facing a challenge, mainly due to my lack of understanding in basic AngularJs concepts. The issue arises when I interact with a list of clickable words. When I click on any of these words, their color changes individually thanks to the i ...

Retrieving Data from Vue JS Store

I am fetching value from the store import {store} from '../../store/store' Here is the Variable:- let Data = { textType: '', textData: null }; Upon using console.log(store.state.testData) We see the following result in the cons ...

Using Javascript to access a website from a Windows Store application

Currently, I am working on a project to create a Windows store app using HTML and JavaScript. One of the key components of my app involves logging into a specific website with a username and password. Here is an example website for reference: The process ...

What is the best way to incorporate an ID from a scala template into an AJAX request?

In my application built on the Play Framework 2.3.8, users can input questions and answers. The view class receives a List[Question] which is iterated through using a for each loop to display them: @for(question <- questionList){ <!-- Questions --& ...

Learn the technique in Vue to separate a string using commas and store the values in an array

As a Ruby enthusiast, I am delving into the world of Vue. In my project, users can input multiple styleCodes separated by commas. I aim to store these styleCodes in an array for flexible length calculations. See my code snippet below: <template> &l ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: with this new link: without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restriction of needing at least 10 reputation points in order to post more t ...

ways to halt a noise once an animation is complete

I don't have much experience with coding in general, but somehow I've made it this far. Now I'm stuck on the final piece of the puzzle. This is related to a Twitch alert that I'm setting up through 'Stream Elements'. The iss ...

changing the contents of an array within the current state

My current task involves updating a list of names in the state before sending it as props to another component. // code snippet omitted for brevity this.state = { // other states here playerName: { player1Name: 'Default Player 1 Name ...

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...

Issue with ngFor displaying only the second item in the array

There are supposed to be two editable input fields for each section, with corresponding data. However, only the second JSON from the sample is being displayed in both sections. The JSON in the TypeScript file appears as follows: this.sample = [ { "se ...

Effective ways to engage with a window that is supervised by a different controller?

Although the question may appear vague initially, I struggled to find a better way to convey my idea. Let me elaborate on it in detail. In my SPA application, I have MasterController connected to the <html> tag. This MasterController consists of all ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

"Troubleshooting the issue of jQuery failing to set data

Although it seems straightforward, I am puzzled as to why this code is not functioning properly. The selector is accurate, but for some reason the .faqContent div is not being updated with the data-height attribute. $('.faqItem .faqContent').eac ...

Encountering an error when attempting to generate a production build after running the npm install command with the

After adding the brotli-webpack-plugin as a devDependency, I encountered an issue when attempting to generate a production build using npm run build (which internally runs next build). The error message displayed was: Error: Cannot find module 'bro ...

NodeJS - Bluebird: implementing a loop with a waiting mechanism for completion

Struggling with a seemingly simple task in my NodeJS and MongoDB project. I've included Bluebird for promises, but need some help. In my code, I have a basic for-loop that generates random names and pushes them into an array: const PlayerGenerator = ...