HTML - What is a Web API?
A Web API is a developer's dream.
It can extend the functionality of the browser
It can greatly simplify complex functions
It can provide easy syntax to complex code
What is Web API?
API stands for Application Programming Interface. An API is some kind of
interface that includes a set of functions and subroutines that allow
programmers to access specific features or data of an application, operating
system or other services.
A Web API is an application programming interface for the Web.
HTML APIs
All browsers have a set of built-in Web APIs to support complex operations,
and to help accessing data.
Here are some of the main HTML5 APIs:
1. Geolocation API - This API is used to access the current location of a user
(with latitude and longitude).
2. Drag and Drop API - This API enables you to use drag-and-drop features
in browsers.
3. Web Storage API - This API has mechanisms to let browsers store
key/value pairs (in a more intuitive way than cookies).
4. Web Workers API - This API allows a JavaScript to run in the background,
without affecting the performance of the page. Users can continue to do
whatever they want: clicking, selecting things, etc., while the web worker
runs in the background.
5. Server-Sent Events API - This API allows a web page to automatically
get updates from a server.
6. Canvas API - This API lets you draw graphics, on the fly, via JavaScript.
ADVERTISEMENT
REMOVE ADS
Notes on Using HTML APIs
When implementing an HTML API, you should always:
Check Browser Capability - Always check that the target browsers support
the API. Always add script or message to be run if a browser does not
support it.
Add Robust Error Handling - Add robust error handling to take care of
scenarios where an API may not function as expected, to ensure a seamless
user experience.
Request User Permission - When using an API that accesses sensitive
data, like the Geolocation API (which will access the user's geographical
position), always prompt the user for consent before proceeding.
Third Party APIs
Third party APIs are not built into your browser.
To use these APIs, you will have to download the code from the Web.
Examples:
YouTube API - Allows you to display videos on a web site.
Twitter API - Allows you to display Tweets on a web site.
Facebook API - Allows you to display Facebook info on a web site.
HTML Geolocation API
The Geolocation API is used to get the user's current location.
Locate the User's Position
The Geolocation API is used to access the user's current location.
Since this can compromise privacy, the location is not available unless the
user approves it.
Note: The Geolocation API is only available on secure contexts such as
HTTPS.
Tip: The Geolocation API is most accurate for devices with GPS, like
smartphones or smartwatches.
Browser Support
The numbers in the table specify the first browser version that fully supports
Geolocation.
Using HTML Geolocation API
The Geolocation API is accessed via a call to [Link]. This will
cause the browser to ask the user for permission to access their location
data. If the user accept, the browser will search for the best available
functionality on the device to access this information (for example GPS).
The getCurrentPosition() method is used to return the user's current location.
The example below returns the latitude and longitude of the user's current
location:
Example
<script>
const x = [Link]("demo");
function getLocation() {
if ([Link]) {
[Link](success, error);
} else {
[Link] = "Geolocation is not supported by this browser.";
}
}
function success(position) {
[Link] = "Latitude: " + [Link] +
"<br>Longitude: " + [Link];
}
function error() {
alert("Sorry, no position available.");
}
</script>
Example explained:
Check if Geolocation is supported
If Geolocation is supported, run the getCurrentPosition() method. If not,
display a message to the user
The success() function outputs the user's location in latitude and longitude
The error() function alerts a text if the browser retrieves an error
in getCurrentPosition()
ADVERTISEMENT
REMOVE ADS
Error Handling and Rejections
The second parameter of the getCurrentPosition() method is used to handle
errors. It specifies a function to run if it fails to get the user's location.
Here is an example of a more specific error handling:
Example
function error(error) {
switch([Link]) {
case error.PERMISSION_DENIED:
[Link] = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
[Link] = "Location information is unavailable."
break;
case [Link]:
[Link] = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
[Link] = "An unknown error occurred."
break;
}
}
Location-specific Information
Geolocation is also very useful for location-specific information, like:
Up-to-date local information
Showing Points-of-interest near the user
Turn-by-turn navigation (GPS)
The getCurrentPosition() Method -
Return Data
The getCurrentPosition() method returns an object on success. The latitude,
longitude and accuracy properties are always returned. The other properties
are returned if available:
Property Returns
[Link] The latitude as a decimal number (always returned)
[Link] The longitude as a decimal number (always returned)
[Link] The accuracy of position (always returned)
[Link] The altitude in meters above the mean sea level (returned if available)
[Link] The altitude accuracy of position (returned if available)
acy
[Link] The heading as degrees clockwise from North (returned if available)
[Link] The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)
Geolocation Object - Other interesting
Methods
The Geolocation object also has other interesting methods:
watchPosition() - Returns the current location of the user and continues
to return updated location as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.
The example below shows the watchPosition() method. You need an accurate
GPS device to test this (like a smartphone):
Example
<script>
const x = [Link]("demo");
function getLocation() {
if ([Link]) {
[Link](success, error);
} else {
[Link] = "Geolocation is not supported by this browser.";
}
}
function success(position) {
[Link] = "Latitude: " + [Link] +
"<br>Longitude: " + [Link];
}
function error(error) {
switch([Link]) {
case error.PERMISSION_DENIED:
[Link] = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
[Link] = "Location information is unavailable."
break;
case [Link]:
[Link] = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
[Link] = "An unknown error occurred."
break;
}
}
</script>
HTML Drag and Drop API
The HTML Drag and Drop API enables an element to be dragged and
dropped.
Example
Drag the W3Schools image into the second rectangle.
Drag and Drop
Drag and drop is a very common feature. It is when you "grab" an object and
drag it to a different location.
Browser Support
The numbers in the table specify the first browser version that fully supports
Drag and Drop.
HTML Drag and Drop API Example
The example below is a simple drag and drop example:
Example
<!DOCTYPE HTML>
<html>
<head>
<script>
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
function dragoverHandler(ev) {
[Link]();
}
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>
<div id="div1" ondrop="dropHandler(event)" ondragover="dragoverHand
ler(event)"></div>
<img id="img1" src="img_logo.gif" draggable="true" ondragstart="dra
gstartHandler(event)" width="336" height="69">
</body>
</html>
It might seem complicated, but lets go through all the different parts of a
drag and drop event.
REMOVE ADS
Make an Element Draggable
First of all: To make an element draggable, set the draggable attribute to true:
<img id="img1" draggable="true">
or:
<p id="p1" draggable="true">Draggable text</p>
What to Drag - ondragstart and
setData()
Then, specify what should happen when the element is dragged.
In the example above, the ondragstart attribute of the <img> element calls a
function (dragstartHandler(ev)), that specifies what data to be dragged.
The [Link]() method sets the data type and the value of the
dragged data:
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
In this case, the data type is "text" and the value is the id of the draggable
element ("img1").
Where to Drop - ondragover
The ondragover attrribute of the <div> element calls a function
(dragoverHandler(ev)), that specifies where the dragged data can be
dropped.
By default, data/elements cannot be dropped in other elements. To allow a
drop, we must prevent the default handling of the element.
This is done by calling the preventDefault() method for the ondragover event:
function dragoverHandler(ev) {
[Link]();
}
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute of the <div> element calls a
function, dropHandler(event):
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
Code explained:
Call preventDefault() to prevent the browser default handling of the data
(default is open as link on drop)
Get the dragged data with the [Link]() method. This
method will return any data that was set to the same type in
the setData() method
The dragged data is the id of the dragged element ("img1")
Append the dragged element into the drop element
More Examples
Example
How to drag and drop an <h1> element to a <div> element:
<script>
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
function dragoverHandler(ev) {
[Link]();
}
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>
<div id="div1" ondrop="dropHandler(event)" ondragover="dragoverHand
ler(event)"></div>
<h1 id="h1" draggable="true" ondragstart="dragstartHandler(event)">
[Link]</h1>
Example
How to drag and drop an <a> element to a <div> element:
<script>
function dragstartHandler(ev) {
[Link]("text", [Link]);
}
function dragoverHandler(ev) {
[Link]();
}
function dropHandler(ev) {
[Link]();
const data = [Link]("text");
[Link]([Link](data));
}
</script>
</head>
<body>
<div id="div1" ondrop="dropHandler(event)" ondragover="dragoverHand
ler(event)"></div>
<a id="link1" href="[Link] draggable="true" ondrags
tart="dragstartHandler(event)">[Link]</a>
Example
How to drag and drop an image back and forth between two <div>
elements:
HTML Web Storage API
HTML Web Storage API; better than cookies.
What is HTML Web Storage?
With web storage, applications can store data locally within the user's
browser.
Before HTML5, application data had to be stored in cookies, included in every
server request. Web storage is more secure, and large amounts of data can
be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is
never transferred to the server.
Web storage is per origin (per domain and protocol). All pages, from one
origin, can store and access the same data.
Web Storage API Objects
Web storage provides two objects for storing data in the browser:
[Link] - stores data with no expiration date (data is
not lost when the browser tab is closed)
[Link] - stores data for one session (data is lost
when the browser tab is closed)
Browser Support
The numbers in the table specify the first browser version that fully supports
Web Storage.
Test Web Storage API Support
Before using web storage, we can quickly check browser support for
localStorage and sessionStorage:
Example
Test browser support:
<script>
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
[Link] = "Your browser supports Web storage!";
} else {
[Link] = "Sorry, no Web storage support!";
}
</script>
ADVERTISEMENT
REMOVE ADS
The localStorage Object
The localStorage object stores the data with no expiration date. The data
will not be lost when the browser is closed, and will be available the next
day, week, or year.
Example
Use localStorage to set and retrieve name and value pairs:
<script>
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
// Store
[Link]("lastname", "Smith");
[Link]("bgcolor", "yellow");
// Retrieve
[Link] = [Link]("lastname");
[Link] = [Link]("bgcolor");
} else {
[Link] = "Sorry, no Web storage support!";
}
</script>
Example explained:
Use the [Link]() method to create name/value pairs
Use the [Link]() method to retrieve the values set
Retrieve the value of "lastname" and insert it into an element with id="result"
Retrieve the value of "bgcolor" and insert it into the style backgroundColor of
the element with id="result"
The syntax for removing the "lastname" localStorage item is as follows:
[Link]("lastname");
Note: Name/value pairs are always stored as strings. Remember to convert
them to another format when needed!
Counting Clicks with localStorage
The following example counts the number of times a user has clicked a
button. In this code the value string is converted to a number to be able to
increase the counter:
Example
<script>
function clickCounter() {
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
if ([Link]) {
[Link] = Number([Link])+1;
} else {
[Link] = 1;
}
[Link] = "You have clicked the button
" + [Link] + " time(s)!";
} else {
[Link] = "Sorry, no Web storage support!";
}
}
</script>
The sessionStorage Object
The sessionStorage object is equal to
the localStorage object, except that it stores the data for only one session!
The data is deleted when the user closes the specific browser tab.
Counting Clicks with sessionStorage
The following example counts the number of times a user has clicked a
button, in the current session:
Example
<script>
function clickCounter() {
const x = [Link]("result");
if (typeof(Storage) !== "undefined") {
if ([Link]) {
[Link] = Number([Link])
+1;
} else {
[Link] = 1;
}
[Link] = "You have clicked the button
" + [Link] + " time(s) in this session!";
} else {
[Link] = "Sorry, no Web storage support!";
}
}
</script>
HTML Web Workers API
A web worker is an external JavaScript file that runs in the background,
without affecting the performance of the page.
What is a Web Worker?
When executing scripts in an HTML page, the page becomes unresponsive
until the script is finished.
A web worker is an external JavaScript file that runs in the background,
independently of other scripts, without affecting the performance of the
page. You can continue to do whatever you want: clicking, selecting things,
etc., while the web worker runs in the background.
Web workers are useful for heavy code that can't be run on the main thread,
without causing long tasks that make the page unresponsive.
Browser Support
The numbers in the table specify the first browser version that fully support
the Web Workers API.
Web Workers API Example
The example below creates a simple web worker that count numbers in the
background:
Example
Count numbers:
Start Worker Stop Worker
Note: Normally web workers are not used for such simple scripts, but for
more CPU intensive tasks!
Check Web Worker API Support
Before using web worker, we can quickly check browser support:
Example
Test browser support:
<script>
const x = [Link]("result");
if(typeof(Worker) !== "undefined") {
[Link] = "Your browser support Web Workers!";
} else {
[Link] = "Sorry, your browser does not support Web
Workers.";
}
</script>
ADVERTISEMENT
REMOVE ADS
Create a .js Web Worker File
Now, let's create a web worker in an external JavaScript file.
Here we create a script that counts. The script is stored in the
"demo_workers.js" file:
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()",500);
}
timedCount();
Note: The important part of the code above is the postMessage() method -
which is used to post messages back to the HTML page.
Create a Web Worker Object
Once we have created the .js web worker file, we can call it from an HTML
page.
The following lines checks if a worker (w) already exists, if not - it creates a
new web worker object and points to the .js file: "demo_workers.js":
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
Then we can SEND and RETRIEVE messages from the web worker.
Data is sent between web workers and the main thread via a system of
messages - both sides send their messages using the postMessage() method,
and respond to messages via the onmessage event handler.
Add an onmessage event listener to the web worker object.
[Link] = function(event){
[Link]("result").innerHTML = [Link];
};
When the web worker in the .js posts a message, the code within the event
listener is executed. The data from the web worker is stored in [Link].
Terminate a Web Worker
When a web worker object is created, it will continue to listen for messages
until it is terminated.
To terminate a web worker object, and free browser/computer resources, use
the terminate() method:
[Link]();
Reuse the Web Worker
If you set the web worker variable to undefined, after it has been terminated,
you can reuse the worker/code:
w = undefined;
Full Web Worker Example
We have already seen the Web Worker code in the .js file.
Below is the full code for the HTML page:
Example
<!DOCTYPE html>
<html>
<body>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>
<script>
let w;
function startWorker() {
const x = [Link]("result");
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_workers.js");
}
[Link] = function(event) {
[Link] = [Link];
};
} else {
[Link] = "Sorry! No Web Worker support.";
}
}
function stopWorker() {
[Link]();
w = undefined;
}
</script>
</body>
</html>
Web Workers and the DOM
Since web workers are in external .js files, they do not have access to the
following JavaScript objects:
The window object
The document object
The parent object
Receive Server-Sent Event
Notifications
The EventSource object is used to receive server-sent event notifications:
Example
<script>
const x = [Link]("result");
// Check browser support for SSE
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
[Link] = function(event) {
[Link] += [Link] + "<br>";
};
} else {
[Link] = "Sorry, no support for server-sent events.";
}
</script>
Example explained:
Create a new EventSource object, and specify the URL of the page sending
the updates (in this example "demo_sse.php")
Each time an update is received, the onmessage event occurs
When an onmessage event occurs, put the received data into the element
with id="result"
Check Browser Support
In the tryit example above there were some extra lines of code to check
browser support for server-sent events:
if(typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
// Some code.....
} else {
// Sorry! No server-sent events support..
}
ADVERTISEMENT
REMOVE ADS
Server-Side Code Example
For the example above to work, you need a server capable of sending data
updates (like PHP or ASP).
The server-side event stream syntax is simple. Set the "Content-Type"
header to "text/event-stream". Now you can start sending event streams.
Code in PHP (demo_sse.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>
Code in ASP (VB) (demo_sse.asp):
<%
[Link] = "text/event-stream"
[Link] = -1
[Link]("data: The server time is: " & now())
[Link]()
%>
Code explained:
Set the "Content-Type" header to "text/event-stream"
Specify that the page should not cache
Output the data to send (Always start with "data: ")
Flush the output data back to the web page
The EventSource Object
In the examples above we used the onmessage event to get messages. But
other events are also available:
Events Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs