Writing to the Window

Being able to generate an entirely new page from the code of an existing page has advantages. You don't need to create a whole new page for each of your popups, and so the popup content is already loaded when the main page is. First, let's » generate a page.

function dirtypop()
{
  var generator=window.open('','name','height=400,width=500');
  
  generator.document.write('<html><head><title>Popup</title>');
  generator.document.write('<link rel="stylesheet" href="style.css">');
  generator.document.write('</head><body>');
  generator.document.write('<p>This page was generated by
    the main window.</p>');
  generator.document.write('<p><a href="javascript:self.close()">
    Close</a> the popup.</p>');
  generator.document.write('</body></html>');
  generator.document.close();
}

<a href="javascript:dirtypop();">Generate!</a>

As you can see, we create a new window as a variable again, and then use the variable name in place of window (which normally comes before document) to write directly into it. The document.close() method at the end is not the same as window.close() — in this case it signifies that we've stopped writing to the window. Note that any stylesheet information you have on your main page is not carried through to the popup; you must write the style information into the popup code.

Generating windows like this does bring some problems. For one, the URL of the page is really up to the browser. Some leave it as 'undefined' or 'blank', while others just give it the URL of the main window, which brings up all sorts of issues. You can check what your browser reckons the URL is with the view URL link I added to the window above. Thankfully, while some browsers see the popup as a conjoined part of the same page, self.close() will always close just the popup, not its parent window.

0 comments:

Post a Comment