The State of Browser APIs - 1

Before here we again to inspect over the some browser API interfaces which are available for a while, before some weeks ago, I remembered the first computer production and tried the think about the people's expectations from them. They might think that the "word processors" had the ability to do our work like cleaning houses, release a car model or make a plane fly without its pilot. The computer systems are now managing central traffic lights of big metropols, deciding our future decisions and talking with us, like a human-race originated species.

That's true like the browsers today. They have a umber of abilities to do as well. In this article, without mentioning IE :), will give some small introduction about some API interfaces embedded into our modern browsers. This article series will continue with some other ones and hope that you will like them all. Additionally, I put some links next to the title of the features with caniuse pages. Let's begin...

Fetch API caniuse/fetch WhatWG DW Blog SitePoint Google Developers Medium

It is a modern implementation of making AJAX requests in the client-side as the new XMLHTTRequest. This middleware is based on promises for easy use.

fetch('some-url').then(function (result) {  
   console.log('got some data from server : ' + result);
}).catch(function (error) {
   console.error('Occured some error : ' + error);
});

It can also be combined with Headers and Request API to setup a more structred way of sending requests.

var headers = new Headers();

headers.set('Accept', 'application/json');  
headers.set('Content-Type', 'application/json');

var newRequest = new Request({headers : headers, url : 'someUrl', method : 'GET'});

fetch(newRequest).then(function (response) {  
   console.log('got some data from server by GET as JSON: ' + response);
}).catch(function (error) {
   console.error('Occured some error : ' + error);
});

Firefox, Chrome and Opera support now this implementation except Safari and Internet Explorer but planning to integrate it into their cores. You can also use for the browsers unsupporting this feature by getting this polyfill.

This API provides developers a handy and easy implementation of making requests without being divided into different APIs, libraries or frameworks.

Battery Status API caniuse/battery W3 SitePoint Hongkiat MobileHTML5

The first API middlewary thing is about getting some charging information from your computer. This fetches for us the battery status of the machine in a double format from 0 to 1. (ex. 0.51 means you have 51% energy of your computer.)

The API is suggested to be used from the navigator object with a getBattery method. In Firefox, it is fetched by navigator's battery property.

if (navigator.getBattery()) {  
   var battery = navigator.getBattery()
   console.log(battery.level * 100); //a double value our battery
}

We can also track the changing level of our computer by attaching an levelchange event:

navigator.getBattery().then(function(battery) {  
  battery.addEventListener('levelchange', function() {
    console.log('Battery Status : ' + this.level * 100 + ' %');
  });
});
//logs Battery Status : 51 %

Battery API is supported within Chrome by the version 45 and Firefox from the version of 43. IE does not support this feature. Opera supports with 34th version and Safari has not included it yet.

As one of the ideas that come up to my mind to develop a small component in trendy React to include it into the a page. You can check this experimental tiny work here.

Full Screen API caniuse/fullscreen SitePoint

During the days of staying without a video streamer like youtube, we didn't even mention about the resizing the media sizes. Torrent systems were not being mentioned regularly, Napster had recently got lost after trials (ex. against Metallica) and (I remember) children who had just come face to face a x86 Pentium 2 processor, expecting a 3d graphics card with 32 MB. Recently, we are talking about resizing videos with a responsive approach, and making streaming views seen through big-sized screens.

This API is for that kind of thing. The main reason not to make a video in full-screen size was security. But now, you can create big screen visulizations with this tiny but useful feature supporting even in IE11.

Example:

1st step: Detect if full screen API is supported in your browser or not with the following keywords.

if(document.fullscreenElement ||  
   document.webkitFullscreenElement ||
   document.mozFullScreenElement ||
   document.msFullscreenElement) {
   //this is ok to make it happen. In the old times, the 's's were read in capitals in the first case.
}

2nd step: Traverse an element to make it full-screen. This is a long, long journey :)

// go full-screen
var videoElToMakeFullScreen = document.getElementById('video-container');  
if (videoElToMakeFullScreen.requestFullscreen) {  
    videoElToMakeFullScreen.requestFullscreen();
} else if (videoElToMakeFullScreen.webkitRequestFullscreen) {
    videoElToMakeFullScreen.webkitRequestFullscreen();
} else if (videoElToMakeFullScreen.mozRequestFullScreen) {
    videoElToMakeFullScreen.mozRequestFullScreen();
} else if (videoElToMakeFullScreen.msRequestFullscreen) {
    videoElToMakeFullScreen.msRequestFullscreen();
}

3rd step: We now deal with the idea of making something else big. The next turn is converting that thing into the previous shape by cancelling making it full screen.

if (document.exitFullscreen) {  
   document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
   document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
   document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
   document.msExitFullscreen();
}

4th step: You can detct changes in the mode of full screen API. You will not have any other information about what is happening but you will be informed at least for changing something in the view.

document.addEventListener("fullscreenchange", function () {});  
document.addEventListener("webkitfullscreenchange", function () {});  
document.addEventListener("mozfullscreenchange", function () {});  
document.addEventListener("MSFullscreenChange", function () {});  

5th step: The tortouring is going on but enough, this is the finishing line, errors.

document.addEventListener("fullscreenerror", function () {});  
document.addEventListener("webkitfullscreenerror", function () {});  
document.addEventListener("mozfullscreenerror", function () {});  
document.addEventListener("MSFullscreenError", function () {});  

Messaging API - postMessage caniuse/postMessage DWBlog, MDN

This API provides us to communicate between windows and iframes in browsers. We can (as developers) call the API as black holes opening to the other windows and applications. You can get and send messages between different domains.

window.addEventListener("message", getMessageFromAnotherWindow, false);

function getMessageFromAnotherWindow(event)  
{
  var origin = event.origin || event.originalEvent.origin; 
   if (origin === "http://somedomain.com")
      //cool, now we can use the other properties
      console.dir(event.data);//Sent from the other domain
      console.log(event.source);//This is the reference for the window object which the message was sent from
   }
}

Service Worker API caniuse/serviceWorkers MDN

Main Purpose

This API allows developers to trigger or catch some events running in the background in a certain time range. The aim of doing this supports the offline applications to develop running the service worker scripts in the background and doing some work and getting some information.

To make an example, if you have a blog and someone gets disconnected with internet; you can configure a service worker to get data when the device becomes online. You can think this middleware tool to reduce the network performance for some assets and etc that you do not need to get for some certain times instead you expect. since it has a promise-based architecture, the usage is basically typical experience for the current generation of developers.

During trying you can notice that it has events like register, install, activate, sync and notification. Let' look at the usage of them in the following.

Example:

1st step: Create a service worker file (ex. someServiceWorker.js) and define the first baby steps methods.

self.addEventListener(function('install') {  
   //do something when the service worker installer
})

self.addEventListener(function('activate') {  
   //do something when the service worker gets activated
})
if (navigator.serviceWorker) {  
   navigator.serviceWorker.register('/someServiceWorker.js').then(function(registration) {
      console.log('Registration is successfull of ' + registration.scope);
   }).catch(function(error) {
      console.error('An error occured during registration : ' + error);
   })
}

The service worker scope also has an additional method called importScripts to get external script into the service worker's self-scoped environment.

self.importScripts('../family.js')  

or to get multiple scripts loaded synchronously:

self.importScripts('../kumsal.js', '../tules.js', '../barbaros.js')

//here i choose using family friends of us here with the little little one, Kumsal ;) 

The example of our work started with an dummy one but here it works as we need in another js file or HTML:

var familyWorker= new Worker('family.js');

familyWorker.addEventListener('message', function(e) {  
  console.log('Worker said: ', e.data);
}, false);

worker.postMessage('Hi, I am working...');  

When the code above is invoked, the content of the worker organized as to post the cmming message, we can handle this like the following:

self.addEventListener('message', function(e) {  
  self.postMessage(e.data);
}, false);

When the whole process is triggered step by step, we get a baby message from the worker like "Hi, I am working...".

There is also a tracking panel section in Dev-Tools in Chrome. You can inspect the all of your service workers as well. Do not be shocked when you see the registered service workers among your tabs from the link. You can also check this diagram to understand the lifecycle of a service worker.

Extra : window.matchMedia caniuse/matchMedia Varvy

Think about if we are developing in the client-side for some responsive web apps. The need of optimizing asset sources are musts for performanse and user experience. This support for detecting device sizes makes it easy to handle the optional resource loads.

Example:

First, think about the devices and the optional code management to initialize. When the device is a mobile one, load or init some; if a device with larger screen size, choose to do another one. Here is the example:

if (window.matchMedia("(max-width: 480px)").matches) {  
/* the view port is larger than 480 pixels wide */
} else {
/* the view port is less than 480 pixels wide */
}

Conclusion

This will help us during some needs we feel that create a social media button or not in the mobile side, for example. Or load a source externally into an HTML "div" element, it is up to you.

Here are the first list after my inspection about the next-gen browser API functionalities. Hope that the further ones will be more good as well. You can also look at the latest release situation of the other interfaces here, from W3C.

comments powered by Disqus