When the pop-up remains open between button presses, the Javascript window[] variable is undefined

Here is an example code snippet that utilizes Javascript to open a pop-up window:

If the pop-up is closed before pressing another button, the data is successfully sent and can be accessed inside the pop-up's javascript code using the following syntax:

window.onload = () => {
    addAnotherTable(window["dataarray"]);
}

However, if the pop-up remains open when pressing another button, the window["dataarray"] variable becomes undefined. Even though v_popup["dataarray"] is still assigned to sub_array within the main AddTable function.

The question at hand is why does window["dataarray"] become undefined without closing the pop-up, and how can this issue be resolved?

function addTable(result, indices) {
    indices = [2, 3, 6, 2, 4, 4, 1, 5, 3, 1, 1, 1, 2, 4, 12, 1, 4, 4, 2, 1, 4, 1, 12, 13, 1]; //for testing
     counter = 0;
    low = [];
    high = [];
    for (var i = 0; i < indices.length; i++) {
        let btn = document.createElement("button");
        btn.innerHTML = result[counter][0];
        btn.className = "button-28";
        var low = counter;
        var high = indices[i] + counter;
        var sub_array = result.slice(low, high);

        (function (sub_array) {
            btn.onclick = function () {
                var v_popup = window.open("popup.html", 'popUpWindow', 'height=300,width=700,left=50,top=50,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no, status=no');
                v_popup["dataarray"] = sub_array;
            }
        })(sub_array);

        counter += indices[i];
    }
}

Answer №1

I advise against utilizing window for state management; instead, consider these examples of more effective state management techniques.

Straightforward approach: How to store and retrieve window state?

More advanced method: https://dev.to/vijaypushkin/dead-simple-state-management-in-vanilla-javascript-24p0

Additionally, here is an article detailing how to properly handle popups to prevent encountering related issues:

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

Encountering an SSL error while running npm dev

➜ npm run dev ... Starting development server... DONE Successfully compiled in 2768ms 11:30:11 AM Listening at http://localhost:8080 After running the npm run devcommand, everything seemed to work fine. However, I noticed an error in the browser c ...

Having trouble transferring a file using html and php?

Currently, I am attempting to transfer a file from one directory to another using PHP. However, I am encountering an issue where every time I select the file to upload and press submit, it redirects me to a page that saves my .php file instead of the inten ...

Dealing with delays in rendering certain values with Angular interpolation & ways to eliminate an element from an array of TypeScript objects

I am currently developing a web application using ASP.NET Core - Angular. The app allows users to select a customer as the starting point and then calculates the distance & duration to other customers using Google Maps Distance Matrix Service. Although I a ...

Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an err ...

Creating dynamic stripes on MUI LinearProgress for lively animations

I'm looking to add animation to MUI LinearProgress. I have the animation keyframes code, but I'm not sure how to implement the stripes effect. Any advice would be appreciated. Here is the code snippet I have: import React, { FunctionComponent } ...

Conceal the URL and any parameters upon successful completion of AJAX request

In my ajax js code, the solonreport.jsp file returns a URL link that connects to a local report server and generates an Excel report. However, when using this link with the window.open(json.url) function, the link and parameters are visible to the user. ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

What is the best way to adjust the maxHeight within AccordionDetails and enable scrolling functionality?

I am looking to display a large amount of data using the Accordion component from material-ui nested inside a Box element. However, I am unsure how to customize the default styles in order to set a specific maxHeight. Is there a way for me to take control ...

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

The Material UI text field on mobile devices causes the screen to zoom in, cutting off the top content and displaying the bottom of the page

Whenever I click on the Material UI text Field during login, the screen gets pushed down and cuts off content at the top of the page. View image description here -I have examined my CSS to see if setting the container height to 100vh is causing this issue ...

tips for extracting data from a javascript chart without an internet connection

Recently, I've been exploring a website that contains a fascinating javascript chart displaying a simple time series. When hovering over the data points on the chart, a popup window reveals the exact value of each point. While I am aware of methods t ...

Node.js Express: Invalid attempt to modify headers after they have already been sent

I have been working on reading a growing file in nodejs and have implemented the following code in my app.js file. app.post('/readfile',function (req,res) { var fullfilename = req.body.filepath+"\\"+req.body.filename; var bi ...

What is the best way to position the wizard on both the left and right sides of the screen

Currently, here's the code I have, and I want it to appear like this. What are the steps needed to adjust the CSS in order to achieve that? .nav-wizard { display: table; width: 100%; } .nav-wizard > li { display: table-cell; text-align: ...

Remove an element from an array based on the index provided by the front end

Currently, I am attempting to eliminate a specific item from a PHP array stored in a JSON file. Here is an example of the JSON file structure: { "1.49514754373E+12": { "description": "I don't like it", "fileNames": [ " ...

Is there a way to include an optional backslash in URLs using the .htaccess file without leading browsers to believe I am navigating to a subfolder?

As I update my php pages with the .htaccess file, I am facing an issue where the pages do not load properly when an optional backslash ("/") is included in the URLs. One possible solution is to use absolute URLs instead of relative ones so that CSS and J ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

The input field cannot accommodate the lengthy value in the Mat Select option

When a user selects a value in my mat select, it doesn't display well in the selection box. The text wraps when the selection is opened, but once a choice is made, it gets cut off without proper spacing between the ellipses and the dropdown arrow. Th ...

Error: The variable 'err' is undefined in the mongoose mongodb code

Every time I try to execute this code, an error pops up stating that err is undefined Below is the code snippet causing the issue: app.post('/tinder/cards', (req, res) => { const dbCard = req.body; Cards.create(dbCard, (err, data) => { ...

Running a JavaScript function directly in the browser's address bar with GWT

Attempting to run Javascript in my web application by entering the following in the browser URL/address bar: javascript:window.alert('test');void(0); Despite this, the alert box fails to display. Is it possible that the application is in DevMod ...

Are there any additional performance costs associated with transmitting JSON objects instead of stringified JSON data through node.js APIs?

When developing node.js APIs, we have the option to send plain JSON objects as parameters (body params). However, I wonder if there is some extra overhead for formatting. What if I stringify the JSON before sending it to the API and then parse it back to i ...