Wednesday, April 24, 2024
HomeProgrammingUnderstanding the JavaScript Window Object

Understanding the JavaScript Window Object


Each JavaScript setting has a world object. Any variables which can be created within the world scope are literally properties of this object, and any features are strategies of it. In a browser setting the worldwide object is the window object, which represents the browser window that incorporates an online web page.

On this article, we’ll cowl some vital makes use of of the Window Object:

This publish is customized from my well-known course: JavaScript: Novice to Ninja.

The Browser Object Mannequin

The Browser Object Mannequin (or BOM for brief) is a group of properties and strategies that comprise details about the browser and pc display. For instance, we are able to discover out which browser is getting used to view a web page (although, this methodology is unreliable). We will additionally discover out the size of the display it’s considered on, and which pages have been visited earlier than the present web page. It can be used for the moderately doubtful follow of making pop-up home windows, in the event you’re into annoying your customers.

There isn’t a official normal for the BOM, though there are a variety of properties and strategies which can be supported by all the main browsers, making a type of de facto normal. These properties and strategies are made obtainable by the window object. Each browser window, tab, popup, body, and iframe has a window object.

The BOM Solely Makes Sense in a Browser Surroundings

Keep in mind that JavaScript might be run in numerous environments. The BOM solely is sensible in a browser setting. Which means different environments (corresponding to Node.js) in all probability received’t have a window object, though they are going to nonetheless have a worldwide object; for instance, Node.js has an object referred to as world.

When you don’t know the identify of the worldwide object, you can too discuss with it utilizing the key phrase this within the world scope. The next code supplies a fast approach of assigning the variable world to the worldwide object:


const world = this;

Going World

World variables are variables which can be created with out utilizing the constlet or var key phrases. World variables might be accessed in all elements of this system.

World variables are precise properties of a worldwide object. In a browser setting, the worldwide object is the window object. Which means any world variable created is definitely a property of the window object, as might be seen within the instance under:

x = 6;  
>> 6
window.x 
>> 6

>> true

On the whole, it is best to discuss with world variables with out utilizing the window object; it’s much less typing and your code shall be extra transportable between environments. An exception is that if it is advisable examine whether or not a worldwide variable has been outlined. For instance, the next code will throw a ReferenceError if x has not been outlined:

if (x) {
    
}

Nonetheless, if the variable is accessed as a property of the window object, then the code will nonetheless work, as window.x will merely return false, which means the block of code is not going to be evaluated:

if (window.x) {
    
}

Some features we’ve already met, corresponding to parseInt() and isNaN(), are literally strategies of the worldwide object, which in a browser setting makes them strategies of the window object:

Like variables, it’s customary to omit accessing them by the window object.

Dialogs

There are three features that produced dialogs within the browsers: alert()affirm() and immediate(). These are usually not a part of the ECMAScript normal, though all main browsers help them as strategies of the window object.

The window.alert() methodology will pause the execution of this system and show a message in a dialog field. The message is offered as an argument to the tactic, and undefined is all the time returned:

window.alert('Howdy');
>> undefined
Alert Dialog
Alert Dialog

The window.affirm() methodology will cease the execution of this system and show a affirmation dialog that exhibits the message offered as an argument, and giving the choices of OK or Cancel. It returns the boolean values of true if the consumer clicks OK, and false if the consumer clicks Cancel:

window.affirm('Do you want to proceed?');
>> undefined
Confirm Dialog
Affirm dialog

The window.immediate() methodology will cease the execution of this system. It shows a dialog that exhibits a message offered as an argument, in addition to an enter area that enables the consumer to enter textual content. This textual content is then returned as a string when the consumer clicks OK. If the consumer clicks Cancel, null is returned:

window.immediate('Please enter your identify:');
Prompt Dialog
Immediate dialog

Use Window Dialogs With Care

It’s price reiterating once more that these strategies will cease the execution of a program in its tracks. Which means every part will cease processing on the level the tactic is named, till the consumer clicks OK or Cancel. This will trigger issues if this system must course of one thing else on the similar time or this system is ready for a callback operate.

There are some events when this performance can be utilized as a bonus, for instance, a window.affirm() dialog can be utilized as a last examine to see if a consumer desires to delete a useful resource. This can cease this system from going forward and deleting the useful resource whereas the consumer decides what to do.

It’s additionally price retaining in thoughts that the majority browsers permit customers to disable any dialogs from repeatedly showing, which means they don’t seem to be a characteristic to be relied upon.

Browser Info

The window object has a variety of properties and strategies that present details about the consumer’s browser.

Get Browser data with the Navigator object

The window object has a navigator property that returns a reference to the Navigator object. The Navigator object incorporates details about the browser getting used. Its userAgent property will return details about the browser and working system getting used. For instance, if I run the next line of code, it exhibits that I’m utilizing Safari model 10 on Mac OS:

window.navigator.userAgent
>>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Model/10.0.3 Safari/602.4.8"

Don’t depend on this data although, as it may be modified by a consumer to masquerade as a special browser. It can be troublesome to make any sense of the string returned, as a result of all browsers faux to be others to a point. For instance, each browser will embody the string “Mozilla” in its userAgent property, for causes of legacy Netscape compatibility. The userAgent property has been deprecated from the official specification, however it stays properly supported in all main browsers.

Get URL particulars: path, protocol, ports, and so forth.

The window.location property is an object that incorporates details about the URL of the present web page. It incorporates a variety of properties that present details about completely different fragments of the URL.

The href property returns the total URL as a string:

window.location.href
>> "https://www.sitepoint.com/premium/books/javascript-novice-to-ninja-2nd-edition/"

This property (in addition to many of the others on this part) is a learn/write property, which suggests it can be modified by task. If that is executed, the web page shall be reloaded utilizing the brand new property. For instance, coming into the next line into the browser console will redirect the web page to the SitePoint homepage:

window.location.href = 'https://www.sitepoint.com/'
>> "https://www.sitepoint.com/"

The protocol property returns a string describing the protocol used (corresponding to httphttpspop2ftp and so forth.). Notice that there’s a colon (:) on the finish:

window.location.protocol
>> "https:"

The host property returns a string describing the area of the present URL and the port quantity (that is typically omitted if the default port 80 is used):

window.location.host
>> "www.sitepoint.com"

The hostname property returns a string describing the area of the present URL:

window.location.hostname
>> "www.sitepoint.com"

The port property returns a string describing the port quantity, though it’ll return an empty string if the port is just not explicitly acknowledged within the URL:

window.location.port
>> ""

The pathname property returns a string of the trail that follows the area:

window.location.pathname
>> "/premium/books/javascript-novice-to-ninja-2nd-edition/"

The search property returns a string that begins with a “?” adopted by the question string parameters. It returns an empty string if there aren’t any question string parameters. That is what I get once I seek for “Darren Jones” on SitePoint:

window.location.search
>> "?q=darrenpercent20jones&firstSearch=true"

The hash property returns a string that begins with a “#” adopted by the fragment identifier. It returns an empty string if there isn’t a fragment identifier:

window.location.hash
>> ""

The origin property returns a string that exhibits the protocol and area the place the present web page originated from. This property is read-only, so can’t be modified:

window.location.origin
>> "https://www.sitepoint.com"

The window.location object additionally has the next strategies:

  • The reload() methodology can be utilized to pressure a reload of the present web page. If it’s given a parameter of true, it’ll pressure the browser to reload the web page from the server, as a substitute of utilizing a cached web page.
  • The assign() methodology can be utilized to load one other useful resource from a URL offered as a parameter, for instance:
window.location.assign('https://www.sitepoint.com/')
  • The substitute() methodology is nearly the identical because the assign() methodology, besides the present web page is not going to be saved within the session historical past, so the consumer shall be unable to navigate again to it utilizing the again button.
  • The toString() methodology returns a string containing the entire URL:
window.location.toString();
>> "https://www.sitepoint.com/javascript/"

The Browser Historical past

The window.historical past property can be utilized to entry details about any beforehand visited pages within the present browser session. Keep away from complicated this with the brand new HTML5 Historical past API. (See http://www.sitepoint.com/javascript-history-pushstate/ publish for particulars.)

The window.historical past.size property exhibits what number of pages have been visited earlier than arriving on the present web page.

The window.historical past.go() methodology can be utilized to go to a particular web page, the place 0 is the present web page:

window.historical past.go(1); 
window.historical past.go(0); 
window.historical past.go(-1); 

There are additionally the window.historical past.ahead() and window.historical past.again() strategies that can be utilized to navigate forwards and backwards by one web page respectively, identical to utilizing the browser’s ahead and again buttons.

Controlling Home windows

A brand new window might be opened utilizing the window.open() methodology. This takes the URL of the web page to be opened as its first parameter, the window title as its second parameter, and a listing of attributes because the third parameter. This can be assigned to a variable, so the window can then be referenced later within the code:

const popup = window.open('https://sitepoint.com','SitePoint','width=700,peak=700,resizable=sure');
A popup window
A popup window

The shut() methodology can be utilized to shut a window, assuming you have got a reference to it:

popup.shut();

Additionally it is attainable to maneuver a window utilizing the window.moveTo() methodology. This takes two parameters which can be the X and Y coordinates of the display that the window is to be moved to:

window.moveTo(0,0); 

You possibly can resize a window utilizing the window.resizeTo() methodology. This takes two parameters that specify the width and peak of the resized window’s dimensions:

window.resizeTo(600,400);

Annoying Popups

These strategies have been largely accountable for giving JavaScript a foul identify, as they have been used for creating annoying pop-up home windows that normally contained intrusive ads. It’s additionally a foul concept from a usability standpoint to resize or transfer a consumer’s window.

Many browsers block pop-up home windows and disallow a few of these strategies to be referred to as in sure instances. For instance, you may’t resize a window if a couple of tab is open. You can also’t transfer or resize a window that wasn’t created utilizing window.open().

It’s uncommon that it could be wise to make use of any of those strategies, so suppose very rigorously earlier than utilizing them. There'll nearly all the time be a greater different, and a ninja programmer will endeavor to seek out it.

Display Info

The window.display object incorporates details about the display the browser is displayed on. You'll find out the peak and width of the display in pixels utilizing the peak and width properties respectively:

window.display.peak
>> 1024
window.display.width
>> 1280

The availHeight and availWidth can be utilized to seek out the peak and width of the display, excluding any working system menus:

window.display.availWidth
>> 1280
window.display.availHeight
>> 995

The colorDepth property can be utilized to seek out the colour bit depth of the consumer’s monitor, though there are few use instances for doing this apart from amassing consumer statistics:

window.display.colorDepth;
>> 24

Extra Helpful on Cellular

The Display object has extra makes use of for cellular gadgets. It additionally lets you do issues like flip off the gadget’s display, detect a change in its orientation or lock it in a particular orientation.

Use With Care

Lots of the strategies and properties coated within the earlier part have been abused previously for doubtful actions corresponding to user-agent sniffing, or detecting display dimensions to resolve whether or not or to not show sure components. These practices have (fortunately) now been outdated by higher practices, corresponding to media queries and have detection, which is roofed within the subsequent chapter.

The Doc Object

Every window object incorporates a doc object. This object has properties and strategies that take care of the web page that has been loaded into the window. In Chapter 6, we coated the Doc Object Mannequin and the properties and strategies used to govern objects on the web page. The doc object incorporates just a few different strategies which can be price taking a look at.

doc.write()

The write() methodology merely writes a string of textual content to the web page. If a web page has already loaded, it'll utterly substitute the present doc:

doc.write('Howdy, world!');

This might substitute the entire doc with the string Howdy, world!. It's attainable to incorporate HTML within the string and this can turn out to be a part of the DOM tree. For instance, the next piece of code will create an <h1> tag node and a toddler textual content node:

doc.write('<h1>Howdy, world!</h1>');

The doc.write() methodology can be used inside a doc inside <script> tags to inject a string into the markup. This is not going to overwrite the remainder of the HTML on the web page. The next instance will place the textual content "Howdy, world!" contained in the <h1> tags and the remainder of the web page will show as regular:

<h1>
    <script>doc.write("Howdy, world!")</script>
</h1>

Using doc.write() is closely frowned upon as it could solely be realistically utilized by mixing JavaScript inside an HTML doc. There are nonetheless some extraordinarily uncommon respectable makes use of of it, however a ninja programmer will infrequently want to make use of it.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments