MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Geolocation, Clipboard & Device APIs0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
15.1History API & Client-Side Routing15.2Geolocation, Clipboard & Device APIs15.3Fullscreen & Screen Orientation APIs15.4Web Audio & MediaStream APIs Basics
HomeTutorialsJavaScript for AdvancedGeolocation, Clipboard & Device APIs
Fullscreen & Screen Orientation APIs

Geolocation, Clipboard & Device APIs

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Modern web applications can access native device capabilities—including GPS coordinates, the system clipboard, hardware vibration motors, and battery status. These Device APIs enable web apps to provide native-app-like user experiences while respecting user privacy and security sandboxes.


1. The Geolocation API

The navigator.geolocation interface provides access to the device's physical geographic location (GPS, Wi-Fi tri-angulation, cell towers):

1function getUserLocation() {
2 if (!navigator.geolocation) {
3 alert('Geolocation is not supported by your browser.');
4 return;
5 }
6 
7 const options = {
8 enableHighAccuracy: true, // Use GPS hardware if available
9 timeout: 5000, // Max wait time (5s)
10 maximumAge: 0 // Do not use cached position
11 };
12 
13 navigator.geolocation.getCurrentPosition(
14 (position) => {
15 const { latitude, longitude, accuracy } = position.coords;
16 console.log(`User Coordinates: ${latitude}, ${longitude} (Accuracy: ${accuracy}m)`);
17 console.log('Timestamp:', new Date(position.timestamp));
18 },
19 (error) => {
20 console.error(`Geolocation error (${error.code}): ${error.message}`);
21 // Error codes: 1 = PERMISSION_DENIED, 2 = POSITION_UNAVAILABLE, 3 = TIMEOUT
22 },
23 options
24 );
25}

2. The Async Clipboard API (navigator.clipboard)

Replacing the legacy, insecure document.execCommand('copy'), the modern Async Clipboard API enables safe reading and writing to the system clipboard with Promise-based asynchronous calls:

1// Copy text to system clipboard
2async function copyToClipboard(text) {
3 try {
4 await navigator.clipboard.writeText(text);
5 console.log('Content successfully copied to clipboard!');
6 showToast('Copied to clipboard!');
7 } catch (err) {
8 console.error('Failed to copy text:', err);
9 }
10}
11 
12// Read text from system clipboard (Requires explicit user permission!)
13async function pasteFromClipboard() {
14 try {
15 const text = await navigator.clipboard.readText();
16 console.log('Pasted text:', text);
17 return text;
18 } catch (err) {
19 console.error('Failed to read clipboard:', err);
20 }
21}

3. The Vibration API (navigator.vibrate)

Provides physical haptic feedback on supported mobile devices:

1function triggerHapticFeedback() {
2 if (navigator.vibrate) {
3 // Vibrate for 200ms
4 navigator.vibrate(200);
5 
6 // Vibration pattern: Vibrate 100ms, pause 50ms, vibrate 100ms
7 // navigator.vibrate([100, 50, 100]);
8 }
9}

4. The Permissions API: Querying Hardware Status

Before invoking intrusive device features, use the Permissions API to inspect whether permission has already been granted, denied, or needs a prompt:

1async function checkLocationPermission() {
2 const status = await navigator.permissions.query({ name: 'geolocation' });
3 console.log('Permission state:', status.state); // 'granted', 'denied', or 'prompt'
4 
5 status.onchange = () => {
6 console.log('Permission state changed to:', status.state);
7 };
8}

5. Security Requirements: Secure Contexts (HTTPS)

All modern Device APIs require a Secure Context (HTTPS or localhost) and explicit User Gesture Activation (e.g., must be triggered inside a click event listener). Invoking navigator.clipboard.writeText() automatically on page load without user interaction throws a NotAllowedError.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What security environment is strictly required to access Device APIs like Geolocation and Clipboard?
Question 2
What modern Promise-based API replaces the deprecated document.execCommand('copy')?
Question 3
What happens if a user denies location permissions when navigator.geolocation.getCurrentPosition() is called?
Question 4
Which API enables checking whether a device permission is currently 'granted', 'denied', or 'prompt' without triggering a prompt?
Question 5
What does navigator.vibrate([100, 200, 100]) do on supported mobile hardware?
Next Lesson

Fullscreen & Screen Orientation APIs

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
History API & Client-Side RoutingFullscreen & Screen Orientation APIs

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext