The worker API is a web API that allows us to run JavaScript code in the background thread. Whenever the web page loads in the browser, it becomes interactive after every <script> tag loads in the browser. Web workers allows users to interact with the web page without loading the whole JavaScript code in the browser. It increases the response time of the web page.
Create a Web Worker File
To create a web worker, you need to write a script in the external file, which you need to execute in a different file.
The filename should have a ‘.js’ extension.
In the below JavaScript code, we defined the counter() function. We used the setTimeout() method inside the function to call the counter() function after every 1000 milliseconds.
The important part of the code is the postMessage() method. It is used to send the data in the main thread.
functioncounter(){postMessage(data);// To send data to the main threadsetTimeout("counter()",1000);}counter();
Check for Web Worker Support
You should check that your browser supports the web worker or not before creating the web worker. You can use the typeof operator to check for this.
if(typeof(Worker)!=="undefined"){//"Web worker is supported by your browser!";}else{//"Web worker is not supported by your browser!";}
Create a Web Worker Object
After creating the external JavaScript file, you need to create a new Worker object by passing the path of the external JavaScript file as an argument, as shown below.
const workerObj =newWorker("testWorker.js");
To get the message main thread from the worker file, which we send using the postMessage() method, you can use the ‘onmessage’ event on the worker object, as shown below.
workerObj.onmessage=function(e){// Use the event.data};
Terminate the Execution of the Web Worker
When you start the execution of the web worker script, it continues the execution until you terminate the execution.
You can use the terminate() method to terminate the execution of the web worker as shown below.
workerObj.terminate();
Example: Complete Program of Web Worker
Filename: – index.html
In the below code, we have defined the startWorker() and stopWorker() functions to start and stop the execution of the worker.
In the startWorker() function, first, we check whether the browser supports the workers. After that, we check whether any instance of the worker is running. If not, we create a new instance of the Worker object using the script defined in the external file.
After that, we added the onmessage event on the worker object. So, whenever it gets data from the external script file, it prints it and performs other operations.
In the stopWorker() function, we use the terminate() method with the workerObj object to terminate the execution of the worker.
workerObj =newWorker("app.js");
workerObj.onmessage=function(event){//Getting the message from web worker
output.innerHTML +="Event data is: "+ event.data +"<br>";};}}else{
output.innerHTML +="Web worker is not supported by your browser.";}}functionstopWorker(){// To stop the web worker.if(typeof workerObj !=="undefined"){
workerObj.terminate();
workerObj =undefined;}}</script></body></html></pre>
Filename: - app.js
In the below code, we have defined the counter() function. In the counter() function, we used the setTimeOut() method to call the counter() function after every second. It also posts the data into the main thread using the postMessage() method.
var i =0;functiontimedCount(){
i = i +1;postMessage(i);setTimeout("timedCount()",500);}timedCount();
Output
To run the above code, you need to make sure that the index.html and app.js file is on the live web server. You can also use the localhost. Also, make sure to add the correct path for the app.js file in the Worker object inside the index.html file.
You can also use multiple workers in the same file to run multiple scripts in the background.
Web Worker Use Cases
The above example is simple, and in such cases, you dont need to use web workers, but it is only for demonstrations.
Here are the real-time use cases of the web workers.
When you need to execute large or complex mathematical script
In the HTML games, you may use web workers
If you want to improve the website performance
In parallel downloads, when you need to execute multiple threads
For the background data synchronization
In the machine learning
For generating reports
To process audio and videos
Web Workers and the DOM
As you need to define the scripts for the web workers in the external file, you can't use the below objects in the external file.
The window object
The document object
The parent object
However, you can use the below objects in the web workers.
JavaScript Forms API is a web API that allows us to interact with and manipulate HTML forms. It provides a set of methods and properties that are used to perform client-side form validation. Its also helpful to ensure data integrity before form submission. The forms API also referred to as Form Validation API or Constraint Validation API.
Here, we will discuss how to use various methods and properties to validate the form data using JavaScript.
Constraint Validation DOM Methods
In JavaScript, the constraint validation DOM method validates the input value by referencing the input fields. It validates the input value based on the HTML attributes you have used with the input.
After validating the input value, it returns a boolean value, representing whether the input value is valid.
Here is the list of the constraint validation methods.
Method
Description
checkValidity()
It returns a boolean value based on whether the input element contains a valid value.
setCustomValidity()
It is used to set the custom message to the validationMessage property.
Syntax
We can follow the syntax below to use the form validation methods.
In the above syntax, you need to access the element using the selector and take it as a reference of the checkValidity() or setCustomValidity() method. The setCustomValidity() method takes the string message as an argument.
Example: Using the checkValidity() method
We created the number input in the code below and set 10 to the min attribute.
In the validateInput() function, we access the number input using the id and use the checkValidity() to validate the value of the number input.
If checkValidity() method returns false, we print the validation message. Otherwise, we print the numeric value.
<html><body><input type ="number" min ="10" id ="num" required><p id ="output"></p><button onclick ="validateInput()"> Validate Number </button><script>const output = document.getElementById("output");functionvalidateInput(){let num = document.getElementById("num");if(num.checkValidity()==false){
output.innerHTML ="Please enter a number greater than 10";}else{
output.innerHTML ="Your number is "+ num.value;}}</script></body></html></pre>
Example: Using the setCustomValidity() Method
In the below code, we have defined the number input to take the users age in the input.
In the validateAge() function, we access the age input using its id and perform the custom validation on the input value. Based on the validation, we use the setCustomValidity() to set the custom validation message.
At last, we use the reportValidity() method to show the validation message set using the setCustomValidity() method.
You can enter the age below 18, and observe the validation message.
<html><body><form><label> Enter your age:</label><input type ="number" id ="age" required><br><br><button type ="button" onclick ="validateAge()"> Validate Age </button></form><div id ="message"></div><script>functionvalidateAge(){const ageInp = document.getElementById("age");const output = document.getElementById("message");const age =parseInt(ageInp.value);if(isNaN(age)){
ageInp.setCustomValidity("Please enter a valid number.");}elseif(age <18){
ageInp.setCustomValidity("You must be at least 18 years old.");}else{
ageInp.setCustomValidity("");// To remove custom error message
output.innerHTML ="Age is valid!";}
ageInp.reportValidity();// To display custom validation message}</script></body></html></pre>
Constraint Validation DOM Properties
JavaScript also contains the DOM properties for constraint validation. It is used to check the particular validation of the input value.
Here, we have listed all DOM properties that can be used for the constraint validation.
Property
Description
validity
It contains multiple properties to perform the particular validation on the input element.
validationMessage
It contains the validation message when the input element doesn't contain valid data.
willValidate
It represents whether the input data will be validated.
Properties of the 'validity' Property
In JavaScript, each element has the 'validity' property, containing multiple properties. You can use the particular property of the 'validation' property to perform the validation.
Here, we have listed all properties of the 'validity' property.
Property
Description
customError
It contains a true boolean value when you set the custom validity message.
patternMismatch
When the parent element's value doesn't match the pattern, it sets true.
rangeOverflow
It returns a boolean value based on whether the input value is greater than the max attribute's value.
rangeUnderflow
It returns a boolean value based on whether the input value is less than the min attribute's value.
stepMismatch
It returns a boolean value based on whether the step is mismatching in the numeric input.
tooLong
If the length of the input element's value is greater than the maxLength attribute's value, it returns true. Otherwise, it returns false.
typeMismatch
When the type of entered value doesn't match the 'type' attribute's value, it returns true.
valueMissing
It returns a boolean value based on whether the input element is empty.
valid
It returns true when the input element is valid.
Syntax
Users can follow the syntax below to use the properties of the validation property.
element.validity.property;
You can use the different properties of the validity property of the element to validate the input elements value.
Example
In the below code, we have defined the number input and set 300 for the value of the max attribute.
In the validateNumber() function, we use the rangeOverflow property of the validity property of the input element to check whether the input value is greater than 300.
If the rangeOverflow property returns true, we print the Number is too large. Otherwise, we print the numeric value.
<html><body><form><label> Enter Any Number:</label><input type ="number" id ="num" max ="300" required><br><br><button type ="button" onclick ="validateNumber()"> Validate Number </button></form><div id ="output"></div><script>const output = document.getElementById('output');functionvalidateNumber(){const numInput = document.getElementById('num');if(numInput.validity.rangeOverflow){
output.innerHTML ="Number is too large";}else{
output.innerHTML ="Number is valid";}}</script></body></html></pre>
Example
In the below code, we have defined the text input.
In the validateText() function, we access the string input. After that, we used the valueMissing property of the validity property to check whether the input value is empty.
In the output, you can keep the input value empty, click the validate text button and observe the error message.
<html><body><form><label> Enter any text:</label><input type ="text" id ="str" required><br><br><button type ="button" onclick ="validateText()"> Validate Text </button></form><div id ="output"></div><script>const output = document.getElementById('output');functionvalidateText(){const strInput = document.getElementById('str');if(strInput.validity.valueMissing){
output.innerHTML ="Please enter a value.";}else{
output.innerHTML ="You have entered "+ strInput.value +".";}}</script></body></html></pre>
You can also use the other properties of the validity property to validate the form input data. If the data is not valid, you can show the custom error message using the setCustomValidity() method.
The web storage API in JavaScript allows us to store the data in the user’s local system or hard disk. Before the storage API was introduced in JavaScript, cookies were used to store the data in the user’s browser.
The main problem with the cookies is that whenever browsers request the data, the server must send it and store it in the browser. Sometimes, it can also happen that attackers can attack and steal the data.
In the case of the storage API, we can store the user’s data in the browsers, which remains limited to the user’s device.
JavaScript contains two different objects to store the data in the local.
localStorage
sessionStorage
Here, we have explained the local and session storage.
The Window localStorage Object
The localStorage object allows you to store the data locally in the key-value pair format in the user’s browser.
You can store a maximum of 5 MB data in the local storage.
Whatever data you store into the local storage, it never expires. However, you can use the removeItem() method to remove the particular or clear() to remove all items from the local storage.
Syntax
We can follow the syntax below to set and get items from the browser’s local storage.
localStorage.setItem(key, value);// To set key-value pair
localStorage.getItem(key);// To get data using a key
In the above syntax, the setItem() method sets the item in the local storage, and the getItem() method is used to get the item from the local storage using its key.
Parameters
key − It can be any string.
value − It is a value in the string format.
Example
In the below code, we set the ‘fruit’ as a key and ‘Apple’ as a value in the local storage inside the setItem() function. We invoke the setItem() function when users click the button.
In the getItem() function, we get the value of the ‘fruit’ key from the local storage.
Users can click the set item button first and then get the item to get the key-value pair from the local storage.
<html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');functionsetItem(){
localStorage.setItem("fruit","Apple");}functiongetItem(){const fruitName = localStorage.getItem("fruit");
output.innerHTML ="The name of the fruit is: "+ fruitName;}</script></body></html></pre>
The localStorage doesn't allow you to store the objects, functions, etc. So, you can use the JSON.stringify() method to convert the object into a string and store it in the local storage.
Example: Storing the object in the local storage
In the below code, we have created the animal object. After that, we used the JSON.stringify() method to convert it into the string and store it as a value of the 'animal' object.
Users can click the set item button to set the object into the local storage and get the item button to get the key-value pair from the local storage.
<html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');functionsetItem(){const animal ={
Example: Removing the items from the local storage
In the below code, we set the 'name' and 'john' key-value pair in the local storage when the web page loads into the browser.
After that, users can click the get item button to get the item from local storage. It will show you the name.
You can click the get item button again after clicking the remove item button, and it will show you null as the item got deleted from the local storage.
<html><body><button onclick ="getItem()"> Get Item </button><button onclick ="removeItem()"> Remvoe Item </button><p id ="demo"></p><script>const output = document.getElementById('demo');
localStorage.setItem('name','John');functiongetItem(){
output.innerHTML ="The name of the person is: "+
localStorage.removeItem('name');
output.innerHTML ='Name removed from local storage. Now, you can\'t get it.';}</script></body></html></pre>
The Window sessionStorage Object
The sessionStorage object also allows storing the data in the browser in the key-value pair format.
It also allows you to store the data up to 5 MB.
The data stored in the session storage expires when you close the tab of the browsers. This is the main difference between the session storage and local storage. You can also use the removeItem() or clear() method to remove the items from the session storage without closing the browser's tab.
Note Some browsers like Chrome and Firefox maintain the session storage data if you re-open the browser's tab after closing it. If you close the browser window, it will definitely delete the session storage data.
Syntax
Follow the syntax below to use the session storage object to set and get data from the session storage.
sessionStorage.setItem(key, value);// To set key-value pair
sessionStorage.getItem(key);// To get data using a key
The setItem() and getItem() methods give the same result with the sessionStorage object as the localStorage object.
Parameters
key − It is a key in the string format.
value − It is a value for the key in the string format.
Example
In the below code, we used the 'username' as a key and 'tutorialspoint' as a value. We store the key-value pair in the sessionStorage object using the setItem() method.
You can click the get item button after clicking the set item button to get the key-value pair from the session storage.
<html><body><button onclick ="setItem()"> Set Item </button><button onclick ="getItem()"> Get Item </button><p id ="output"></p><script>const output = document.getElementById('output');functionsetItem(){
sessionStorage.setItem("username","tutorialspoint");}functiongetItem(){const username = sessionStorage.getItem("username");
output.innerHTML ="The user name is: "+ username;}</script></body></html></pre>
You can't store the file or image data directly in the local or session storage, but you can read the file data, convert it into the string, and store it in the session storage.
Example
In the below code, we have used the <input> element to take the image input from users. When a user uploads the image, it will call the handleImageUpload() function.
In the handleImageUpload() function, we get the uploaded image. After that, we read the image data using the FileReader and set the data into the session storage.
In the getImage() function, we get the image from the session storage and set its data as a value of the 'src' attribute of the image.
Users can upload the image first and click the get Image button to display the image on the web page.
<html><body><h2> Upload image of size less than 5MB</h2><input type ="file" id ="image" accept ="image/*" onchange ="handleImageUpload()"><div id ="output"></div><br><button onclick ="getImage()"> Get Image </button><script>// To handle image uploadfunctionhandleImageUpload(){const image = document.getElementById('image');const output = document.getElementById('output');const file = image.files[0];// Read Image fileif(file){const reader =newFileReader();
reader.onload=function(event){const data = event.target.result;// Storing the image data in sessionStorage
sessionStorage.setItem('image', data);};
reader.readAsDataURL(file);}}// Function to get imagefunctiongetImage(){let data = sessionStorage.getItem("image");
output.innerHTML =&lt;img src="${data}" alt="Uploaded Image" width="300"&gt;;}</script></body></html></pre>
You can also use the removeItem() or clear() method with the sessionStorage object like the localStorage.
Cookie Vs localStorage Vs sessionStorage
Here, we have given the difference between the cookie, localStorage, and sessionStorage objects.
Feature
Cookie
Local storage
Session storage
Storage Limit
4 KB per cookie
5 MB
5 MB
Expiry
It has an expiry date.
It never expires.
It gets deleted when you close the browser window.
Accessibility
It can be accessed on both the client and server.
It can be accessed by the client only.
It can be accessed by the client only.
Security
It can be vulnerable.
It is fully secured.
It is fully secured.
Storage Object Properties and Methods
Property/Method
Description
key(n)
To get the name of the nth key from the local or session storage.
length
To get the count of key-value pairs in the local or session storage.
getItem(key)
To get a value related to the key passed as an argument.
setItem(key, value)
To set or update key-value pair in the local or session storage.
removeItem(key)
To remove key-value pairs from the storage using its key.
clear()
To remove all key-value pairs from the local or session storage.
In JavaScript, the history API allows us to access the browsers history. It can be used to navigate through the history.
JavaScript History API provides us with methods to manipulate window history object. History object is a property of JavaScript window object. The window history object contains the array of visited URLs in the current session
The history API is very powerful tool to create may useful effects. For example, we can use it to implement history based undo redo system.
How to use JavaScript History API?
The History API is a very simple API to use. There are just a few methods and a property that you need to know about:
back() − This method navigates back to the previous page in the history.
forward() − This method navigates forward to the next page in the history.
go() − This method navigates to a specific page in the history. The number that you pass to the go() method is the relative position of the page that you want to navigate to. For example, to navigate to the previous page in the history, you would pass -1 to the go() method.
length − This property returns the length of the history list. It tells us the number of pages that have been visited by the user.
Syntax
Followings are the syntaxes to use the different methods and property of the history object −
// Load the previous URL in the history list
history.back();// Load the next URL in the history list
history.forward();// Load the page through its number
history.go(-2);// This will go to the previous 2nd page
history.go(2);// This will go to the next 2nd page// Get the length of the history listconst length = history.length;
Loading Previous Page in History List
The JavaScript history back() method of the history object loads the previous URL in the history list. We can also use the history go() method to load the previous page. The difference between these two methods is that back() method only load the immediate previous URL in history list but we can use the go() method to load any previous URL in the history list.
Example: Using back() method to load previous page
In the example below, we have used history back() method to load the previous page the user has already visited.
Please note that if you have no previous page in the history list (i.e., you have not visited any page previously), the back() method will not work.
We have implemented a back button, on clicking that we can load the previous visited page.
<html><body><p> Click "Load Previous Page" button to load previous visited page </p><button onclick="goback()"> Load Previous Page </button><p id ="output"></p><script>functiongoback(){
history.back();
document.getElementById("output").innerHTML +="You will have gone to previous visited page if it exists";}</script></body></html></pre>
Example: Using go() method to load the previous page
In the example bellow, we have used the history go() method to load to the 2nd previous visited page from the current web page.
<html><body><p> Click the below button to load 2nd previous visited page</p><button onclick ="moveTo()"> Load 2nd Previous Page </button><p id ="output"></p><script>functionmoveTo(){
history.go(-2);
document.getElementById("output").innerHTML ="You will have forwarded to 2nd previous visited page if it exists.";}</script></body></html></pre>
Loading Next Page in History List
The JavaScript history forward() method of the history object loads the next URL in the history list. We can also use the history go() method to load the next page. The difference between these two methods is that forward() method only loads the immediate next URL in history list but we can use the go() method to load any next URL in the history list.
Example: Using forward() method to load next page
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 "Load Next Page" button to load next visited page</p><button onclick ="goForward()"> Load Next Page </button><p id ="output"></p><script>functiongoForward(){
history.forward();
document.getElementById("output").innerHTML ="You will have forwarded to next visited page if it exists."}</script></body></html></pre>
Example: Using go() method to load next page
In the example below, we have used the go() method to move to the 2nd previous page from the current web page.
<html><body><p> Click the below button to load next 2nd visited page</p><button onclick ="moveTo()"> Load 2nd Next Page </button><p id ="output"></p><script>functionmoveTo(){
history.go(2);
document.getElementById("output").innerHTML ="You will have forwarded to 2nd next visited page if it exists.";}</script></body></html></pre>
Get the length of the history list
We can use the history.length proerty to get the length of history list.
Example
Try the follwing example −
<html><body><p> Click the below button to get the lenght of history list</p><button onclick ="moveTo()"> Get Lenght of History List </button><p id ="output"></p><script>const output = document.getElementById("output");functionmoveTo(){
A Web API is an application programming interface (API) for web. The concept of the Web API is not limited to JavaScript only. It can be used with any programming language. Lets learn what web API is first.
What is Web API?
The API is an acronym for the Application Programming Interface. It is a standard protocol or set of rules to communicate between two software components or systems.
A web API is an application programming interface for web.
The API provides an easy syntax to use the complex code. For example, you can use the GeoLocation API to get the coordinates of the users with two lines of code. You dont need to worry about how it works in the backend.
Another real-time example you can take is of a power system at your home. When you plug the cable into the socket, you get electricity. You dont need to worry about how electricity comes into the socket.
There are different types of web APIs, some are as follow −
Browser API (Client-Side JavaScript API)
Server API
Third Party APIs
Lets discuss each of the above type of web APIs in detail −
Browser API (Client-side JavaScript API)
The browser APIs are set of Web APIs that are provided by the browsers.
The browser API is developed on top of the core JavaScript, which you can use to manipulate the web page’s functionality.
There are multiple browser APIs available which can be used to interact with the web page.
Following is a list of common browser APIs −
Storage API − It allows you to store the data in the browser’s local storage.
DOM API − It allows you to access DOM elements and manipulate them.
History API − It allows you to get the browsers history.
Fetch API − It allows you to fetch data from web servers.
Forms API − It allows you to validate the form data.
Server API
A server API provides different functionalities to the web server. Server APIs allow developers to interact with server and access data and resources.
For example, REST API is a server API that allows us to create and consume the resources on the server. A JSON API is popular API for accessing data in JSON format. The XML API is a popular API for accessing data in XML format.
Third-party APIs
The third-party API allows you to get the data from their web servers. For example, YouTube API allows you to get the data from YouTubes web server.
Here is the list of common third-party APIs.
YouTube API − It allows you to get YouTube videos and display them on the website.
Facebook API − It allows you to get Facebook posts and display them on the website.
Telegram API − It allows you to fetch and send messages to the telegram.
Twitter API − It allows you to get tweets from Twitter.
Pinterest API − It allows you to get Pinterest posts.
You can also create and expose API endpoints for your own software. So, other applications can use your API endpoints to get the data from your web server.
Fetch API: An Example of Web API
Here is an example of how to use the fetch API. In the below example, we Fetch API to access data from a given URL (‘https://jsonplaceholder.typicode.com/todos/5). The fetch() method returns a promise that we handle using the then block. First, we convert the data into the JSON format. After that, we convert the data into the string and print it on the web page.
<html><body><h3> Fetch API: An Example of Web API</h3><div id ="output"></div><script>constURL='https://jsonplaceholder.typicode.com/todos/5';fetch(URL).then(res=> res.json()).then(data=>{
document.getElementById('output').innerHTML +="The data accessed from the API: "+"<br>"+JSON.stringify(data);});</script></body></html></pre>
JavaScript Web API List
Here, we have listed the most common web APIs.
API
Description
Console API
It is used to interact with the browsers console.
Fetch API
It is used to fetch data from web servers.
FullScreen API
It contains various methods to handle HTML elements in full-screen mode.
GeoLocation API
It contains the methods to get the users current location.
History API
It is used to navigate in the browser based on the browsers history.
MediaQueryList API
It contains methods to query media.
Storage API
It is used to access the local and session storage.
Forms API
It is used to validate the form data.
In upcoming chapters, we will cover the above APIs in details/>
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 −
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.
<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>functionprintMessage(){
console.log("You have printed message in console!");let num =10;
console.log(num);}</script></body></html></pre>
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.
<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>functionprintError(){
console.error("Error occured in the code!");}</script></body></html></pre>
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.
<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.");functionclearConsole(){
console.clear();}</script></body></html></pre>
The console object methods list
Here, we have listed all methods of the console object.
Method
Method Description
assert()
It prints the error message in the console if the assertion passed as a parameter is false.
clear()
It clears the console.
count()
It is used to count how many times the count() method is invoked at a specific location.
error()
It displays the error message in the console.
group()
It is used to create a group of messages in the console.
groupCollapsed()
It is used to create a new collapsed group of messages in the console.
groupEnd()
It is used to end the group.
info()
It shows the informational or important message in the console.
log()
It prints the message into the output.
table()
It shows the data in the tabular format in the console.
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.
document.getElementById("output").innerHTML ="The host of the current location is: "+ host;</script></body></html></pre>
Output
The host of the current location is:
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></pre>
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
<html><body><div id ="output"></div><script>
document.getElementById("output").innerHTML ="The host name of the current location is: "+ location.hostname;</script></body></html></pre>
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.
<html><body><div id ="output"></div><script>
document.getElementById("output").innerHTML ="The protocol of the current location is: "+ location.pathname;</script></body></html></pre>
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.
<html><body><div id="output"></div><button onclick="changePage()">Go to Home Page</button><script>let output = document.getElementById("output");functionchangePage(){
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.
mimeTypes[]
It gives you an array of Mime types. It is supported by Firefox and Netscape 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></pre>
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></pre>
Output
Please, enable the Java!
Please note you may get different result depending on your browser.
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.
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>functiongoback(){
history.back();
document.getElementById("output").innerHTML +="You will have gone to previous URL if it exists";}</script></body></html></pre>
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>functiongoforward(){
history.forward();
document.getElementById("output").innerHTML ="You will have forwarded to next URL if it exists."}</script></body></html></pre>
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>functionmoveTo(){
history.go(-2);
document.getElementById("output").innerHTML ="You will have forwarded to 2nd previous URL if it exists.";}</script></body></html></pre>
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 next URL</p><button onclick ="moveTo()"> Move at 2nd next URL</button><p id ="output"></p><script>functionmoveTo(){
history.go(2);
document.getElementById("output").innerHTML ="You will have forwarded to 2nd next URL if it exists.";}</script></body></html></pre>
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
length
It returns the object's length, representing the number of URLS present in the 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>
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>
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.