Sling Academy
Home/JavaScript/Auto-Fill Verification Codes Using JavaScript WebOTP

Auto-Fill Verification Codes Using JavaScript WebOTP

Last updated: December 14, 2024

In today's digital world, security is paramount, and applications often use two-factor authentication (2FA) to enhance security. One popular form of 2FA is using One-Time Passwords (OTP). However, entering an OTP manually can be cumbersome for users. JavaScript provides an easy way to simplify this with the WebOTP API, allowing developers to access the code sent via SMS to the user's phone and auto-fill it in input fields.

What is the WebOTP API?

The WebOTP API is a part of the Credential Management API that enables web developers to programmatically access OTP hashes from SMS messages. This use case requires the user's permission and only works when:

  • The OTP's SMS originates from a supported service (e.g., from a short code).
  • The user is on a domain that hosts your application.
  • The SMS contains a specially formatted message.

Basic Usage of WebOTP API

Here’s how you can integrate the WebOTP API into your web application:

Step 1: HTML Setup

First, ensure you have an input field where the OTP will be auto-filled. It requires an autocomplete attribute with the value one-time-code.


<input type="text" id="otp" autocomplete="one-time-code" placeholder="Enter OTP here">

This setup helps the browser recognize the purpose of the input field, making it easier to associate web APIs with it.

Step 2: JavaScript Implementation

With your OTP input in place, add the following JavaScript to handle the retrieval and auto-fill of the code.


if ('OTPCredential' in window) {
  const input = document.querySelector('#otp');

  // Start listening for the OTP message
  const ac = new AbortController();
  const options = {
    otp: { transport:['sms'] },
    signal: ac.signal
  };

  navigator.credentials.get(options).then(otp => {
    input.value = otp.code;
    ac.abort();  // Stop listening immediately after retrieving the code.
  }).catch(err => {
    console.error('Error retrieving OTP:', err);
  });
}

In this script, we are checking if the OTPCredential interface is available in the window. Then, it listens for SMS messages containing OTPs, captures the code, and enters it automatically into the specified input field.

Creating the OTP Message Format

The SMS message should be formatted in an easily identifiable manner for the WebOTP API to work effectively. The message must include a specific domain URL, which you should confirm aligns with your application, followed by the OTP.

123456 is your verification code from ExampleApp.
@https://example.com #123456

In this case, 123456 is the OTP that will be extracted and filled automatically. Make sure to replace https://example.com with the actual domain of your web application.

Security Considerations

While using the WebOTP API, it is important to address privacy and security implications:

  • Make sure users are aware of this feature and provide a way to opt out.
  • Ensure your server-side components are securely sending the right format and handling API errors gracefully.
  • Test across different devices and browser versions as support for the WebOTP API may vary.

Conclusion

The WebOTP API is a powerful tool for improving user experience by reducing friction in entering OTPs during the authentication process. With correct implementation and suitable security measures, it can significantly improve the usability and security of web applications dealing with OTP verification codes. Nonetheless, always stay informed about the latest updates or changes within the API for optimal usage.

Next Article: Streamline Login Flows via the WebOTP API in JavaScript

Previous Article: Receive One-Time Passwords with the WebOTP API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration