0% found this document useful (0 votes)
5 views44 pages

JavaScript- BOM Concept

The Browser Object Model (BOM) in JavaScript allows interaction with browser functionalities through various objects like Window, Document, Screen, History, Navigator, Location, and Console. Each object serves specific purposes, such as manipulating the browser window, accessing the current web page, and retrieving device information. The document object, a key component of the BOM, represents the HTML document and provides methods for manipulating HTML elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

JavaScript- BOM Concept

The Browser Object Model (BOM) in JavaScript allows interaction with browser functionalities through various objects like Window, Document, Screen, History, Navigator, Location, and Console. Each object serves specific purposes, such as manipulating the browser window, accessing the current web page, and retrieving device information. The document object, a key component of the BOM, represents the HTML document and provides methods for manipulating HTML elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

JavaScript - Browser Object Model

The Browser Object Model (BOM) in JavaScript refers to the objects provided by the browsers
to interact with them. By using these objects, you can manipulate the browser's functionality. For
example, you can get the browser history and window size, navigate to different URLs, etc.

The Browser object model is not standardized. It depends on which browser you are using.

Here, we have listed all objects of the Browser Object Model with descriptions −

1. Window − The 'window' object represents the current browser window. You
can use it to manipulate the browser window.

2. Document − The 'document' object represents the currently opened web


page in the browser window. You can use it to customize the property of the
document.

3. Screen − It provides information about the user's device's screen.

4. History − It provides the browser's session history.

5. Navigator − It is used to get the browser's information like default language,


etc.

6. Location − The Location object is used to get the URL information, such as
the hostname of the current web page.

7. Console − The console object allows developers to access the browser's


console.

JavaScript Window Object


The JavaScript window object represents the browser's window. We can use different methods
and properties of the window object to manipulate current browser window. For example,
showing an alert, opening a new window, closing the current window, etc.

All the JavaScript global variables are properties of window object. All global functions are
methods of the window object.
The other objects listed above such as document, screen, history etc., are the properties of the
window object. We can access these objects as properties of the window object. We can also
access them with referencing the window object. Look at the below example snippet to access
the document object

window.document.write("Welcome to Tutorials Point");


or without window object −

document.write("Welcome to Tutorials Point");

The innerHeight and innerWidth properties of the window object are used to access the height
and width of the browser window. We will learn JavaScript window object in detail in next
chapters.

JavaScript Document Object


The document object is a property of the JavaScript window object. The whole HTML document
is represented as a document object. The document object forms HTML DOM. It is root node of
the HTML document.

The document object can be accessed as window.document or just document.

The document object provides us with many properties and methods to access the HTML
elements and manipulate them. One such method is document.getElementById() to access the
HTML element using its id.

We can access an element with id as "text" using getElementById() method and manipulate it

Example
<html>
<body>
<div id ="text">This text will be changed. </div>
<script>
// Access the element with id as text
const textDiv = document.getElementById("text");
// Change the content of this element
textDiv.innerHTML = "The text of this DIV is changed.";
</script>
</body>
</html>
JavaScript Screen Object
In JavaScript, the screen object is a property of window object. It provides us with properties that
can be used to get the information about the device window screen. We can access the screen
object as window.screen or just screen.

To get the width and height of the device screen in pixels we can use the screen.width and
screen.height properties

Example
<html>
<body>
<div id ="width">Width of the device screen is </div>
<div id ="height">Height of the device screen is </div>
<script>
document.getElementById("width").innerHTML += screen.width + " px.";
document.getElementById("height").innerHTML += screen.height + " px.";
</script>
<p> The above result may be different for different device.</p>
</body>
</html>
Output
Width of the device screen is 1536 px.
Height of the device screen is 864 px.
The above result may be different for different device.

JavaScript History Object


In JavaScript, the history object is also a property of the window object. It contains a list of the
visited URLs in the current session. The history object provides an interface to manipulate the
browser's session history.

The JavaScript history object can be accessed using window.history or just history. We can use
the methods of history object to navigate the URLs in the history list. For example to go the
previous page/URL in the history list, we can use history.back() method.

JavaScript Navigator Object


The JavaScript navigator object is also a property of the window object. Using the 'navigator'
object, you can get the browser version and name and check whether the cookie is enabled in the
browser. We can access the navigator object using window.navigator. We can also access it
without using the window prefix.
JavaScript Location Object
The JavaScript 'location' object contains various properties and methods to get and manipulate
the information of the browser's location, i.e. URL. It's also a property of JavaScript window
object.

We can use the properties and methods of the location object to manipulate the URL
information. For example, to get the host from the current URL, we can use the
window.location.host or just location.host. The host is property of the location object.

Example
<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The host of the current location is: " + location.host;
</script>
</body>
</html>
Output
The host of the current location is: www.tutorialspoint.com

JavaScript Console Object


The JavaScript console object allows us to access the debugging console of the browser. It is a
property of the JavaScript window object. It can be accessed using window.console or just
console.

The console object provides us with different methods such as console.log(). The console.log()
method is used to display the message in debugging console.
JavaScript - Window Object
The JavaScript window object represents the browser's window. In JavaScript, a 'window' object
is a global object. It contains the various methods and properties that we can use to access and
manipulate the current browser window. For example, showing an alert, opening a new window,
closing the current window, etc.

All the JavaScript global variables are properties of window object. All global functions are
methods of the window object. Furthermore, when the browser renders the content in the 'iframe,
it creates a separate 'window' object for the browser and each iframe.

Here, you will learn to use the 'window' object as a global object and use the properties and
methods of the window object.

Window Object as a Global Object

As 'window' is a global object in the web browser, you can access the global variables, functions,
objects, etc., using the window object anywhere in the code.

Let's understand it via the example below.

Example

In the below code, we have defined the 'num' global and local variables inside the function. Also,
we have defined the 'car' global object.

In the test() function, we access the global num variable's value using the 'window' object.

<html>
<body>
<div id = "output1">The value of the global num variable is: </div>
<div id = "output2">The value of the local num variable is: </div>
<div id = "output3">The value of the car object is: </div>
<script>
var num = 100;
const car = {
brand: "Honda",
model: "city",
}
function test() {
let num = 300;
document.getElementById("output1").innerHTML += window.num;
document.getElementById("output2").innerHTML += num;
document.getElementById("output3").innerHTML += car.brand;
}
test();
</script>
</body>
</html>

Output
The value of the global num variable is: 100
The value of the local num variable is: 300
The value of the car object is: Honda

You may also use the 'window' object to make a particular variable global from a particular
block.

Window Object Properties

The 'window' object contains the various properties, returning the status and information about
the current window.

Below, we have covered all properties of the 'window' object with a description. You may use
the 'window' as a reference to access these properties.

Property Name Property Description

closed When the particular window is closed, it returns true.

console It returns the window's console object.

It is used to define and access the custom elements in the browser


customElements
window.

devicePixelRatio It returns the physical pixel ratio of the device divided by CSS pixel ratio.

document It is used to access the HTML document opened in the current window.

frames It is used to get the window items like iframes, which are opened in the
current window.

frameElement It returns the current frame of the window.

history It is used to get the history object of the window.

It returns the inner height of the window without including the scroll bar,
innerHeight
toolbar, etc.

It returns the inner width of the window without including the scroll bar,
innerWidth
toolbar, etc.

length It returns the total number of iframes in the current window.

localStorage It is used to access the local storage of the current window.

location It is used to access the location object of the current window.

name It is used to get or set the name of the window.

navigator It is used to get the Navigator object of the browser.

It returns a reference to the window from where the current window is


opener
opened.

outerHeight It returns the total height of the window.

outerWidth It returns the total width of the window.

It returns the number of pixels you have scrolled the web page
pageXOffset
horizontally.

pageYOffset It returns the number of pixels you have scrolled the web page vertically.

parent It contains the reference to the parent window of the current window.
scheduler It is entry point for using the prioritized task scheduling.

screen It returns the 'screen' object of the current window.

It returns the position of the x-coordinate of the current window relative to


screenLeft
the screen in pixels.

It returns the position of the y-coordinate of the current window relative to


screenTop
the screen in pixels.

screenX It is similar to the screenLeft property.

screenY It is similar to the screenTop property.

scrollX It is similar to the pageXOffset.

scrollY It is similar to the pageYOffset.

self It is used to get the current state of the window.

sessionStorage It lets you access the 'sessionStorage' object of the current window.

speechSynthesis It allows you to use the web speech API.

visualViewPort It returns the object containing the viewport of the current window.

top It contains a reference to the topmost window.

Here, we will cover some properties with examples.

OuterHeight/OuterWidth Properties of the Window object

The outerHeight property of the window object returns the window's height, and the outerWidth
property of the window object returns the window's width.

Example
In the code below, we used the outerHeight and outerWidth property to get the dimensions of the
window. You can change the size of the window and observe changes in the value of these
properties.

<html>
<body>
<p id = "output1">The outer width of the window is: </p>
<p id = "output2">The outer height of the window is: </p>
<script>
const outerHeight = window.outerHeight;
const outerWidth = window.outerWidth;
document.getElementById("output1").innerHTML += outerWidth;
document.getElementById("output2").innerHTML += outerHeight;
</script>
</body>
</html>

Output
The outer width of the window is: 1536
The outer height of the window is: 816

ScreenLeft Property of the Window Object

The window screenLeft property returns the left position of the current window.

Example

In the output of the below code, you can see the left position of the current window in pixels.

<html>
<body>
<div id = "output">Your browser window is left by: </div>
<script>
const screenLeft = window.screenLeft;
document.getElementById("output").innerHTML += screenLeft + " px.";
</script>
</body>
</html>

Output
Your browser window is left by: 0 px.
Window Object Methods

The 'window' object also contains methods like properties to manipulate the current browser
window.

In the below table, we have covered the methods of the 'window' object with their description.
You may use 'window' as a reference to access and invoke the below methods to make the code
readable.

Method Name Method Description

alert() It is used to show the alert message to the visitors.

atob() It converts the string into the base-64 string.

blur() It removes the focus from the window.

btoa() It decodes the base-64 string in the normal string.

It cancels the animation frame scheduled using the


cancelAnimationFrame()
requestAnimationFrame() method.

It cancels a callback scheduled with the requestIdCallback()


cancelIdleCallback()
method.

It is used to clear actions specified using the setImmediate()


clearImmediate()
method.

clearInterval() It resets the timer you have set using the setInterval() method.

It stops the timeout you have set using the setTimeOut()


clearTimeout()
method.

close() It is used to close the current window.

confirm() It shows the confirm box to get the confirmation from users.
focus() It focuses on the current active window.

getComputedStyle() It returns the current window's computed CSS style.

getSelection() It returns the selection object based on the selected text range.

It returns a new MediaQueryList object, which you can use to


matchMedia()
check whether the document matches the media queries.

It changes the position of the window relative to the current


moveBy()
position.

moveTo() It changes the position of the window absolutely.

open() It opens a new window.

postMessage() It is used to send a message to a window.

print() It lets you print the window.

prompt() It allows you to show a prompt box to get user input.

It helps you to tell the browser that you want to perform an


requestAnimationFrame() animation so the browser can update the animation before the
next repaint.

It sets the callback functions to be called when the browser is


requestIdleCallback()
Idle.

resizeBy() It resizes the window by a particular number of pixels.

resizeTo() It changes the size of the window.

scrollTo() It scrolls the window to the absolute position.

scrollBy() It scrolls the window relative to the current position.


It breaks up long-running operations and runs the callback
setImmediate()
function instantly when the browser completes other operations.

setInterval() It is used to execute a particular action after every interval.

setTimeout() It is used to execute a particular action after a particular time.

stop() It stops the loading of window.

Here, we will cover some methods with examples.

JavaScript window.alert() Method

The window.alert() method allows you to show the pop-up dialog containing the message,
warning, etc. It takes the string text as an argument.

Example

In the below example, when you click the button, it will invoke the alert_func() function and
show the pop-up box at the middle top.

<html>
<body>
<button onclick = "alert_func()"> Execute Alert </button>
<script>
function alert_func() {
window.alert("The alert_func funciton is executed!");
}
</script>
</body>
</html>

JavaScript window.open() Method

The window.open() method is used to open a new window. It takes a URL as an argument,
which you need to open in a new window.

Example

In the below code, we used the window.open() method to open a new window in the browser.
You can see that the code opens the home page of the 'tutorialspoint' website in the new window.
<html>
<body>
<button onclick = "openWindow()"> Open New Window </button>
<script>
function openWindow() {
window.open("https://www.tutorialspoint.com/");
}
</script>
</body>
</html>

JavaScript window.print() Method

The window.print() method lets you print the web page.

Example

In the below code, click the button to print the web page.

<html>
<body>
<h2> Hello World! </h2>
<button onclick = "printPage()"> Print Webpage </button>
<script>
function printPage() {
window.print();
}
</script>
</body>
</html>
JavaScript - Document Object
Window Document Object
The document object is a JavaScript object that provides the access to all elements of an HTML
document. When the HTML document is loaded in the web browser, it creates
a document object. It is the root of the HTML document.

The document object contains the various properties and methods you can use to get details
about HTML elements and customize them.

The JavaScript document object is a property of the window object. It can be accessed
using window.document syntax. It can also be accessed without prefixing window object.

JavaScript Document Object Properties


The JavaScript Document Object represents the entire HTML document, and it comes with
several properties that allow us to interact with and manipulate the document. Some common
Document object properties are as follows

• document.title − Gets or sets the title of the document.


• document.URL − Returns the URL of the document.
• document.body − Returns the <body> element of the document.
• document.head − Returns the <head> element of the document.
• document.documentElement − Returns the <html> element of the document.
• document.doctype − Returns the Document Type Declaration (DTD) of the document.

These properties provide a way to access and modify different parts of the HTML document
using JavaScript.

Example: Accessing the document title


In the example below, we use the document.title property to access the property odd the
document.

<html>
<head>
<title> JavaScript - DOM Object </title>
</head>
<body>
<div id = "output">The title of the document is: </div>
<script>
document.getElementById("output").innerHTML += document.title;
</script>
</body>
</html>

Output
The title of the document is: JavaScript - DOM Object

Example: Accessing the document URL


In the example below, we have used the document.URL property to access the current URL of
the page.

<html>
<head>
<title> JavaScript - DOM Object </title>
</head>
<body>
<div id = "output">The URL of the document is: </div>
<script>
document.getElementById("output").innerHTML += document.URL;
</script>
</body>
</html>

Output
The URL of the document is:
https://www.tutorialspoint.com/javascript/javascript_document_object.htm

JavaScript Document Object Methods


The JavaScript Document Object provides us with various methods that allow us to interact with
and manipulate the HTML document. Some common Document object methods are as follows

• getElementById(id) − Returns the element with the specified ID.


• getElementsByClassName(className) − Returns a collection of elements with the specified
class name.
• getElementsByTagName(tagName) − Returns a collection of elements with the specified tag
name.
• createElement(tagName) − Creates a new HTML element with the specified tag name.
• createTextNode(text) − Creates a new text node with the specified text.
• appendChild(node) − Appends a node as the last child of a node.
• removeChild(node) − Removes a child node from the DOM.
• setAttribute(name, value) − Sets the value of an attribute on the specified element.
• getAttribute(name) − Returns the value of the specified attribute on the element.

These methods enable us to dynamically manipulate the structure and content of the HTML
document using JavaScript.

Example: Accessing HTML element using its id


In the example below, we use document.getElementById() method to access the DIV element
with id "output" and then use the innerHTML property of the HTML element to display a
message.

<html>
<body>
<div id = "result"> </div>
<script>
// accessing the DIV element.
document.getElementById("result").innerHTML +=
"Hello User! You have accessed the DIV element using its id.";
</script>
</body>
</html>

Output
Hello User! You have accessed the DIV element using its id.

Example: Adding an event to the document


In the example below, we use document.addEventListener() method to add a mouseover event to
the document.

<html>
<body>
<div id = "result">
<h2> Mouseover Event </h2>
<p> Hover over here to change background color </p>
</div>
<script>
document.addEventListener('mouseover', function () {
document.getElementById("result").innerHTML = "Mouseover event occurred.";
});
</script>
</body>
</html>

Document Object Properties List


Here, we have listed all properties of the document object.

Property Description

To get the currently focused element in the HTML


document.activeElement
document.

It sets the array of the newly constructed stylesheets to


adoptedStyleSheets
the document.

baseURI To get the absolute base URI of the document.

body To set or get the documents <body> tag.

characterSet To get the character encoding for the document.

To get a count of the number of child elements of the


childElementCount
document.

children To get all children of the document.

To get a boolean value representing whether the


compatMode
document is rendered in the standard modes.

contentType It returns the MIME type of the document.


cookie To get the cookies related to the document.

It returns the script of the document whose code is


currentScript
currently executing.

To get the window object associated with the


defaultView
document.

designMode To change the editability of the document.

dir To get the direction of the text of the document.

doctype To get the document type declaration.

documentElement To get the <html> element.

documentURI To set or get the location of the document.

To get all embedded (<embed>) elements of the


embeds
document.

firstElementChild To get the first child element of the document.

forms It returns an array of <form> elements of the document.

To get the element that is being presented in the full


fullScreenElement
screen.

It returns the boolean value, indicating whether the full


fullScreenEnabled
screen is enabled in the document.

head It returns the <head> tag of the document.

hidden It returns a boolean value, representing whether the


document is considered hidden.

images It returns the collection of the <img> elements.

lastElementChild It returns the last child element of the document.

lastModified To get the last modified date and time of the document.

links To get the collection of all <a> and <area> elements.

location To get the location of the document.

readyState To get the current state of the document.

To get the URL of the document, which has opened the


referrer
current document.

To get the collection of all <script> elements in the


scripts
document.

To get the reference to the element which scrolls the


scrollingElement
document.

It returns the style sheet list of the CSSStyleSheet


styleSheets
object.

timeLine It represents the default timeline of the document.

title To set or get the title of the document.

URL To get the full URL of the HTML document.

It returns the boolean value, representing the visibility


visibilityState
status of the document.
Document Object Methods List
The following is a list of all JavaScript document object methods −

Method Description

addEventListener() It is used to add an event listener to the document.

adoptNode() It is used to adopt the node from the other documents.

It appends the new node or HTML after the last child node of
append()
the document.

It returns the caretPosition object, containing the DOM node


caretPositionFromPoint()
based on the coordinates passed as an argument.

It closes the output stream opened using the document.open()


close()
method.

createAttribute() It creates a new attribute node.

It creates a new attribute node with the particular namespace


createAttributeNS()
URI.

createComment() It creates a new comment node with a specific text message.

createDocumentFragment() It creates a DocumentFragment node.

createElement() It creates a new element node to insert into the web page.

It is used to create a new element node with a particular


createElementNS()
namespace URI.

createEvent() It creates a new event node.


createTextNode() It creates a new text node.

elementFromPoint() It accesses the element from the specified coordinates.

It returns the array of elements that are at the specified


elementsFromPoint()
coordinates.

getAnimations() It returns the array of all animations applied on the document.

getElementById() It accesses the HTML element using the id.

getElementsByClassName() It accesses the HTML element using the class name.

getElementsByName() It accesses the HTML element using the name.

getElementsByTagName() It accesses the HTML element using the tag name.

It returns the boolean value based on whether any element or


hasFocus()
document itself is in the focus.

importNode() It is used to import the node from another document.

It removes the text nodes, which are empty, and joins other
normalize()
nodes.

open() It is used to open a new output stream.

prepand() It is used to insert the particular node before all nodes.

It is used to select the first element that matches the css selector
querySelector()
passed as an argument.

It returns the nodelist of the HTML elements, which matches the


querySelectorAll()
multiple CSS selectors.
removeEventListener() It is used to remove the event listener from the document.

replaceChildren() It replaces the children nodes of the document.

write() It is used to write text, HTML, etc., into the document.

It is similar to the write() method but writes each statement in


writeln()
the new line.
Window Screen Object
The screen object in JavaScript is a property of the 'window' object. The 'screen' object's
properties contain information about the device's screen. The screen object can be accessed by
using the window.screen syntax. We can also access it without using the window object.

Screen Object Properties


The screen object has a number of properties that provide information about the screen's
orientation, resolution, and more. These properties can be used to develop applications that are
responsive to different screen sizes and orientations.

Following are some properties of the JavaScript screen object −

• width − The width of the screen in pixels.


• height − The height of the screen in pixels.
• availWidth − The width of the screen, minus the width of the window taskbar.
• availHeight − The height of the screen, minus the height of the window taskbar.
• colorDepth − The number of bits per pixel that the screen can display.
• pixelDepth − The number of bits per pixel that the screen is actually using.

Screen Object Property Syntax


Follow the syntax below to use the property of the screen object in JavaScript −

window.screen.property;
OR
screen.property;

You may or may not use the 'window' object to access the screen object.

Example
In the example below, we access the various properties of the screen object with referencing
the screen as the property of window object.

<html>
<body>
<p> Screen Information </p>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"screen height: " + window.screen.height + "<br>" +
"screen width: " + window.screen.width + "<br>" +
"screen colorDepth: " + window.screen.colorDepth + "<br>" +
"screen pixelDepth: " + window.screen.pixelDepth + "<br>" +
"screen availHeight: " + window.screen.availHeight + "<br>" +
"screen availWidth: " + window.screen.availWidth;
</script>
</body>
</html>

Output
Screen Information
screen height: 864
screen width: 1536
screen colorDepth: 24
screen pixelDepth: 24
screen availHeight: 816
screen availWidth: 1536

Example
In the below code, we access the various properties of the screen object and observe their value.
In this example we are not referencing the window object to access the screen object.

<html>
<body>
<p> Screen Information </p>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"screen height: " + screen.height + "<br>" +
"screen width: " + screen.width + "<br>" +
"screen colorDepth: " + screen.colorDepth + "<br>" +
"screen pixelDepth: " + screen.pixelDepth + "<br>" +
"screen availHeight: " + screen.availHeight + "<br>" +
"screen availWidth: " + screen.availWidth;
</script>
</body>
</html>

Output
Screen Information
screen height: 864
screen width: 1536
screen colorDepth: 24
screen pixelDepth: 24
screen availHeight: 816
screen availWidth: 1536

Please note that we get the same information about the screen in the above two examples.

Screen Object Properties List


Below, we have covered all properties of the 'screen' object with a description. You need to use
the 'screen' as a reference to access these properties.

Property Description

availHeight It gives the height of the screen without including the taskbar.

availWidth It gives the width of the screen without including the taskbar.

colorDepth It gives the depth of the color palette to display images.

height It returns the total height of the screen.

pixelDepth It is used to get the color resolution of the screen.

width To get the total width of the screen.


Window History Object
In JavaScript, the window 'history' object contains information about the browser's session
history. It contains the array of visited URLs in the current session.

The 'history' object is a property of the 'window' object. The history property can be accessed
with or without referencing its owner object, i.e., window object.

Using the 'history' object's method, you can go to the browser's session's previous, following, or
particular URL.

History Object Methods


The window history object provides useful methods that allow us to navigate back and forth in
the history list.

Follow the syntax below to use the 'history' object in JavaScript.

window.history.methodName();
OR
history.methodName();

You may use the 'window' object to access the 'history' object.

JavaScript History back() Method


The JavaScript back() method of the history object loads the previous URL in the history list.

Syntax
Follow the syntax below to use the history back() method.

history.back();

Example
In the below code's output, you can click the 'go back' button to go to the previous URL. It works
as a back button of the browser.

<html>
<body>
<p> Click "Go Back" button to load previous URL </p>
<button onclick="goback()"> Go Back </button>
<p id = "output"> </p>
<script>
function goback() {
history.back();
document.getElementById("output").innerHTML +=
"You will have gone to previous URL if it exists";
}
</script>
</body>
</html>

JavaScript History forward() Method


The forward() method of the history object takes you to the next URL.

Syntax
Follow the syntax below to use the forward() method.

history.forward();

Example
In the below code, click the button to go to the next URL. It works as the forward button of the
browser.

<html>
<body>
<p> Click "Go Forward" button to load next URL</p>
<button onclick = "goforward()"> Go Forward </button>
<p id = "output"> </p>
<script>
function goforward() {
history.forward();
document.getElementById("output").innerHTML =
"You will have forwarded to next URL if it exists."
}
</script>
</body>
</html>
JavaScript History go() Method
The go() method of the history object takes you to the specific URL of the browser's session.

Syntax
Follow the syntax below to use the go() method.

history.go(count);

In the above syntax, 'count' is a numeric value representing which page you want to visit.

Example
In the below code, we use the go() method to move to the 2nd previous page from the current
web page.

<html>
<body>
<p> Click the below button to load 2nd previous URL</p>
<button onclick = "moveTo()"> Move at 2nd previous URL </button>
<p id = "output"> </p>
<script>
function moveTo() {
history.go(-2);
document.getElementById("output").innerHTML =
"You will have forwarded to 2nd previous URL if it exists.";
}
</script>
</body>
</html>

Example
In the below code, we use the go() method to move to the 2nd previous page from the current
web page.

Open Compiler

<html>
<body>
<p> Click the below button to load 2nd next URL</p>
<button onclick = "moveTo()"> Move at 2nd next URL </button>
<p id = "output"> </p>
<script>
function moveTo() {
history.go(2);
document.getElementById("output").innerHTML =
"You will have forwarded to 2nd next URL if it exists.";
}
</script>
</body>
</html>

Following is the complete window history object reference including both properties and
methods −

History Object Property List


The history object contains only the 'length' property.

Property Description

It returns the object's length, representing the number of URLS present in the
length
object.

History Object Methods List


The history object contains the below 3 methods.

Method Description

back() It takes you to the previous web page.

forward() It takes you to the next web page.

go() It can take you to a specific web page.


Window Navigator Object
The navigator object in JavaScript is used to access the information of the user's browser. Using
the 'navigator' object, you can get the browser version and name and check whether the cookie is
enabled in the browser.

The 'navigator' object is a property of the window object. The navigator object can be accessed
using the read-only window.navigator property.

Navigator Object Properties


There are many properties of navigator object that can be used to access the information about
the user's browser.

Syntax
Follow the syntax below to use to access a property of navigator object in JavaScript.

window.navigator.proeprty;
OR
navigator.property;

You may use the 'window' object to access the 'navigator' object.

Here, we have listed all properties of the Navigator object.

Property Description

appName It gives you a browser name.

appVersion It gives you the browser version.

appCodeName It gives you the browser code name.

cookieEnabled It returns a boolean value based on whether the cookie is enabled.

language It returns the browser language. It is supported by Firefox and Netscape only.
plugins It returns the browser plugins. It is supported by Firefox and Netscape only.

It gives you an array of Mime types. It is supported by Firefox and Netscape


mimeTypes[]
only.

platform It gives you a platform or operating system in which the browser is used.

online Returns a boolean value based on whether the browser is online.

product It gives you a browser engine.

userAgent It gives you a user-agent header of the browser.

Example: Accessing Navigator Object Properties


We used the different properties in the below code to get the browser information.

The appName property returns the browser's name, appCodeName returns the code name of the
browser, appVersion returns the browser's version, and the cookieEnabled property checks
whether the cookies are enabled in the browser.

<html>
<body>
<p> Browser Information</p>
<p id = "demo"> </p>
<script>
document.getElementById("demo").innerHTML =
"App Name: " + navigator.appName + "<br>" +
"App Code Name: " + navigator.appCodeName + "<br>" +
"App Version: " + navigator.appVersion + "<br>" +
"Cookie Enabled: " + navigator.cookieEnabled + "<br>" +
"Language: " + navigator.language + "<br>" +
"Plugins: " + navigator.plugins + "<br>" +
"mimeTypes[]: " + navigator.mimeTypes + "<br>" +
"platform: " + navigator.platform + "<br>" +
"online: " + navigator.online + "<br>" +
"product: " + navigator.product + "<br>" +
"userAgent: " + navigator.userAgent;
</script>
<p>Please note you may get different result depending on your browser. </p>
</body>
</html>

Output
Browser Information

App Name: Netscape


App Code Name: Mozilla
App Version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/102.0.0.0 Safari/537.36
Cookie Enabled: true
Language: en-US
Plugins: [object PluginArray]
mimeTypes[]: [object MimeTypeArray]
platform: Win32
online: undefined
product: Gecko
userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/102.0.0.0 Safari/537.36

Please note you may get different result depending on your browser.

Example
In the example below, we accessed the navigator object as a property of the window object. Then
we accessed different properties of this navigator object.

<html>
<body>
<p> Browser Information</p>
<p id = "demo"> </p>
<script>
document.getElementById("demo").innerHTML =
"App Name: " + window.navigator.appName + "<br>" +
"App Code Name: " + window.navigator.appCodeName + "<br>" +
"App Version: " + window.navigator.appVersion + "<br>" +
"Cookie Enabled: " + window.navigator.cookieEnabled + "<br>" +
"Language: " + window.navigator.language + "<br>" +
"Plugins: " + window.navigator.plugins + "<br>" +
"mimeTypes[]: " + window.navigator.mimeTypes + "<br>" +
"platform: " + window.navigator.platform + "<br>" +
"online: " + window.navigator.online + "<br>" +
"product: " + window.navigator.product + "<br>" +
"userAgent: " + window.navigator.userAgent;
</script>
<p>Please note you may get different result depending on your browser. </p>
</body>
</html>

Output
Browser Information

App Name: Netscape


App Code Name: Mozilla
App Version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/102.0.0.0 Safari/537.36
Cookie Enabled: true
Language: en-US
Plugins: [object PluginArray]
mimeTypes[]: [object MimeTypeArray]
platform: Win32
online: undefined
product: Gecko
userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/102.0.0.0 Safari/537.36

Please note you may get different result depending on your browser.

JavaScript Navigator Object Methods


The Navigator object contains only one method.

Method Description

javaEnabled() It checks whether the Java is enabled in the web browser.

Example: Navigator javaEnabled() Method


In the below code, we used the javaEnabled() method of the navigator object to check whether
the java is enabled in the browser.

<html>
<body>
<p id = "output"> </p>
<script>
const output = document.getElementById("output");
if (navigator.javaEnabled()) {
output.innerHTML += "Java is enabled in the browser!";
} else {
output.innerHTML += "Please, enable the Java!";
}
</script>
<p>Please note you may get different result depending on your browser. </p>
</body>
</html>

Output
Please, enable the Java!

Please note you may get different result depending on your browser.
Window Location Object
The location object in JavaScript provides information about the browser's location, i.e., URLs.
It is a built-in property of both the window and document objects. We can access it using
either window.location or document.location.

The 'location' object contains various properties and methods to get and manipulate the
information of the browser's location (URL).

JavaScript Location Object Properties

We can use the properties of the location object to get information of URL:

• hash − This property is used to set or get the anchor part of the URL.
• host − This property is used to set or get the hostname or port number of the URL.
• hostname − This property is used to set the hostname.
• href − This property is used to set or get the URL of the current window.
• origin − This property returns the protocol, domain, and port of the URL.
• pathname − This property updates or gets the path name.
• port − This property updates or gets the port of the URL.
• protocol − This property updates or gets the protocol.
• search − This property is used to set or get the query string of the URL.

Syntax
Follow the syntax below to access the location object's properties and methods −

window.location.property;

OR

location.property;

You may use the 'window' object to access the 'location' object.

Here, we have demonstrated the use of some properties of the location object with examples.
Example: Accessing location host property
The location.host property returns the host from the current URL. However, you can also
change the host using it.

In the below code, we extract the host from the URL. You can see that it returns
'www.tutorialspoint.com'.

<html>
<body>
<div id="output"></div>
<script>
const host = location.host;
document.getElementById("output").innerHTML =
"The host of the current location is: " + host;
</script>
</body>
</html>

Output
The host of the current location is: www.tutorialspoint.com

Example: Accessing location protocol property


The location.protocol propery is used to get used in the current URL. You can also use it to
update the protocol.

Try the following example to use the location.protocol property -

<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The protocol of the current location is: " + location.protocol;
</script>
</body>
</html>

Output
The protocol of the current location is: https:

Example: Accessing location hostname property


The location.hostname property returns the host name of the current URL. You can use it to the
hostname as well.

Try the following example to use location.hostname property

Open Compiler

<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The host name of the current location is: " + location.hostname;
</script>
</body>
</html>

Output
The host name of the current location is: www.tutorialspoint.com

Example: Accessing location pathname property


The location.pathname property returns the path name of the current location. You can set the
path name using it.

Open Compiler

<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The protocol of the current location is: " + location.pathname;
</script>
</body>
</html>

Output
The protocol of the current location is: /javascript/javascript_location_object.htm

JavaScript Location Object Methods


We can also use the methods of the location object to navigation to new URLs −
• assign(url) − This method loads a new document at the specified URL.
• replace(url) − This method replaces the current document with a new document at the specified
URL.
• reload() − This method reloads the current document.

JavaScript location assign() method


The location.assign() method takes the URL and changes the URL in the current window. In
short, it opens a new web page.

Syntax
Follow the syntax below to use the location.assign() method in JavaScript −

location.assign();

Example
In the below code, when you click the 'Go to home page' button, it will redirect you to the home
page of the tutorialpoint website.

Open Compiler

<html>
<body>
<div id="output"></div>
<button onclick="changePage()">Go to Home Page</button>
<script>
let output = document.getElementById("output");
function changePage() {
window.location.assign("https://www.tutorialspoint.com/");
}
</script>
</body>
</html>

Location Object Properties List


Here, we have listed all properties of the Location object.

Property Description
It is used to set or get the anchor part of
hash
the URL.

It is used to set or get the hostname or


host
port number of the URL.

hostname It is used to set the hostname.

It is used to set or get the URL of the


href
current window.

It returns the protocol, domain, and port


origin
of the URL.

pathname To update or get the path name.

port To update or get the port of the URL.

protocol To update or get the protocol.

search To set or get the query string of the URL.

Location Object Methods List


Here, we have listed all methods of the Location object.

Method Description

assign() To load resources at a particular URL.


reload() To reload the web page.

To replace the resources of the current


replace() webpage with another webpage's
resources.

toString() Returns the URL in the string format.

Window Console Object


In JavaScript, the 'console' object is a property of the window object. It allows the developers to
access the debugging console of the browser.

The console object contains the various methods used for different functionalities. In Node.js, the
console object is used to interact with the terminal.

We access the console object using the window object or without using the window object -
window.console or just console.

Console Object Methods


There are many methods available on the console object. These methods are used to perform a
number of task such testing, debugging and logging.

You may access the 'console' object methods using the following syntax −

window.console.methodName();
OR
console.methodName();

You can observe outputs in the console. To open the console, use the Ctrl + shift + I or Cmd +
shift + I key.

Below, we will cover some methods of the console object with examples.
JavaScript console.log() Method
You can use the console.log() method to print the message in the debugging console. It takes the
expression or text message as an argument.

Syntax
Follow the syntax below to use the console.log() method.

console.log(expression);

In the above syntax, the expression can be a variable, mathematical expression, string, etc.,
which you need to print in the console.

Example
In the below code, clicking the button will invoke the 'printMessage' function. The function
prints the string text and number value in the console.

Open Compiler

<html>
<body>
<h2> JavaScript console.log() Method </h2>
<button onclick = "printMessage()"> Print Message in Console </button>
<p> Please open the console before you click "Print Message in Console" button</p>
<script>
function printMessage() {
console.log("You have printed message in console!");
let num = 10;
console.log(num);
}
</script>
</body>
</html>

JavaScript console.error() Method


The console.error() method prints the error message in the console, highlighting the error with a
red background.

Syntax
Follow the syntax below to use the console.error() method.
console.error(message);

The console.error() message takes a message as an argument.

Example
In the below code, printError() function logs the error in the console when you click the button.
You can observe the error highlighted with the red background.

Open Compiler

<html>
<body>
<h2> JavaScript console.error() Method </h2>
<button onclick="printError()"> Print Error Message in Console </button>
<p> Please open the console before you click " Print Error Message in Console" button.</p>
<script>
function printError() {
console.error("Error occured in the code!");
}
</script>
</body>
</html>

JavaScript console.clear() Method


The console.clear() method clears the console.

Syntax
Follow the syntax below to use the console.clear() method.

console.clear()

Example
In the below code, we print messages to the console. After that, when you click the button, it
executes the clearConsole() function and clears the console using the console.clear() method.

Open Compiler

<html>
<body>
<h2> JavaScript console.clear() Method </h2>
<button onclick = "clearConsole()"> Clear Console </button>
<p> Please open the console before you click "Clear Console" button</p>
<script>
console.log("Hello world!");
console.log("Click the button to clear the console.");
function clearConsole() {
console.clear();
}
</script>
</body>
</html>

The console object methods list


Here, we have listed all methods of the console object.

Method Method Description

It prints the error message in the


assert() console if the assertion passed as
a parameter is false.

clear() It clears the console.

It is used to count how many


count() times the count() method is
invoked at a specific location.

It displays the error message in


error()
the console.

It is used to create a group of


group()
messages in the console.
It is used to create a new
groupCollapsed() collapsed group of messages in
the console.

groupEnd() It is used to end the group.

It shows the informational or


info() important message in the
console.

It prints the message into the


log()
output.

It shows the data in the tabular


table()
format in the console.

It is used to start the time in the


time()
console.

It stops the timer started by the


timeEnd()
time() method.

It displays the stack trace in the


trace()
console.

It shows the warning message in


warn()
the console.

You might also like