Category: Web APIs

  • Geolocation API

    Geolocation API

    The Geolocation API is a web API that provides a JavaScript interface to access the user’s geographical location data. A Geolocation API contains the various methods and properties that you can use to access the user’s location on your website.

    It detects the location of the user’s using the device’s GPS. The accuracy of the location depends on the accuracy of the GPS device.

    As location compromises the users’ privacy, it asks for permission before accessing the location. If users grant permission, websites can access the latitude, longitude, etc.

    Sometimes, developers need to get the user’s location on the website. For example, if you are creating an Ola, Uber, etc. type applications, you need to know the user’s location to pick them up for the ride.

    The Geolocation API allows users to share the location with a particular website.

    Real-time use cases of the Geolocation API

    Here are the real-time use cases of the Geolocation API.

    • To get the user’s location coordinates, show them on the map.
    • To tag the user’s location on the photograph.
    • To suggest nearby stores, food courts, petrol pumps, etc., to users.
    • To get the current location for the product or food delivery.
    • To pick up users for the ride from their current location.

    Using the Geolocation API

    To use the Geolocation API, you can use the ‘navigator’ property of the window object. The Navigator object contains the ‘geolocation’ property, containing the various properties and methods to manipulate the user’s location.

    Syntax

    Follow the syntax below to use the Geolocation API.

    var geolocation = window.navigator.geolocation;ORvar geolocation = navigator.geolocation;

    Here, the geolocation object allows you to access the location coordinates.

    Example: Checking the browser support

    Using the navigator, you can check whether the user’s browser supports the Geolocation.geolocation property.

    The code below prints the message accordingly whether the Geolocation is supported.

    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><div id ="output"></div><script>const output = document.getElementById("output");if(navigator.geolocation){
    
      output.innerHTML +="Geolocation is supported by your browser."}else{
      output.innerHTML +="Geolocation is not supported by your browser."}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    Geolocation is supported by your browser.
    

    Geolocation Methods

    Here are the methods of the Geolocation API.

    MethodDescription
    getCurrentPosition()It is used to retrieve the current geographic location of the website user.
    watchPosition()It is used to update the user's live location continuously.
    clearWatch()To clear the ongoing watch of the user's location using the watchPosition() method.

    The Location Properties

    The getCurrentPosition() method executes the callback function you passed as an argument. The callback function takes the object as a parameter. The parametric object contains various properties with information about the user's location.

    Here, we have listed all properties of the location object in the table below.

    PropertyTypeDescription
    coordsobjectsIt is an object you get as a parameter of the callback function of the getCurrentPosition() method. It contains the below properties.
    coords.latitudeNumberIt contains the latitude of the current location in decimal degrees. The value range is [-90.00, +90.00].
    coords.longitudeNumberIt contains the longitude of the current location in decimal degrees. The value range is [-180.00, +180.00].
    coords.altitudeNumberIt is an optional property, and it specifies the altitude estimate in meters above the WGS 84 ellipsoid.
    coords.accuracyNumberIt is also optional and contains the accuracy of the latitude and longitude estimates in meters.
    coords.altitudeAccuracyNumber[Optional]. It contains the accuracy of the altitude estimate in meters.
    coords.headingNumber[Optional]. It contains information about the device's current direction of movement in degrees counting clockwise relative to true north.
    coords.speedNumber[Optional]. It contains the device's current ground speed in meters per second.
    timestampdateIt contains the information about the time when the location information was retrieved, and the Position object created.

    Getting User's Location

    You can use the getCurrentPosition() method to get the user's current location.

    Syntax

    Users can follow the syntax below to get the user's current position using the getCurrentPosition() method.

    navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

    Parameters

    The getCurrentPosition() object takes 3 parameters.

    • successCallback − This function will be called when the method successfully retrieves the user's location.
    • errorCallback − This function will be called when the method throws an error while accessing the user's location.
    • Options − It is an optional parameter. It is an object containing properties like timeout, maxAge, etc.

    Permitting the website to access your location

    Whenever any website tries to access your location, the browser pops up the permission alert box. If you click the 'allow, it can fetch your location details. Otherwise, it throws an error.

    You can see the permission pop-up in the image below.

    Example

    In the below code, we use the getCurrentPosition() method to get the user's location. The method calls the getCords() function to get the current location.

    In the getCords() function, we print the value of the various properties of the cords object.

    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> Location Information </h3><button onclick ="findLocation()"> Find Location </button><p id ="output"></p><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){
    
        navigator.geolocation.getCurrentPosition(getCords);//}else{
        output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
      output.innerHTML +="The current position is: &lt;br&gt;";
      output.innerHTML +="Latitude: "+ coords.coords.latitude +"&lt;br&gt;";
      output.innerHTML +="Longitude: "+ coords.coords.longitude +"&lt;br&gt;";
      output.innerHTML +="Accuracy: "+ coords.coords.accuracy +"&lt;br&gt;";
      output.innerHTML +="Altitude: "+ coords.coords.altitude +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Geolocation Errors

    The getCurrentPosition() method takes the callback function as a second parameter to handle the error. The callback function can have an error object as a parameter.

    In the below cases, an error can occur.

    • When the user has denied access to the location.
    • When location information is not available.
    • When the request for the location is timed out.
    • It can also generate any random error.

    Here is the list of properties of the error object.

    PropertyTypeDescription
    codeNumberIt contains the error code.
    messageStringIt contains the error message.

    Here is the list of different error codes.

    CodeConstantDescription
    0UNKNOWN_ERRORWhen methods of the geolocation object cant retrieve the location, it returns the code 0 for unknown error.
    1PERMISSION_DENIEDWhen the user has denied the permission to access the location.
    2POSITION_UNAVAILABLEWhen it cant find the location of the device.
    3TIMEOUTWhen the method of the geolocation object cant find the users position.

    Example: Error Handling

    We use the getCurrentPosition() method in the findLocation() function in the below code. We have passed the errorCallback() function as a second parameter of the getCurrentPosition() method to handle the errors.

    In the errorCallback() function, we use the switch case statement to print the different error messages based on the error code.

    When you click the Find Location button, it will show you a pop-up asking permission to access the location. If you click on the 'block, it will show you an error.

    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><div id ="output"></div><button onclick ="findLocation()"> Find Location </button><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){
    
    navigator.geolocation.getCurrentPosition(getCords, errorCallback);//}else{
    output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
    output.innerHTML +="The current position is: <br>"; output.innerHTML +="Latitude: "+ coords.coords.latitude +"<br>"; output.innerHTML +="Longitude: "+ coords.coords.longitude +"<br>";}// Function to handle errorfunctionerrorCallback(err){switch(err.code){case err.PERMISSION_DENIED:
      output.innerHTML +="You have denied to access your device's location";break;case err.POSITION_UNAVAILABLE:
      output.innerHTML +="Your position is not available.";break;case err.TIMEOUT:
      output.innerHTML +="Request timed out while fetching your location.";break;case err.UNKNOWN_ERROR:
      output.innerHTML +="Unknown error occurred while fetching your location.";break;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Geolocation Options

    The getCurrentPosition() method takes the object containing the options as a third parameter.

    Here is the list of options you can pass as a key to the option object.

    PropertyTypeDescription
    enableHighAccuracyBooleanIt represents whether you want to get the most accurate location.
    timeoutNumberIt takes a number of milliseconds as a value for that much time you want to wait to fetch the location data.
    maximumAgeNumberIt takes the milliseconds as a value, specifying the maximum age of the cached location.

    Example

    The below code finds the most accurate location. Also, we have set milliseconds to the maximumAge, and timeout properties of the options object.

    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><div id ="output"></div><button onclick ="findLocation()"> Find Location </button><script>const output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){// Options for geolocationconst options ={
    
        enableHighAccuracy:true,
        timeout:5000,
        maximumAge:0};
      navigator.geolocation.getCurrentPosition(getCords, errorfunc, options);}else{
      output.innerHTML +="Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCords(coords){
    output.innerHTML +="The current position is: &lt;br&gt;";
    output.innerHTML +="Latitude: "+ coords.coords.latitude +"&lt;br&gt;";
    output.innerHTML +="Longitude: "+ coords.coords.longitude +"&lt;br&gt;";}functionerrorfunc(err){
    output.innerHTML +="The error message is - "+ err.message +"&lt;br&gt;";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Watching the Current Location of the User

    The watchPosition() method allows you to track the live location of users. It returns the ID, which we can use with the clearWatch() method when you want to stop tracking the user.

    Syntax

    Follow the syntax below to use the watchPosition() method to track the live location of users.

    var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)

    The errorCallback and options are optional arguments.

    If you want to stop tracking the user, you can follow the syntax below.

    navigator.geolocation.clearWatch(id);

    The clearWatch() method takes the id returned by the watchPosition() method as an argument.

    Example

    In the below code, we used the geolocation object's watchPosition () method to get the user's continuous position.

    We used the getCords() function as a callback of the watchPosition() method, where we print the latitude and longitude of the user's position.

    In the findLocation() method, we used the setTimeOut() method to stop tracking after 30 seconds.

    In the output, you can observe that the code prints the user's position multiple times.

    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><button onclick ="findLocation()"> Find Location </button><div id ="output"></div><script>let output = document.getElementById("output");functionfindLocation(){if(navigator.geolocation){let id = navigator.geolocation.watchPosition(getCoords);setTimeout(function(){
    
          navigator.geolocation.clearWatch(id);
          output.innerHTML +="&lt;br&gt;Tracking stopped!";},30000);// Stop tracking after 30 seconds.}else{
        output.innerHTML +="&lt;br&gt;Geo Location is not supported by this browser!";}}// Callback functionfunctiongetCoords(location){let latitude = location.coords.latitude;let longitude = location.coords.longitude;
      output.innerHTML +=&amp;lt;br&amp;gt; Latitude: ${latitude}, Longitude: ${longitude};}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Fetch API

    What is a Fetch API?

    The JavaScript Fetch API is a web API that allows a web browser to make HTTP request to the web server. In JavaScript, the fetch API is introduced in the ES6 version. It is an alternative of the XMLHttpRequest (XHR) object, used to make a ‘GET’, ‘POST’, ‘PUT’, or ‘DELETE’ request to the server.

    The window object of the browser contains the Fetch API by default.

    The Fetch API provides fetch() method that can be used to access resources asynchronously across the web.

    The fetch() method allows you to make a request to the server, and it returns the promise. After that, you need to resolve the promise to get the response received from the server.

    Syntax

    You can follow the syntax below to use the fetch() API in JavaScript

    window.fetch(URL,[options]);ORfetch(URL,[options]);

    Parameters

    The fetch() method takes two parameters.

    • URL − It is an API endpoint where you need to make a request.
    • [options] − It is an optional parameter. It is an object containing the method, headers, etc., as a key.

    Return value

    It returns the promise, which you can solve using the ‘then…catch’ block or asynchronously.

    Handling Fetch() API Response with ‘then…catch’ Block

    The JavaScript fetch() API returns the promise, and you can handle it using the ‘then…catch’ block.

    Follow the syntax below to use the fetch() API with the ‘then…catch’ block.

    fetch(URL).then(data=>{// Handle data}).catch(err=>{// Handle error})

    In the above syntax, you can handle the ‘data’ in the ‘then’ block and the error in the ‘catch’ block.

    Example

    In the below code, we fetch the data from the given URL using the fetch() API. It returns the promise 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><div id ="output"></div><script>const output = document.getElementById('output');constURL='https://jsonplaceholder.typicode.com/todos/5';fetch(URL).then(res=> res.json()).then(data=>{
    
         output.innerHTML +="The data from the API is: "+"&lt;br&gt;";
      	 output.innerHTML +=JSON.stringify(data);});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The data from the API is:
    {"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}
    

    Handling Fetch() API Response Asynchronously

    You can also solve the promise returned by the fetch() API asynchronously using the async/await keyword.

    Syntax

    Users can follow the syntax below to use the async/await keywords with the fetch() API.

    let data =awaitfetch(URL);
    data =await data.json();

    In the above syntax, we used the 'await' keyword to stop the code execution until the promise gets fulfilled. After that, we again used the 'await' keyword with the data.json() to stop the execution of the function until it converts the data into the JSON format.

    Example

    In the code below, we have defined the getData()asynchronous function to fetch the to-do list data from the given URL using the fetch() API. After that, we convert the data into JSON and print the output on the web page.

    <html><body><div id ="output"></div><script>asyncfunctiongetData(){let output = document.getElementById('output');letURL='https://jsonplaceholder.typicode.com/todos/6';let data =awaitfetch(URL);
    
      data =await data.json();
      output.innerHTML +="The data from the API is: "+"&lt;br&gt;";
      output.innerHTML +=JSON.stringify(data);}getData();&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The data from the API is:
    {"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}
    

    Options with Fetch() API

    You can also pass the object as a second parameter containing the options as a key-value pair.

    Syntax

    Follow the syntax below to pass the options to the Fetch() API.

    fetch(URL,{
    
    method:"GET",
    body:JSON.stringify(data),
    mode:"no-cors",
    cache:"no-cache",
    credentials:"same-origin",
    headers:{"Content-Type":"application/json",},
    redirect:"follow",})</pre>

    Options

    Here, we have given some options to pass to the fetch() API.

    • method − It takes the 'GET', 'POST', 'PUT', and 'DELETE' methods as a value based on what kind of request you want to make.
    • body − It is used to pass the data into the string format.
    • mode − It takes the 'cors', 'no-cors', 'same-origin', etc. values for security reasons.
    • cache − It takes the '*default', 'no-cache', 'reload', etc. values.
    • credentials − It takes 'same-origin', 'omit', etc. values.
    • headers − You can pass the headers with this attribute to the request.
    • redirect − If you want users to redirect to the other web page after fulfilling the request, you can use the redirect attribute.

    Example: Making a GET Request

    In the below code, we have passed the "GET" method as an option to the fetch() API.

    Fetch () API fetches the data from the given API endpoint.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");let options ={
    
         method:'GET',}letURL="https://dummy.restapiexample.com/api/v1/employee/2";fetch(URL, options).then(res=&gt; res.json()).then(res=&gt;{
            output.innerHTML +="The status of the response is - "+ res.status +"&lt;br&gt;";
            output.innerHTML +="The message returned from the API is - "+ res.message +"&lt;br&gt;";
            output.innerHTML +="The data returned from the API is - "+JSON.stringify(res.data);}).catch(err=&gt;{
            output.innerHTML +="The error returned from the API is - "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the response is - success
    The message returned from the API is - Successfully! Record has been fetched.
    The data returned from the API is - {"id":2,"employee_name":"Garrett Winters","employee_salary":170750,"employee_age":63,"profile_image":""}
    

    Example (Making a POST Request)

    In the below code, we have created the employee object containing the emp_name and emp_age properties.

    Also, we have created the options object containing the method, headers, and body properties. We use the 'POST' as a value of the method and use the employee object after converting it into the string as a body value.

    We make a POST request to the API endpoint using the fetch() API to insert the data. After making the post request, you can see the response on the web page.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");let employee ={"emp_name":"Sachin","emp_age":"30"}let options ={
    
         method:'POST',// To make a post request
         headers:{'Content-Type':'application/json;charset=utf-8'},
         body:JSON.stringify(employee)}letURL="https://dummy.restapiexample.com/api/v1/create";fetch(URL, options).then(res=&gt; res.json())// Getting response.then(res=&gt;{
            output.innerHTML +="The status of the request is : "+ res.status +"&lt;br&gt;";
            output.innerHTML +="The message returned from the API is : "+ res.message +"&lt;br&gt;";
            output.innerHTML +="The data added is : "+JSON.stringify(res.data);}).catch(err=&gt;{
            output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the request is : success
    The message returned from the API is : Successfully! Record has been added.
    The data added is : {"emp_name":"Sachin","emp_age":"30","id":7425}
    

    Example (Making a PUT Request)

    In the below code, we have created the 'animal' object.

    Also, we have created the options object. In the options object, we added the 'PUT' method, headers, and animal objects as a body.

    After that, we use the fetch() API to update the data at the given URL. You can see the output response that updates the data successfully.

    <html><body><div id ="output"></div><script>let output = document.getElementById("output");let animal ={"name":"Lion","color":"Yellow","age":10}let options ={
    
         method:'PUT',// To Update the record
         headers:{'Content-Type':'application/json;charset=utf-8'},
         body:JSON.stringify(animal)}letURL="https://dummy.restapiexample.com/api/v1/update/3";fetch(URL, options).then(res=&gt; res.json())// Getting response.then(res=&gt;{
            console.log(res);
            output.innerHTML +="The status of the request is : "+ res.status +"&lt;br&gt;";
            output.innerHTML +="The message returned from the API is : "+ res.message +"&lt;br&gt;";
            output.innerHTML +="The data added is : "+JSON.stringify(res.data);}).catch(err=&gt;{
            output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the request is : success
    The message returned from the API is : Successfully! Record has been updated.
    The data added is : {"name":"Lion","color":"Yellow","age":10}
    

    Example (Making a DELETE Request)

    In the below code, we make a 'DELETE' request to the given URL to delete the particular data using the fetch() API. It returns the response with a success message.

    <html><body><div id ="output"></div><script>const output = document.getElementById("output");let options ={
    
         method:'DELETE',// To Delete the record}letURL=" https://dummy.restapiexample.com/api/v1/delete/2";fetch(URL, options).then(res=&gt; res.json())// After deleting data, getting response.then(res=&gt;{
    output.innerHTML +="The status of the request is : "+ res.status +"<br>"; output.innerHTML +="The message returned from the API is : "+ res.message +"<br>"; output.innerHTML +="The data added is - "+JSON.stringify(res.data);}).catch(err=>{
    	    output.innerHTML +="The error returned from the API is : "+JSON.stringify(err);})&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    The status of the request is : success
    The message returned from the API is : Successfully! Record has been deleted
    The data added is - "2"
    

    Advantages of Using the Fetch() API

    Here are some benefits of using the fetch() API to interact with third-party software or web servers.

    • Easy Syntax − It provides a straightforward syntax to make an API request to the servers.
    • Promise-based − It returns the promise, which you can solve asynchronously using the 'then...catch' block or 'async/await' keywords.
    • JSON handling − It has built-in functionality to convert the string response data into JSON data.
    • Options − You can pass multiple options to the request using the fetch() API.
  • Worker API

    Web Worker API

    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.

    <html><body><button onclick ="startWorker()"> Start Counter </button><button onclick ="stopWorker()"> Stop Counter </button><div id ="output"></div><script>let output = document.getElementById('output');let workerObj;functionstartWorker(){if(typeof(Worker)!=="undefined"){if(typeof workerObj ==="undefined"){
    
            workerObj =newWorker("app.js");
            workerObj.onmessage=function(event){//Getting the message from web worker
               output.innerHTML +="Event data is: "+ event.data +"&lt;br&gt;";};}}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;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.

    Web Worker API

    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.

    • The location object
    • The navigator object
    • The Application Cache
    • Importing external script using importScripts()
    • XMLHttpRequest
  • Forms API

    Web Forms API

    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.

    MethodDescription
    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.

    element.checkValidity()OR
    element.setCustomValidity(message);

    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;}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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 &lt;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}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.

    PropertyDescription
    validityIt contains multiple properties to perform the particular validation on the input element.
    validationMessageIt contains the validation message when the input element doesn't contain valid data.
    willValidateIt 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.

    PropertyDescription
    customErrorIt contains a true boolean value when you set the custom validity message.
    patternMismatchWhen the parent element's value doesn't match the pattern, it sets true.
    rangeOverflowIt returns a boolean value based on whether the input value is greater than the max attribute's value.
    rangeUnderflowIt returns a boolean value based on whether the input value is less than the min attribute's value.
    stepMismatchIt returns a boolean value based on whether the step is mismatching in the numeric input.
    tooLongIf the length of the input element's value is greater than the maxLength attribute's value, it returns true. Otherwise, it returns false.
    typeMismatchWhen the type of entered value doesn't match the 'type' attribute's value, it returns true.
    valueMissingIt returns a boolean value based on whether the input element is empty.
    validIt 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";}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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 +".";}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.

  • Storage API

    What is Web Storage API?

    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;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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 ={
    
            name:"Lion",
            color:"Yellow",
            food:"Non-vegetarian",}
         localStorage.setItem("animal",JSON.stringify(animal));}functiongetItem(){const animal = localStorage.getItem("animal");
         output.innerHTML ="The animal object is: "+ animal;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    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.getItem('name');}functionremoveItem(){
         localStorage.removeItem('name');
         output.innerHTML ='Name removed from local storage. Now, you can\'t get it.';}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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 =&amp;lt;img src="${data}" alt="Uploaded Image" width="300"&amp;gt;;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.

    FeatureCookieLocal storageSession storage
    Storage Limit4 KB per cookie5 MB5 MB
    ExpiryIt has an expiry date.It never expires.It gets deleted when you close the browser window.
    AccessibilityIt 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.
    SecurityIt can be vulnerable.It is fully secured.It is fully secured.

    Storage Object Properties and Methods

    Property/MethodDescription
    key(n)To get the name of the nth key from the local or session storage.
    lengthTo 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.
  • History API

    Web History API

    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";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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."}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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.";}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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(){
    
         output.innerHTML = history.length;}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>
  • Web API

    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: "+"&lt;br&gt;"+JSON.stringify(data);});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    JavaScript Web API List

    Here, we have listed the most common web APIs.

    APIDescription
    Console APIIt is used to interact with the browsers console.
    Fetch APIIt is used to fetch data from web servers.
    FullScreen APIIt contains various methods to handle HTML elements in full-screen mode.
    GeoLocation APIIt contains the methods to get the users current location.
    History APIIt is used to navigate in the browser based on the browsers history.
    MediaQueryList APIIt contains methods to query media.
    Storage APIIt is used to access the local and session storage.
    Forms APIIt is used to validate the form data.

    In upcoming chapters, we will cover the above APIs in details/>