Manipulating an open window from the parent window with Javascript

Asked

Viewed 2,234 times

7

I’m thinking of using the native resource window.open() to create a small web system that is similar to desktop systems (made with windows Forms). My problem is in relation to communication and data/event manipulation between 2 windows.

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

1 answer

6


A way of manipulating window of window.open() is keeping your declaration in a variable. For example:

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

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

The arguments are respectively: origem, windowName and atributos.


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

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

You can’t use the .innerHTML since you don’t 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 that you insert into window content already existing somewhere on your site.


To manipulate the elements you can use Jquery, thus:

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

Can insert elements:

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

And so on 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 elements of popup, and these elements belong to another page, is to use the .load() jquery, I ran tests with .ready(), but I didn’t succeed. 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');
})

Thus, you would be free to configure the elements already created on another page.

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

I hope it helped...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.