Author: saqibkhan

  • Modernizr

    Modernizr is a small JavaScript Library that detects whether a particular feature of web technologies is available or not in the users browser. It provides an easy way to detect any new feature so that we can take corresponding action based on the browsers capabilities. For example, if a browser does not support a video feature then we can display a simple message regarding the same. We can also create CSS rules based on the feature availability and these rules would be applied automatically on the webpage if the browser does not support a new feature.

    Before we start using Modernizr, we are required to include its javascript library in our HTML page header as follows −

    <script src="modernizr.min.js" type="text/javascript"></script>

    Instance

    Following is the simple syntax to handle supported and non supported features −

    <!-- In your CSS: -->
    .no-audio #music {
       display: none; <!-- to not show Audio options -->
    }
    .audio #music button {
      <!-- Style the Play and Pause buttons nicely -->
    }
    
    <!-- In your HTML: --><div id="music"><audio><source src="audio.ogg" /><source src="audio.mp3" /></audio><button id="play">Play</button><button id="pause">Pause</button></div>

    Here it is notable that you need to prefix “no-” to every feature/property you want to handle for the browser which does not support them.

    Following code snippet can be added to detect a particular feature through Javascript −

    if (Modernizr.audio) {
       <!-- properties for browsers that
       support audio -->
    }
    
    else{
       <!-- properties for browsers that
       does not support audio -->
    }
    

    Features detected by Modernizr

    Following is the list of features which can be detected by Modernizr −

    FeatureCSS PropertyJavaScript Check
    @font-face.fontfaceModernizr.fontface
    Canvas.canvasModernizr.canvas
    Canvas Text.canvastextModernizr.canvastext
    HTML Audio.audioModernizr.audio
    HTML Audio formatsNAModernizr.audio[format]
    HTML Video.videoModernizr.video
    HTML Video FormatsNAModernizr.video[format]
    rgba().rgbaModernizr.rgba
    hsla().hslaModernizr.hsla
    border-image.borderimageModernizr.borderimage
    border-radius.borderradiusModernizr.borderradius
    box-shadow.boxshadowModernizr.boxshadow
    Multiple backgrounds.multiplebgsModernizr.multiplebgs
    opacity.opacityModernizr.opacity
    CSS Animations.cssanimationsModernizr.cssanimations
    CSS Columns.csscolumnsModernizr.csscolumns
    CSS Gradients.cssgradientsModernizr.cssgradients
    CSS Reflections.cssreflectionsModernizr.cssreflections
    CSS 2D Transforms.csstransformsModernizr.csstransforms
    CSS 3D Transforms.csstransforms3dModernizr.csstransforms3d
    CSS Transitions.csstransitionsModernizr.csstransitions
    Geolocation API.geolocationModernizr.geolocation
    Input TypesNAModernizr.inputtypes[type]
    Input AttributesNAModernizr.input[attribute]
    localStorage.localstorageModernizr.localstorage
    sessionStorage.sessionstorageModernizr.sessionstorage
    Web Workers.webworkersModernizr.webworkers
    applicationCache.applicationcacheModernizr.applicationcache
    SVG.svgModernizr.svg
    SVG Clip Paths.svgclippathsModernizr.svgclippaths
    SMIL.smilModernizr.smil
    Web SQL Database.websqldatabaseModernizr.websqldatabase
    IndexedDB.indexeddbModernizr.indexeddb
    Web Sockets.websocketsModernizr.websockets
    Hashchange Event.hashchangeModernizr.hashchange
    History Management.historymanagementModernizr.historymanagement
    Drag and Drop.draganddropModernizr.draganddrop
    Cross-window Messaging.crosswindowmessagingModernizr.crosswindowmessaging
    addTest() Plugin APINAModernizr.addTest(str,fn)
  •  QR Code

    A QR is an abbreviation, stands for Quick Response code which is a form of 2-D matrix barcode. If we take a closer look at a QR Code closely, we will clearly see that it consists of black squares on a white background. It can store various types of data including phone numbers, URLs of a website and any type of text up to 4000 characters.

    The below QR Generator tool has been developed specifically for the readers of tutorialspoint. To use this simple tool, simply enter your URL or any characters in the text box and the QR code for that character will be automatically generated.

  • Velocity Draw

    The HTML velocity draw is a tool used for creating and manipulating animations on a web page. It has some set of properties like opacity, size and position that control the animation.

    In the below velocity draw tool, we can draw a variety of visual graphics by changing the position of cursor, opacity and density. To change the opacity and density, drag the circle in the left corner up or down.

    • opacity: 25%
    • density: 422
    • point cache: 14
    • pan: space + drag
    • lock opacity: hold shift
    • clear cache: ctrl + del
    • save: ctrl + shift + s
    • velocity skewing disabled
  • Web Slide Desk

    A slide is a single page of a presentation. Collectively, a group of slides may be known as a slide desk.

    Example

    Let’s look at the following example, where we are going to create an HTML web slide desk.

    Open Compiler

    <!DOCTYPE html><html><style>
    
      body {
         font-family: verdana;
         background-color: #F4ECF7;
         color: #DE3163;
      }
      .x {
         display: none;
         text-align: center;
         padding: 123px;
      }
      .x.active {
         display: block;
      }
      .prev,
      .next {
         position: absolute;
         top: 40%;
         background-color: #EAFAF1;
         color: #DE3163;
         padding: 10px 20px;
         cursor: pointer;
         border: none;
         transition: background-color 0.2s;
      }
      .prev:hover,
      .next:hover {
         background-color: #DFFF00;
      }
      .prev {
         left: 10px;
      }
      .next {
         right: 10px;
      }
    </style><body><div class="x active"><h1>SLIDE 1</h1><p>HELLO</p></div><div class="x"><h1>SLIDE 2</h1><p>WELCOME</p></div><div class="x"><h1>SLIDE 3</h1><p>THANK YOU.!</p></div><button class="prev" onclick="prevSlide()">Previous</button><button class="next" onclick="nextSlide()">Next</button><script>
      let a = 0;
      const slides = document.querySelectorAll('.x');
      function showSlide(n) {
         slides[a].classList.remove('active');
         a = (n + slides.length) % slides.length;
         slides[a].classList.add('active');
      }
      function prevSlide() {
         showSlide(a - 1);
      }
      function nextSlide() {
         showSlide(a + 1);
      }
      showSlide(a);
    </script></body></html>

    When we run the above code, it will generate an output consisting of the button along with a slide containing the text in it displayed on the webpage.

  • Custom HTML Video Player

    Creating a Custom Video Player in HTML

    We can create a custom HTML video player using the HTML <video> tag, some other HTML tags for design, CSS, and JavaScript. HTML features include native video support without the need for Flash.

    In this tutorial, we will learn how we can create a video player in HTML. The code provided in this tutorial works based on HTML, CSS, and JavaScript. You can drag and drop your local video files into the container.

    We recommend going through the chapter to learn about embedding Video Player in HTML.

    Complete Code to Create a Custom HTML Video Player

    Let’s look at the following example, where we are going to allow the user to upload the local video file:

    Open Compiler

    <!DOCTYPE html><html><head><style>
    
      body {
         background-color: #E8DAEF;
         text-align: center;
      }
    </style></head><body><input type="file" accept="video/*"><br><video controls height="300" width="500"></video><script>
      (function localFileVideoPlayer() {
         'WELCOME'
         var x = function(event) {
            var vid = this.files[0]
            var a = window.a || window.webkitURL
            var y = a.createObjectURL(vid)
            var videoNode = document.querySelector('video')
            videoNode.src = y
         }
         var z = document.querySelector('input')
         z.addEventListener('change', x, false)
      })()
    </script></body></html>

    When we run the above code, it will generate an output displaying the video controls, allowing the user to upload the local video file on the webpage.

    Capture and Play Video Using Camera Accessibility

    Below is a recorder that works based on HTML, CSS, and JavaScript. Before entering this page, the user must allow camera accessibility to cost images.

    Example

    Consider the following example, where we are going to use the user camera and capture the image:

    Open Compiler

    <html><head><style>
    
      body {
         text-align: center;
         background-color: #EAFAF1;
      }
    </style></head><body><video id="vid" controls autoplay></video><canvas id="mytutorial" width="600" height="300" style="border:1px solid #d3d3d3;"></canvas><button id="snapshot">Take Picture</button><script>
      const x = document.getElementById('vid');
      const mycanvas = document.getElementById('mytutorial');
      const y = mycanvas.getContext('2d');
      const clickpicture = document.getElementById('snapshot');
      const a = {
         video: true,
      };
      clickpicture.addEventListener('click', () =&gt; {
         y.drawImage(x, 1, 0, mycanvas.width, mycanvas.height);
      });
      navigator.mediaDevices.getUserMedia(a).then((stream) =&gt; {
         x.srcObject = stream;
      });
    </script></body></html>

    On running the above code, the output window will pop up, displaying the canvas along with a capture button on the webpage.

  • HTML Audio Player with Visualizer

    HTML Audio Player with Visualizer

    HTML features include native audio and video support without the need for Flash. The below code works based on HTML, CSS, and JavaScript. You can drag and drop your local MP3 files into the container.

    We recommend going through these chapters to learn about embedding audio in HTML and the <audio> tag.

    Code Files to Create HTML Audio Player

    Let’s look at the following example, where we are going to create a local audio visualizer

    1. HTML File

    <!DOCTYPE html><html><style>
    
      #instructions {
         width: 100%;
         text-align: center;
         top: 50%;
         margin-top: -100px;
         color: #DE3163;
      }
      #container {
         position: absolute;
         width: 100%;
         height: 100%;
         background: #D5F5E3;
      }
      #canvas-container {
         width: 600px;
         height: 600px;
         margin: auto;
         position: relative;
         top: 50%;
         margin-top: -263px;
         margin-right: -61px;
      }
      #canvas-copy {
         opacity: 0.05;
         -webkit-transform: scaleY(-1);
         margin-top: -6px;
      }
    </style><body><div id="container"><div id="canvas-container"><canvas width=600 height=300 id="canvas"></canvas><canvas width=600 height=300 id="canvas-copy"></canvas></div><div id="instructions"><a href="https://www.tutorialspoint.com/index.htm" align="center"> Tutorials Point</a><h2 style="font-family:verdana"> Drag Your Local MP3 Files </h2></div><div id="button"></div></div><script src="js.html"></script></body></html>

    Now, we are going to create a JavaScript file with the name mentioned in the above HTML file.

    2. JavaScript File

    <script>(function(){var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    
      window.requestAnimationFrame = requestAnimationFrame;})();
    window.onload=function(){var element = document.getElementById('container')dropAndLoad(element, init,"ArrayBuffer")}functiondropAndLoad(dropElement, callback, readFormat){var readFormat = readFormat ||"DataUrl"
      dropElement.addEventListener('dragover',function(e){
         e.stopPropagation()
         e.preventDefault()
         e.dataTransfer.dropEffect ='copy'},false)
      dropElement.addEventListener('drop',function(e){
         e.stopPropagation()
         e.preventDefault()loadFile(e.dataTransfer.files[0])},false)functionloadFile(files){var file = files
         var reader =newFileReader()
         reader.onload=function(e){callback(e.target.result)}
         reader['readAs'+ readFormat](file)}}functioninit(arrayBuffer){
      document.getElementById('instructions').innerHTML ='Audio Loading'
      window.audioCtx =newAudioContext()
      window.analyser = audioCtx.createAnalyser()if(window.source) source.noteOff(0)
      audioCtx.decodeAudioData(arrayBuffer,function(buffer){
         window.source = audioCtx.createBufferSource()
         source.buffer = buffer
         source.connect(analyser)
         analyser.connect(audioCtx.destination)
         source.start(0)var viz =newsimpleViz()newvisualizer(viz['update'], analyser)
         document.getElementById('instructions').innerHTML =''})}functionvisualizer(visualization, analyser){var self =thisthis.visualization = visualization
      var last = Date.now()varloop=function(){var dt = Date.now()- last
         var byteFreq =newUint8Array(analyser.frequencyBinCount)
         analyser.getByteFrequencyData(byteFreq)
         last = Date.now()
         self.visualization(byteFreq, dt)requestAnimationFrame(loop)}requestAnimationFrame(loop)}functionsimpleViz(canvas){var self =thisthis.canvas = document.getElementById('canvas')this.ctx =this.canvas.getContext("2d")this.copyCtx = document.getElementById('canvas-copy').getContext("2d")this.ctx.fillStyle ='#fff'this.barWidth =10this.barGap =4this.bars = Math.floor(this.canvas.width /(this.barWidth +this.barGap))this.update=function(byteFreq){
         self.ctx.clearRect(0,0, self.canvas.width, self.canvas.height)var step = Math.floor(byteFreq.length / self.bars)for(var i =0; i &lt; self.bars; i++){var barHeight = byteFreq[i * step]
            self.ctx.fillRect(i *(self.barWidth + self.barGap), self.canvas.height - barHeight, self.barWidth, barHeight)
            self.copyCtx.clearRect(0,0, self.canvas.width, self.canvas.height)
            self.copyCtx.drawImage(self.canvas,0,0)}}}&lt;/script&gt;</pre>

    Complete Code to Create HTML Audio Player

    Let's combine both the file and observe the output we are going to get.

    Open Compiler

    <!DOCTYPE html><html><style>
    
      #instructions {
         width: 100%;
         text-align: center;
         top: 50%;
         margin-top: -100px;
         color: #DE3163;
      }
      #container {
         position: absolute;
         width: 100%;
         height: 100%;
         background: #D5F5E3;
      }
      #canvas-container {
         width: 600px;
         height: 600px;
         margin: auto;
         position: relative;
         top: 50%;
         margin-top: -263px;
         margin-right: -61px;
      }
      #canvas-copy {
         opacity: 0.05;
         -webkit-transform: scaleY(-1);
         margin-top: -6px;
      }
    </style><body><div id="container"><div id="canvas-container"><canvas width=600 height=300 id="canvas"></canvas><canvas width=600 height=300 id="canvas-copy"></canvas></div><div id="instructions"><a href="https://www.tutorialspoint.com/index.htm" align="center"> Tutorials Point</a><h2 style="font-family:verdana"> Drag Your Local MP3 Files </h2></div><div id="button"></div></div><script>
      (function() {
         var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
         window.requestAnimationFrame = requestAnimationFrame;
      })();
      window.onload = function() {
         var element = document.getElementById('container')
         dropAndLoad(element, init, "ArrayBuffer")
      }
      function dropAndLoad(dropElement, callback, readFormat) {
         var readFormat = readFormat || "DataUrl"
         dropElement.addEventListener('dragover', function(e) {
            e.stopPropagation()
            e.preventDefault()
            e.dataTransfer.dropEffect = 'copy'
         }, false)
         dropElement.addEventListener('drop', function(e) {
            e.stopPropagation()
            e.preventDefault()
            loadFile(e.dataTransfer.files[0])
         }, false)
         function loadFile(files) {
            var file = files
            var reader = new FileReader()
            reader.onload = function(e) {
               callback(e.target.result)
            }
            reader['readAs' + readFormat](file)
         }
      }
      function init(arrayBuffer) {
         document.getElementById('instructions').innerHTML = 'Audio Loading'
         window.audioCtx = new AudioContext()
         window.analyser = audioCtx.createAnalyser()
         if (window.source) source.noteOff(0)
         audioCtx.decodeAudioData(arrayBuffer, function(buffer) {
            window.source = audioCtx.createBufferSource()
            source.buffer = buffer
            source.connect(analyser)
            analyser.connect(audioCtx.destination)
            source.start(0)
            var viz = new simpleViz()
            new visualizer(viz['update'], analyser)
            document.getElementById('instructions').innerHTML = ''
         })
      }
      function visualizer(visualization, analyser) {
         var self = this
         this.visualization = visualization
         var last = Date.now()
         var loop = function() {
            var dt = Date.now() - last
            var byteFreq = new Uint8Array(analyser.frequencyBinCount)
            analyser.getByteFrequencyData(byteFreq)
            last = Date.now()
            self.visualization(byteFreq, dt)
            requestAnimationFrame(loop)
         }
         requestAnimationFrame(loop)
      }
      function simpleViz(canvas) {
         var self = this
         this.canvas = document.getElementById('canvas')
         this.ctx = this.canvas.getContext("2d")
         this.copyCtx = document.getElementById('canvas-copy').getContext("2d")
         this.ctx.fillStyle = '#fff'
         this.barWidth = 10
         this.barGap = 4
         this.bars = Math.floor(this.canvas.width / (this.barWidth + this.barGap))
         this.update = function(byteFreq) {
            self.ctx.clearRect(0, 0, self.canvas.width, self.canvas.height)
            var step = Math.floor(byteFreq.length / self.bars)
            for (var i = 0; i &lt; self.bars; i++) {
               var barHeight = byteFreq[i * step]
               self.ctx.fillRect(i * (self.barWidth + self.barGap), self.canvas.height - barHeight, self.barWidth, barHeight)
               self.copyCtx.clearRect(0, 0, self.canvas.width, self.canvas.height)
               self.copyCtx.drawImage(self.canvas, 0, 0)
            }
         }
      }
    </script></body></html>

    When we run the above code, it will generate an output consisting of the text applied with CSS indicating to drag the local MP3 file to play music.

    HTML Audio Player with Playlist

    Consider the following example, where we are allowing the user to upload the multiple local MP3s that act as a playlist.

    Open Compiler

    <!DOCTYPE html><html><body style="background-color:#ABEBC6;"><audio controls id="y" autoplay></audio><br><br><br><input type="file" id="x" multiple><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>
    
      var x = document.getElementById("x"),
         y = document.getElementById("y");
      function next(n) {
         var a = URL.createObjectURL(z[n]);
         y.setAttribute('src', a);
         y.play();
      }
      var _next = 0,
         z,
         len;
      x.addEventListener('Change', function() {
         z = x.z;
         len = z.length;
         if (len) {
            next(_next);
         }
      });
      y.addEventListener("Completed", function() {
         _next += 1;
         next(_next);
         console.log(len, _next);
         if ((len - 1) == _next) {
            _next = -1;
         }
      });
    </script></body></html>

    On running the above code, the output window will pop up, allowing the user to upload multiple mp3 files and play them automatically on the webpage.

  • Web RTC

    Web RTC introduced by World Wide Web Consortium (W3C) that supports browser-to-browser applications for voice calling, video chat, and P2P file sharing.

    The web RTC implements three API’s as shown below −

    • MediaStream − get access to the user’s camera and microphone.
    • RTCPeerConnection − get access to audio or video calling facility.
    • RTCDataChannel − get access to peer-to-peer communication.

    MediaStream

    The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here.

    The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chat applications, a chat application gets stream from web camera, rear camera, microphone.

    Sample code of MediaStream

    function gotStream(stream) {
       window.AudioContext = window.AudioContext || window.webkitAudioContext;
       var audioContext = new AudioContext();
       
       // Create an AudioNode from the stream
       var mediaStreamSource = audioContext.createMediaStreamSource(stream);
       // Connect it to destination to hear yourself
       // or any other node for processing!
       mediaStreamSource.connect(audioContext.destination);
    }
    navigator.getUserMedia({audio:true}, gotStream);
    

    Session Control, Network & Media Information

    Web RTC required peer-to-peer communication between browsers. This mechanism required signaling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications.

    Sample code of createSignalingChannel()

    var signalingChannel = createSignalingChannel();
    var pc;
    var configuration = ...;
    // run start(true) to initiate a call
    function start(isCaller) {
       pc = new RTCPeerConnection(configuration);
       // send any ice candidates to the other peer
       pc.onicecandidate = function (evt) {
    
      signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
    }; // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) {
      remoteView.src = URL.createObjectURL(evt.stream);
    }; // get the local stream, show it in the local video element and send it navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
      selfView.src = URL.createObjectURL(stream);
      pc.addStream(stream);
      if (isCaller)
         pc.createOffer(gotDescription);
      else
         pc.createAnswer(pc.remoteDescription, gotDescription);
         function gotDescription(desc) {
            pc.setLocalDescription(desc);
            signalingChannel.send(JSON.stringify({ "sdp": desc }));
         }
      });
    } signalingChannel.onmessage = function (evt) {
      if (!pc)
         start(false);
         var signal = JSON.parse(evt.data);
      if (signal.sdp)
         pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
      else
         pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
    };

  • CORS

    Cross-origin resource sharing (CORS) is a mechanism to allows to load the restricted resources from another domain in web browser

    For example, suppose we click on HTML5 video player in HTML5 demo section. First, it will ask camera permission, if user allow the permission then only it will open the camera otherwise not.

    Making a CORS request

    The modern browsers like Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object.

    function createCORSRequest(method, url) {
       var xhr = new XMLHttpRequest();
       
       if ("withCredentials" in xhr) {
    
      // Check if the XMLHttpRequest object has a "withCredentials" property.
      // "withCredentials" only exists on XMLHTTPRequest2 objects.
      xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      // Otherwise, CORS is not supported by the browser.
      xhr = null;
    } return xhr; } var xhr = createCORSRequest('GET', url); if (!xhr) { throw new Error('CORS not supported'); }

    Event handles in CORS

    Sr.No.Event Handler & Description
    1onloadstartStarts the request
    2onprogressLoads the data and send the data
    3onabortAbort the request
    4onerrorrequest has failed
    5onloadrequest load successfully
    6ontimeouttime out has happened before request could complete
    7onloadendWhen the request is complete either successful or failure

    Example of onload or onerror event

    xhr.onload = function() {
       var responseText = xhr.responseText;
       // process the response.
       console.log(responseText);
    };
    xhr.onerror = function() {
       console.log('There was an error!');
    };
    

    Example of CORS with handler

    Below example will show the example of makeCorsRequest() and onload handler

    // Create the XHR object.
    function createCORSRequest(method, url) {
       var xhr = new XMLHttpRequest();
       if ("withCredentials" in xhr) {
    
      
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
      
      // XDomainRequest for IE.
      xhr = new XDomainRequest();
      xhr.open(method, url);
    } else {
      
      // CORS not supported.
      xhr = null;
    } return xhr; } // Helper method to parse the title tag from the response. function getTitle(text) { return text.match('<title>(.*)?</title>')[1]; } // Make the actual CORS request. function makeCorsRequest() { // All HTML5 Rocks properties support CORS. var url = 'http://www.tutorialspoint.com'; var xhr = createCORSRequest('GET', url); if (!xhr) {
      alert('CORS not supported');
      return;
    } // Response handlers. xhr.onload = function() {
      var text = xhr.responseText;
      var title = getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
    }; xhr.onerror = function() {
      alert('Woops, there was an error making the request.');
    }; xhr.send(); }

  • Web Messaging

    Web Messaging is the way for documents to separates browsing context to share the data without Dom. It overrides the cross domain communication problem in different domains, protocols or ports.

    For example, if we want to send the data from our page to ad container which is placed at iframe or voice-versa, in this scenario, Browser throws a security exception. With web messaging we can pass the data across as a message event.

    Message Event

    Message events fires Cross-document messaging, channel messaging, server-sent events and web sockets. It is described by Message Event interface.

    Properties of Message Event

    The following table contains a list of Message Event properties −

    S.No.Property & Description
    1dataContains string data
    2originContains Domain name and port
    3lastEventIdContains unique identifier for the current message event.
    4sourceContains to A reference to the originating documents window
    5portsContains the data which is sent by any message port

    Sending a cross-document message

    Before send cross document message, we need to create a new web browsing context either by creating new iframe or new window. We can send the data using with postMessage() and it has two arguments. They are as

    • message − The message to send
    • targetOrigin − Origin name

    Examples

    Sending message from iframe to button

    var iframe = document.querySelector('iframe');
    var button = document.querySelector('button');
    var clickHandler = function(){
       iframe.contentWindow.postMessage('The message to send.','https://www.tutorialspoint.com);
    }
    button.addEventListener('click',clickHandler,false);
    

    Receiving a cross-document message in the receiving document

    var messageEventHandler = function(event){
       // check that the origin is one we want.
       if(event.origin == 'https://www.tutorialspoint.com'){
    
      alert(event.data);
    } } window.addEventListener('message', messageEventHandler,false);

    Channel messaging

    Two-way communication between the browsing contexts is called channel messaging. It is useful for communication across multiple origins.

    The MessageChannel and MessagePort Objects

    While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context.

    • postMessage() − Post the message throw channel
    • start() − It sends the data
    • close() − it close the ports

    In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM.

    var loadHandler = function(){
       var mc, portMessageHandler;
       mc = new MessageChannel();
       window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2]);
       portMessageHandler = function(portMsgEvent){
    
      alert( portMsgEvent.data );
    } mc.port1.addEventListener('message', portMessageHandler, false); mc.port1.start(); } window.addEventListener('DOMContentLoaded', loadHandler, false);

    Above code, it is taking the data from port 2, now it will pass the data to second iframe

    var loadHandler = function(){
       var iframes, messageHandler;
       iframes = window.frames;
       messageHandler = function(messageEvent){
    
      if( messageEvent.ports.length &gt; 0 ){
         // transfer the port to iframe[1]
         iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports);
      }
    } window.addEventListener('message',messageHandler,false); } window.addEventListener('DOMContentLoaded',loadHandler,false);

    Now second document handles the data by using the portMsgHandler function.

    var loadHandler(){
       // Define our message handler function
       var messageHandler = function(messageEvent){
    
      
      // Our form submission handler
      var formHandler = function(){
         var msg = 'add &lt;[email protected]&gt; to game circle.';
         messageEvent.ports[0].postMessage(msg);
      }
      document.forms[0].addEventListener('submit',formHandler,false);
    } window.addEventListener('message',messageHandler,false); } window.addEventListener('DOMContentLoaded',loadHandler,false);

    Print Page

  • IndexedDB

    The indexedDB is a new HTML5 concept to store the data inside user’s browser. It is more powerful than local storage and useful for applications that requires to store large amount of the data. These applications can run more efficiency and load faster.

    Why to use indexedDB?

    The W3C has announced that the Web SQL database is a deprecated local storage specification so web developer should not use this technology any more. The indexedDB is an alternative for web SQL data base and more effective than older technologies.

    Features

    • It stores key-pair values
    • It is not a relational database
    • IndexedDB API is mostly asynchronous
    • It is not a structured query language
    • It allows to access the data from same domain

    IndexedDB

    Before enter into an indexedDB, we need to add some prefixes of implementation as shown below −

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
    
    if (!window.indexedDB) {
       window.alert("Your browser doesn't support a stable version of IndexedDB.")
    }
    

    Open an IndexedDB database

    Before creating a database, we have to prepare some data for the data base.let’s start with company employee details.

    const employeeData = [
       { id: "01", name: "Gopal K Varma", age: 35, email: "[email protected]" },
       { id: "02", name: "Prasad", age: 24, email: "[email protected]" }
    ];
    

    Adding the data

    Here adding some data manually into the data as shown below −

    function add() {
       var request = db.transaction(["employee"], "readwrite")
       .objectStore("employee")
       .add({ id: "01", name: "prasad", age: 24, email: "[email protected]" });
       
       request.onsuccess = function(event) {
    
      alert("Prasad has been added to your database.");
    }; request.onerror = function(event) {
      alert("Unable to add data\r\nPrasad is already exist in your database! ");
    } }

    Retrieving Data

    We can retrieve the data from the data base using with get()

    function read() {
       var transaction = db.transaction(["employee"]);
       var objectStore = transaction.objectStore("employee");
       var request = objectStore.get("00-03");
       
       request.onerror = function(event) {
    
      alert("Unable to retrieve daa from database!");
    }; request.onsuccess = function(event) {
      if(request.result) {
         alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
      } else {
         alert("Kenny couldn't be found in your database!");
      }
    }; }

    Using with get(), we can store the data in object instead of that we can store the data in cursor and we can retrieve the data from cursor

    function readAll() {
       var objectStore = db.transaction("employee").objectStore("employee");
       
       objectStore.openCursor().onsuccess = function(event) {
    
      var cursor = event.target.result;
      
      if (cursor) {
         alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
         cursor.continue();
      } else {
         alert("No more entries!");
      }
    }; }

    Removing the data

    We can remove the data from IndexedDB with using the remove() method. Here is how the code looks like −

    function remove() {
       var request = db.transaction(["employee"], "readwrite")
       .objectStore("employee")
       .delete("02");
       
       request.onsuccess = function(event) {
    
      alert("prasad entry has been removed from your database.");
    }; }

    HTML Code

    To show all the data we need to use onClick event as shown below code −

    Open Compiler

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>IndexedDb Demo | onlyWebPro.com</title></head><body><button onclick="read()">Read </button><button onclick="readAll()"></button><button onclick="add()"></button><button onclick="remove()">Delete </button></body></html>

    The final code should be as −

    Open Compiler

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">
    
      
      //prefixes of implementation that we want to test
      window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
      
      //prefixes of window.IDB objects
      window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
      window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
      
      if (!window.indexedDB) {
         window.alert("Your browser doesn't support a stable version of IndexedDB.")
      }
      
      const employeeData = [
         { id: "00-01", name: "gopal", age: 35, email: "[email protected]" },
         { id: "00-02", name: "prasad", age: 32, email: "[email protected]" }
      ];
      var db;
      var request = window.indexedDB.open("newDatabase", 1);
      
      request.onerror = function(event) {
         console.log("error: ");
      };
      
      request.onsuccess = function(event) {
         db = request.result;
         console.log("success: "+ db);
      };
      
      request.onupgradeneeded = function(event) {
         var db = event.target.result;
         var objectStore = db.createObjectStore("employee", {keyPath: "id"});
         
         for (var i in employeeData) {
            objectStore.add(employeeData[i]);
         }
      }
      function read() {
         var transaction = db.transaction(["employee"]);
         var objectStore = transaction.objectStore("employee");
         var request = objectStore.get("00-03");
         
         request.onerror = function(event) {
            alert("Unable to retrieve daa from database!");
         };
         request.onsuccess = function(event) {
            
            // Do something with the request.result!
            if(request.result) {
               alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
            } else {
               alert("Kenny couldn't be found in your database!");
            }
         };
      }
      
      function readAll() {
         var objectStore = db.transaction("employee").objectStore("employee");
         objectStore.openCursor().onsuccess = function(event) {
            var cursor = event.target.result;
            
            if (cursor) {
               alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
               cursor.continue();
            } else {
               alert("No more entries!");
            }
         };
      }
      
      function add() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .add({ id: "00-03", name: "Kenny", age: 19, email: "[email protected]" });
         
         request.onsuccess = function(event) {
            alert("Kenny has been added to your database.");
         };
         request.onerror = function(event) {
            alert("Unable to add data\r\nKenny is aready exist in your database! ");
         }
      }
      
      function remove() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .delete("00-03");
         
         request.onsuccess = function(event) {
            alert("Kenny's entry has been removed from your database.");
         };
      }
    </script></head><body><button onclick="read()">Read </button><button onclick="readAll()">Read all </button><button onclick="add()">Add data </button><button onclick="remove()">Delete data </button></body></html>

    Print Page