Introducing the JavaScript Window Object — XML and Console

Introducing the JavaScript Window Object — XML and Console

We look at how to create web components and the console object

Image for postPhoto by Paul Carmona on Unsplash

The window object is a global object that has the properties pertaining to the current DOM document, which is what?s in the tab of a browser. The document property of the window object has the DOM document and associated nodes and methods that we can use to manipulate the DOM nodes and listen to events for each node. Since the window object is global, it?s available in every part of the application.

When a variable is declared without the var , let, or const keywords, they?re automatically attached to the window object, making them available to every part of your web app. This is only applicable when strict mode is disabled. If it?s enabled, then declaring variables without var , let, or const will be stopped an error since it?s not a good idea to let us declare global variables accidentally.

The window object has many properties. They include constructors, value properties, and methods. There are methods to manipulate the current browser tab, like opening and closing new pop-up windows, etc.

In a tabbed browser, each tab has its own window object, so the window object always represents the state of the currently opened tab in which the code is running. However, some properties still apply to all tabs of the browser, like the resizeTo method and the innerHeight and innerWidth properties.

Note that we don?t need to reference the window object directly for invoking methods and object properties. For example, if we want to use the window.Image constructor, we can just write new Image().

In this piece, we continue to look at what?s in the window object. In Part 1, we explored the main constructors that are included with the window object. In this piece, we continue to look at more constructors of the window object and some properties of the window object.

More Constructors

XMLSerializer

The XMLSerializer constructor creates objects with the serializeToString method to build an XML string which represents a DOM tree. The constructor takes no arguments. The serializeToString method takes in a DOM tree node and then returns the string with all the DOM tree content inside the node. The method will throw a TypeError when the node type cannot be serialized. It will throw an InvalidStateError if the tree can’t be serialized successfully. If the content is malformed, then a SyntaxError will be thrown. The following types of nodes can be serialized by the serializeToString method:

  • DocumentType
  • Document
  • DocumentFragment
  • Element
  • Comment
  • Text
  • ProcessingInstruction
  • Attr

For example, we can use the XMLSerializer object as in the following code:

const serializer = new XMLSerializer();const doc = document;const docStr = serializer.serializeToString(doc);console.log(docStr);

The code above creates an XMLSerializer instance. Then we pass in the document object into the serializeToString method, which returns the string of the DOM tree. The console.log output on the last line should resemble something like the following if the code above is run:

<!DOCTYPE html><html xmlns=”http://www.w3.org/1999/xhtml”><head> <meta http-equiv=”content-type” content=”text/html; charset=UTF-8″ /> <title></title> <meta http-equiv=”content-type” content=”text/html; charset=UTF-8″ /> <meta name=”robots” content=”noindex, nofollow” /> <meta name=”googlebot” content=”noindex, nofollow” /> <meta name=”viewport” content=”width=device-width, initial-scale=1″ /><script type=”text/javascript” src=”/js/lib/dummy.js”></script><link rel=”stylesheet” type=”text/css” href=”/css/result-light.css” /><style id=”compiled-css” type=”text/css”> </style><!– TODO: Missing CoffeeScript 2 –><script type=”text/javascript”>//&lt;![CDATA[window.onload=function(){ const serializer = new XMLSerializer();const doc = document;const docStr = serializer.serializeToString(doc);console.log(docStr);}//]]&gt;</script></head><body><script> // tell the embed parent frame the height of the content if (window.parent &amp;&amp; window.parent.parent){ window.parent.parent.postMessage([“resultsFrame”, { height: document.body.getBoundingClientRect().height, slug: “” }], “*”) }// always overwrite window.name, in case users try to set it manually window.name = “result” </script></body></html>Image for postPhoto by Colin Maynard on Unsplash

Properties

The window object has many properties. It inherits properties from the EventTarget interface and implements properties from the WindowOrWorkerGlobalScope and WindowEventHandlers mixins.

window.closed

The closed property is a read-only property that indicates whether the referenced browser window is closed or not. It?s true if the window is closed and false otherwise. For example, if you run:

console.log(window.closed)

