Web APIs

Frontend SELF EN
Level 46 , Lesson 2
Available

7.1 Geolocation API

Web APIs (Web Application Programming Interfaces) give you some serious tools to interact with the functionality of a user's browser and device. Let's check out some of these APIs, including Geolocation and Notifications, and how to use them.

The Geolocation API lets a web app get the geographic position of a user's device. This can be super useful for things like maps, navigation, and geotargeting.

Requesting Location Access Permission

To use the Geolocation API, a web app needs to ask the user for permission to access their location. This is done using the navigator.geolocation.getCurrentPosition() method.

Example of using Geolocation API:

JavaScript
    
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
          },
          (error) => {
            console.error('Error getting geolocation:', error);
          },
          {
            enableHighAccuracy: true, // High accuracy
            timeout: 5000, // Waiting timeout (ms)
            maximumAge: 0 // Maximum time to use cached data (ms)
          }
        );
      } else {
        console.log('Geolocation is not supported by this browser.');
      }
    
  

Tracking Location

The navigator.geolocation.watchPosition() method allows you to track changes in the user's location.

Example of tracking location:

JavaScript
    
      let watchId;

      if ('geolocation' in navigator) {
        watchId = navigator.geolocation.watchPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
          },
          (error) => {
            console.error('Error getting geolocation:', error);
          },
          {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
          }
        );
      }

      // Stop tracking location
      function stopTracking() {
        if (watchId) {
          navigator.geolocation.clearWatch(watchId);
        }
      }
    
  

7.2 Notifications API

Notifications API allows a web app to display notifications in the user's system. It's handy for grabbing the user's attention to important events, even if the browser tab isn't active.

Requesting Permission to Send Notifications

To use the Notifications API, a web app needs to ask the user for permission to send notifications.

Example of requesting permission:

JavaScript
    
      if ('Notification' in window) {
        Notification.requestPermission().then((permission) => {
          if (permission === 'granted') {
            console.log('Notification permission granted.');
          } else {
            console.log('Notification permission denied.');
          }
        });
      } else {
        console.log('Notifications are not supported by this browser.');
      }
    
  

Sending Notifications

Once permission is granted, you can send notifications using the Notification constructor.

Example of sending a notification:

JavaScript
    
      if (Notification.permission === 'granted') {
        const options = {
          body: 'This is a notification body',
          icon: 'icon.png',
          data: { url: 'https://example.com' }
        };
        const notification = new Notification('Hello, world!', options);

        // Handling notification click
        notification.onclick = (event) => {
          event.preventDefault(); // Prevents the default click behavior
          window.open(notification.data.url, '_blank');
        };
      }
    
  

7.3 Other Useful Web API

1. DeviceOrientation API

The DeviceOrientation API lets you get data about the orientation of a device in space.

Example of using DeviceOrientation API:

JavaScript
    
      window.addEventListener('deviceorientation', (event) => {
        console.log(`Alpha: ${event.alpha}, Beta: ${event.beta}, Gamma: ${event.gamma}`);
      });
    
  

2. Battery Status API

The Battery Status API provides information about the battery status of a device.

Example of using Battery Status API:

JavaScript
    
      navigator.getBattery().then((battery) => {
        console.log(`Battery level: ${battery.level * 100}%`);
        console.log(`Battery charging: ${battery.charging}`);

        battery.addEventListener('levelchange', () => {
          console.log(`Battery level changed: ${battery.level * 100}%`);
        });

        battery.addEventListener('chargingchange', () => {
          console.log(`Battery charging state changed: ${battery.charging}`);
        });
      });
    
  

3. Fullscreen API

The Fullscreen API lets you toggle a web page into full-screen mode.

Example of using Fullscreen API:

JavaScript
    
      const element = document.documentElement; // Whole document

      function toggleFullScreen() {
        if (!document.fullscreenElement) {
          element.requestFullscreen().catch((err) => {
            console.error(`Error attempting to enable full-screen mode: ${err.message}`);
          });
        } else {
          document.exitFullscreen();
        }
      }

      document.getElementById('fullscreenButton').addEventListener('click', toggleFullScreen);
    
  
1
Task
Frontend SELF EN, level 46, lesson 2
Locked
User Location
User Location
1
Task
Frontend SELF EN, level 46, lesson 2
Locked
Battery Status
Battery Status
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION