Window generation in JS

1

I have the following code js when I execute the function "write ()" with a button event, I get the following error "Can not read property 'closed' of undefined" in the if of the function, can you help me?

var nuevaventana;

function crearnuevaventana()
{
    var nuevaventana = window.open("", "nueva ventana", "status, heigth=200 width=300");
}

function escribe()
{

    if (nuevaventana.closed)
    {
        crearnuevaventana();
    }

    nuevaventana.focus();
    var contenido = "<html><head><title>Nueva Ventana</title></head>";

    contenido += "<body bgcolor='coral'> <h1>Hola mundo</h1>";
    contenido += "</body> </html>";

    nuevaventana.document.write(contenido);
    nuevaventana.document.closed;
}
    
asked by Agustin Coronel 05.10.2018 в 05:28
source

2 answers

0

That happens because within the function create new window () you do not use the global variable new window , but you define another variable with the same name within the scope of the function.

To fix it, you must delete the " var " inside the new window ().

function crearnuevaventana()
{
    nuevaventana = window.open("", "nueva ventana", "status, heigth=200 width=300");
}

This way create new window () initializes the variable new window .

    
answered by 05.10.2018 в 05:42
0

Adding to what RockoDev says, you are effectively declaring a local scope variable (it exists only within crearnuevaventana ) that does not touch the global scope variable.

var nuevaventana; // ámbito global: undefined

function crearnuevaventana()
{
    var nuevaventana = window.open(...); // ámbito local
}

crearnuevaventana();

console.log(nuevaventana); // undefined;

The first step, then, would be to have your function write to the global variable:

function crearnuevaventana()
{
    nuevaventana = window.open(...); // pisa la variable global
}

Peeero There is another problem. When you declare the global variable:

 var nuevaventana;

this has value undefined . It exists, but it has no value. The primitive undefined has no such thing as an attribute closed . When you want to check if the window is closed, and you have never called crearnuevaventana , you will still get that error.

What you can do, then, is to initialize it as a flat object with a property closed

var nuevaventana = { closed: true };

And that way the first time you consult it, it will effectively appear as closed. In successive calls, it will already have been overwritten as a DOM element.

    
answered by 05.10.2018 в 14:40