Explore modern browser APIs like Geolocation, Web Workers, and more.
Example showing usage of Geolocation API and Web Workers:
// Using Geolocation API to get current position
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
console.log('Latitude:', position.coords.latitude);
console.log('Longitude:', position.coords.longitude);
},
error => {
console.error('Error getting location:', error);
}
);
} else {
console.log('Geolocation is not supported by this browser.');
}
// Creating a simple Web Worker
if (window.Worker) {
const worker = new Worker('worker.js'); // worker.js contains the background task
worker.postMessage('Start');
worker.onmessage = function(event) {
console.log('Message from worker:', event.data);
};
} else {
console.log('Web Workers are not supported in this browser.');
}
This code demonstrates:
Web APIs are interfaces provided by modern browsers to allow web applications to access features beyond basic HTML, CSS, and JavaScript capabilities.
Some commonly used Web APIs include:
These APIs improve the user experience by enabling richer interactions, parallel processing, and access to device capabilities.
Q1: What is the primary purpose of the Geolocation API?
Answer: B. To retrieve the user's geographic location
Q2: What do Web Workers allow you to do?
Answer: B. Run JavaScript code in a background thread
Q3: Which Web API would you use to draw graphics on a webpage?
Answer: B. Canvas API
Q4: How can you check if the browser supports a specific Web API?
Answer: B. Using feature detection like `if (navigator.geolocation)`