Skip to content
Robbie Chipka edited this page Jan 12, 2016 · 23 revisions

The libxmljs-dom Window object represents a browser Window

Creating a new window

Here we initiate a new Window object. This will automatically create a new Document in Window.document, but we can replace that if we want to.

var window = new libxmljs.Window();

window.alert("hello world");

window.alert(window.document);

Get a Document's window object

To retrieve the Window object for an existing document, we use Document.defaultView

var document = new libxmljs.Document(); // create a new document

var window = document.defaultView; // get the Window object

window.alert("hello world")

Note: The Document.defaultView Window object is initialized only when it is accessed. This increases performance in cases where a Window object is not needed.

Scripts

As soon as a Window object has a non-empty Document (or as soon as a Document creates a Window via Document.defaultView), the Window object will find all <script> elements and automatically run them (including remote scripts).

Scripts are executed using the built-in NodeJS vm. The code is compiled and run in a sandboxed context where Window is the global object, just like a browser.

Remote scripts are requested and executed asynchronously, but only one script will run at a time. This means that you have to wait until the resource is done loading before you can use it. For example, if a page has a remote jQuery script, you can't access Window.$ until the script has been loaded and executed.

Script done event

The done event is fired when the Window's stack count goes down to 0. This happens after all scripts have run, events have been fired, and all HTTP requests and setTimeouts are finished.

var html = '<html><head><script src="/jquery.js" /></head><body></body></html>';

var document = libxmljs.parseHtml(html);

var window = document.defaultView; // starts loading scripts

window.addEventListener('done', function() {
    // called when all scripts have finished loading
    $('div.content').html(...)
})

Note: The done event callback is automatically cleared after it is triggered, but you can register it again using Window.addEventListener().

Run a script

To run a script in the context of the Window object you can use Window.eval().

window.exec('alert(document.title)')
Clone this wiki locally