Manipulate an open window from the parent window with Javascript

7

I'm thinking of using the native window.open() feature to create a small web system that is similar to desktop systems (made with windows forms). My problem is regarding communication and manipulation of data / events between 2 windows.

I need to know how I can manipulate windows instantiated from a parent window, updating your DOM, executing functions, etc ...

    
asked by anonymous 10.01.2016 / 18:35

1 answer

6

One way to handle window of window.open() is to save its declaration to a variable. For example:

var win = window.open("pagina.html", "", "width=400, height=400");

In the example above, it will open pagina.html with a width and height of 400px.

The arguments are, respectively, origem , windowName and atributos .

You can also open an empty window and enter data manually, however this is quite limited. You would do this basically with document.write() as follows.

win.document.write(seu html);
win.document.write("<img src='img.jpg' alt='' />"); // por exemplo

You can not use .innerHTML since you do not have HTML yet.

Another technique is this:

var popup = window.open("", "popup", "width=400, height=400");
popup.document.write("<html><head><title>Exemplo</title></head><body>");
// Captura a div#content e insere seu conteudo HTML na popup
popup.document.write(document.getElementById('content').innerHTML);

popup.document.write("</body></html>");

And you insert into the window an existing content some place of your site.

To manipulate the elements you can use JQuery, like this:

var body = $("body", popup.document); // especifica-se o documento como segundo argumento.

You can insert elements:

body.append('<input type="text"/>')

And so on ...

Here is an example of functions:

var popup = window.open("", "popup", "width=200, height=100");
popup.document.write("<html><head><title></title></head><body></body></html>");

var body = $("body", popup.document);
body.append('<input type="text" id="texto"> <br> <span><span>');

var text = body.children('input:text');
var span = body.children('span');
text.keyup(function() {
  span.text(text.val())
})

A way to manipulate the popup elements, since these elements belong to another page, is to use .load() of jquery, I tested with .ready() , but did not get success. It would look something like this:

var popup = window.open("exemplo.html", "popup", "width=200, height=100");
// No load declara-se a popup
$(popup).load(function(){
    var body = $('body', popup.document); //seleciona o body com a declaração do documento da popup
    body.css('background', '#333');
})

So you would be free to set up elements already created on another page.

Note: DOM manipulation in a popup does not work in Chrome in the file protocol. In the http protocol it works normally, just like in Firefox.

I hope you have helped ...

    
10.01.2016 / 20:11