JavaScript Tutorial in Hindi #36 | Geolocation, Clipboard & Notification API
✅ 1. What are Web APIs?
- Web APIs are built-in browser interfaces that let JavaScript interact with the browser and device features.
- They provide access to hardware or services like location, clipboard, notifications, storage, etc.
- Examples: DOM API, Fetch API, Geolocation API, Clipboard API, Notification API.
✅ 2. Why Web APIs are Important in Web Development?
- Allow developers to build interactive, dynamic, and feature-rich web apps.
- Enable access to device features securely from a web page.
- Help create smoother user experiences without needing external plugins.
✅ 3. Geolocation API
- Lets the browser get the user’s current geographic location (with permission).
- 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
- Allows web apps to read from and write to the user’s clipboard (copy-paste).
- 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
- Allows web apps to send notifications to the user even when the page is not focused.
- 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');
}