JavaScript Tutorial in Hindi #36 | Geolocation, Clipboard & Notification API

✅ 1. What are Web APIs?

  1. Web APIs are built-in browser interfaces that let JavaScript interact with the browser and device features.
  2. They provide access to hardware or services like location, clipboard, notifications, storage, etc.
  3. Examples: DOM API, Fetch API, Geolocation API, Clipboard API, Notification API.

✅ 2. Why Web APIs are Important in Web Development?

  1. Allow developers to build interactive, dynamic, and feature-rich web apps.
  2. Enable access to device features securely from a web page.
  3. Help create smoother user experiences without needing external plugins.

✅ 3. Geolocation API

  1. Lets the browser get the user’s current geographic location (with permission).
  2. Useful for location-based services, maps, weather apps, etc.

Example:

js
CopyEdit
if ('geolocation' in navigator) {
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 not supported');
}

✅ 4. Clipboard API

  1. Allows web apps to read from and write to the user’s clipboard (copy-paste).
  2. Useful for “Copy to Clipboard” buttons.

Example: Copy text to clipboard

js
CopyEdit
function copyText() {
navigator.clipboard.writeText('Hello from Clipboard API!')
.then(() => alert('Text copied to clipboard!'))
.catch(err => console.error('Failed to copy:', err));
}

✅ 5. Notification API

  1. Allows web apps to send notifications to the user even when the page is not focused.
  2. Requires user permission.

Example:

js
CopyEdit
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
new Notification('Hello!', { body: 'This is a notification from your app.' });
}
});
} else {
console.log('Notifications not supported');
}