on the currently opened window, it should log false since the browser window is obviously open.

window.console

The console property is an object with many properties that are useful for logging information to the browser?s console. It is a read-only object. The console methods are useful for debugging and shouldn?t be used for presenting information to end users. The console object has the following methods:

  • console.assert() ? logs a message and the stack trace to the console if the first argument is false
  • console.clear() ? clears the console
  • console.count() ? logs the number of times this method has been called with the given label
  • console.countReset() ? resets the value of the counter for the given label
  • console.debug() ? logs a message to the console with the log level ?debug?
  • console.dir() ? lists the properties of the given JavaScript object. The content will have triangles to show the content of child objects.
  • console.dirxml() ? displays an HTML or XML representation of the object if possible
  • console.error() ? logs an error message to the console. We can use string substitution and additional arguments to format the log message.
  • console.group() ? creates a group of console messages, indented by levels. We can move out of a level with groupEnd().
  • console.groupCollapsed() ? creates a group of console messages, indented by levels with the items collapsed. We can move out of a level with groupEnd().
  • console.groupEnd() ? exits the current inline group
  • console.info() ? logs informational messages. We can use string substitution and additional arguments to format the log message.
  • console.log() ? used for general logging of information. We can use string substitution and additional arguments to format the log message.
  • console.table() ? logs and displays data in a tabular format
  • console.time() ? starts a timer with the name specified in the parameter. 10000 simultaneous timers can be run on a given page.
  • console.timeEnd() ? stops the specified timer and logs the elapsed time in seconds since it started.
  • console.timeLog() ? logs the value of the specified timer to the console
  • console.trace() ? logs a stack trace
  • console.warn() ? logs a warning message to the console. We can use string substitution and additional arguments to format the log message.

window.customElements

The customElements property is a read-only property that returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements. Custom elements are also called Web Components.

Web Components is a standard that lets us create custom elements that encapsulate other HTML elements. We need this so that we can reuse groups of HTML elements in various places. Without it, we have to repeat the same group of HTML elements in different places if we want to reuse them. Defined custom elements are stored in the CustomElementRegistry so that browsers know that the defined custom element is actually a valid element.

To define a custom element, we can use the customElements property as in the following code:

const customElementRegistry = window.customElements;customElementRegistry.define(‘hello-element’, class extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({ mode: ‘open’ }); const span = document.createElement(‘span’); span.setAttribute(‘class’, ‘wrapper’); span.innerHTML = ‘Hello’; shadow.appendChild(span); } });

Then in the HTML file, we add:

<hello-element></hello-element>

In the code above, we used the define method of the window.customElements object. In the first argument of the define method, we pass in the element name. Then in the second element, we pass in an HTMLElement class, which is actually an object in JavaScript. In the constructor method of the class , we create a span element with the innerHTML set to ?Hello’ and then append it to the shadow root, which is the root of the Web Component. If we run the code above, we should see the word Hello displayed on the screen.

The define method takes three arguments. The first is the name, which is a string that has the name of the custom element. The second argument is an HTMLElement constructor, where, in the constructor class, we create the HTML elements that we want to attach to the shadow root and display the created elements. The third argument is an optional argument that controls how elements are defined. The only property that?s supported is the extends property, which is a string that lets us specify the built-in element to extend. It?s useful for creating a custom element that customizes a built-in element like div , span or p.

Summary

In this piece, we barely scratched the surface of the window object. We only went through the few constructors that may come in handy in various situations.

We created an XMLSerializer object that lets us use the serializeToString method, which comes with the instance that lets us pass in a DOM tree node and get back a string with all the child elements inside converted to a string.

Then we looked at some properties of the window object, including the closed, console, and the customElements properties. The closed property lets us check if the current browser window is closed or not. The console object lets us log data in various ways for debugging purposes. It has various methods to group logging outputs, get the timing of code that?s executed, change the style of the logging output, and much more. The customElements property lets us create new custom elements that are recognized by the browser as a Web Component, which is an entity that encapsulates built-in HTML elements so that we can reuse them by referencing them in our code.

16

No Responses

Write a response