• 11 Chrome APIs That Will Give Your Web App a Native Feel
  • Shanika Wickramasinghe
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Jessica
  • Proofreader: NiayyY-S, GESj-Yean

11 Chrome apis to make your Web App look like a native App

Why pursue the so-called “native experience”?

Native apps are more stable, faster, and offer many features that Web apps lacked (and still lacked until recently). In short, native apps generally provide a better user experience than Web apps.

Of course, Web apps have their advantages — they’re versatile, easy to get started, and always up to date. And, more importantly for us developers, it’s very cost-effective.

Our best solution should not be a compromise between the two, but “kids choose, I want them all.”

1. Receive SMS service

Mobile phones are essentially used for user communication and authentication. For online transactions, the App sends a one-time password (OTP) to the phone via SMS to verify the user’s phone number. The user copies the OTP and sends it to the appropriate agent via a Web browser.

Users need to perform OTP operations twice during each confirmation process. Searching for verification code SMS messages and copying the latest OTP messages are tedious and risky tasks. By using the SMS receiving API, the OTP obtained from SMS authentication information can be directly copied and verified without users’ copying and pasting operations.

Once you receive an SMS with an OTP verification code, you will see a bottom page pop up, prompting you to verify the phone number. Clicking “Verify” on the application sends the OTP programmatically to the browser to submit the form automatically. When using the SMS receiving API, it is recommended to use additional security layers, such as form authentication, to establish new sessions for the user.

How to use the API:

  1. Function detection: Detects and determines the functions of SMS objects.
if ('sms' in navigator) {
  ...
}

Copy the code
  1. OTP processing: After receiving an SMS message, a page with an authentication button is displayed at the bottom. After the user clicks the verify button, the OTP is extracted and the user is authenticated by regular expression.
const code = sms.content.match(/^[\s\S]*otp=([0-9]{6})[\s\S]*$/m) [1];
Copy the code
  1. Submit OTP: Once the OTP is retrieved, it is sent to the server for OTP validation.

View Demo: SMS service receiving API Demo

2. Contact selector

Picking a contact from a mobile device’s contact list is a simple operation that most mobile device users take for granted. However, this is not possible on a Web App, and the only way to do this is to manually enter the contact details.

Using the Contact selection API, you can effortlessly search for contacts from your contact list, select them, and add them to a form in your Web App. This is what Chrome version 80 provides for this requirement. The Contact selection API allows the user to select one or more contacts and then add limited details to the browser.

With it, you can quickly extract email, phone numbers, names and other contact information for a variety of purposes. Some use cases include selecting the recipient’s email for Web mail sending, selecting the recipient’s phone number for VOICE OVER IP calls, and searching for contacts on Facebook.

Chrome needs to keep all your contact information and data secure. So, check the security and privacy policies before using this API in your App.

How to use the API:

This API requires a separate call, where the arguments passed in are optional. First, determine if the feature is available. For Windows, use the following code.

const supported = ('contacts' in navigator && 'ContactsManager' in window);

Copy the code

Then, use the “navigator. Contacts. Select ()” open “contact selector”, and then let the user choose want to share the contact, and then click finish. The API returns a Promise that displays contacts for selection and action.

const props = ['name'.'email'.'tel'.'address'.'icon'];
const opts = {multiple: true};
 
try {
  const contacts = await navigator.contacts.select(props, opts);
  handleResults(contacts);
} catch (ex) {
  // Handle any errors here.
}

Copy the code

In addition, you need to handle errors from these apis.

Watch this Demo: Contact selection API Demo

Native file system APIS

File reads and writes are a common scenario in the digital world. We can now use the native file system API to build apps that interact with files on the user’s local device. With the user’s permission, you can allow them to select files, modify them, and save them back to device storage.

Types of files such as ides, editors, and text files can be accessed, modified, and stored on disk. Before opening and saving a file, the Web App needs to request permission from the user.

When writing a file to a disk, you can rename it. To modify existing files on disk, users need to grant additional permissions. System files and other important files cannot be accessed to ensure the security and stability of the device.

  1. The native file system API can be used to open a directory and list its contents.

  2. Permission given by a user to modify an existing file or directory can be revoked.

  3. Permissions are only valid for as long as the TAB is open.

Once the TAB is closed, the Web App loses the permissions that the user allowed. Even if you open the same App again, you need to be prompted for permission each time. The native file system API is available in Origin Trials, where you can work with the native file system API.

Before using this API, review its security and permissions.

How to use the API:

  1. Start by enabling native file-system-API flags in Chrome ://flags.

  2. Apply for a token at this link to add to the page.

or origin-trial: TOKEN_GOES_HERE.

After open API, using Windows. ChooseFileSystEmentries () to allow the user to select to edit the file. The file is then retrieved from the system and read.

const file = await fileHandle.getFile();
const contents = await file.text();

Copy the code

After the file is saved, set the type to saveFile via chooseFileSystemEnteries.

function getNewFileHandle() {
  const opts = {
	type: 'saveFile'.accepts: [{
  	description: 'Text file'.extensions: ['txt'].mimeTypes: ['text/plain']],}};const handle = window.chooseFileSystemEntries(opts);
  return handle;
}

Copy the code

Then save all changes to a file.

async function writeFile(fileHandle, contents) {
  // Create a writer (request permission if necessary).
  const writer = await fileHandle.createWriter();
  // Write the content
  await writer.write(0, contents);
  // Close the file and write the contents to disk
  await writer.close();
}

Copy the code

Applications need permission to write content to disk. After obtaining write permission, call filesystemwriter.writer () to write the content. Then use the close() method to close FileSystemSWriter().

To view the Demo:

Text editor

4. Graph detection API

You can now capture faces in a Web App using the graph detection API. With browser-based apis and the Chrome browser in Android, you can easily capture images or live video from your device’s camera. And it integrates with Android, iOS, and macOS at the hardware level, allowing access to the device’s camera module without affecting application performance.

This is done through a set of JavaScript libraries. The supported functions include face detection, bar code detection, etc. Face recognition in a Web App allows you to:

  • Annotate people on social media – it will highlight the boundaries of faces detected in the image for easy annotation.
  • Content sites can accurately crop images of highlighted sites that include specific objects.
  • The operation of superimposing objects on the highlighted person’s face can be done easily.

How to use the API:

Functional detection: Checks whether the constructor for graph detection exists.

const supported = await (async() = >'FaceDetector' in window &&
    await new FaceDetector().detect(document.createElement('canvas'))
    .then(_= > true)
    .catch(e= > e.name === 'NotSupportedError' ? false : true()));Copy the code

These detections work asynchronously, so it takes some time to detect faces.

5. Web payment API

The Web payment API follows the Web Payment standard. It simplifies the online payment process and works with a variety of payment systems, browsers and device types. The payment request API is available on a variety of browsers, including Chrome, Edge, Safari, and Mozilla. It speeds up the flow of payments between merchants and users. Merchants can integrate various payment methods with minimal cost.

The Web payment API works based on three principles:

  1. Standard and open: provides a common standard that anyone can implement.
  2. Simple and consistent: Provide a convenient payment experience for users by restoring payment details and addresses that need to be filled in payment forms.
  3. Secure and Flexible: Provides industry-leading security and flexibility for many payment streams.

How to use the API:

To use this API, call the hasEnrolledInstrument() method and check whether the device exists.

// Check payment App availability without checking device existence.
if (request.hasEnrolledInstrument) {
  // The specific behavior in 'canMakePayment()' is based on
  // 'hasEnrolledInstrument' varies depending on whether the enrolledinstrument is available.
  request.canMakePayment().then(handlePaymentAppAvailable).catch(handleError);
} else {
  console.log("Cannot check for payment app availability without checking for instrument presence.");
}

Copy the code

6. Wake up lock API

Many types of devices are programmed to sleep automatically when idle or unused. While this is great when not in use, it can be annoying when the device turns off and locks the screen when the user is using it.

There are two types of wakeup lock apis: screen and system. The screen wakeup lock prevents the device from shutting down the application while it is running on the screen, and the system wakeup lock prevents the device’s CPU from going into standby mode.

Page visibility and full-screen mode are responsible for activating or releasing wakelock. Changes on the screen (such as going into full-screen mode, minimizing the current window, or switching from tabs) will release the wakeup lock.

How to use the API:

To use this feature, get a token for your source and add it to your page.

or origin-trial: TOKEN_GOES_HERE

In addition to using tokens, make sure the #experimental-web-platform-features flag is enabled on the Chrome :// Flags page.

To request a wake lock, please call the navigator. Wavelock. Request () method returns a WakeLockSentinel object. And add the call to the try… In the catch block. To release the wakeup lock, call the Release () method of wavelockSentinel.

// Wake up lock.
let wakeLock = null; 
// The function that attempts to invoke the lock.
const requestWakeLock = async() = > {try {
	wakeLock = await navigator.wakeLock.request('screen');
	wakeLock.addEventListener('release', () = > {console.log('Wake Lock was released');
	});
	console.log('Wake Lock is active');
  } catch (err) {
	console.error(`${err.name}.${err.message}`); }};// Request a wakeup lock...
await requestWakeLock();
// Release again after 5 seconds.
window.setTimeout((a)= > {
  wakeLock.release();
  wakeLock = null;
}, 5000);
Copy the code

Wakeup locks have a life cycle and are sensitive to page visibility and full-screen mode. So check these states before asking to wake up the lock.

const handleVisibilityChange = (a)= > {
  if(wakeLock ! = =null && document.visibilityState === 'visible') { requestWakeLock(); }};document.addEventListener('visibilitychange', handleVisibilityChange);
document.addEventListener('fullscreenchange', handleVisibilityChange);
Copy the code

To view the Demo:

Wake up lock API Demo

7. Service worker and Cache caching apis

The browser cache used to be the only way to reload the old content of a web page, but now you can use the Service worker and cache cache apis to better control the process.

The Service worker is a JavaScript file that intercepts network requests, performs caching, and delivers messages via push. They run in the background, independent of the main thread.

Using the cache cache API, developers can determine and control what the browser caches. It follows a code-driven approach to storing the cache and is called from the Service worker. You can configure the cache cache API using the cache-control header.

You need to clear cache-control Settings to access versioned and unversioned urls. If versioned urls are added to the cache, browsers avoid making additional network requests for those urls.

The combination of HTTP caching, Service worker, and cache storage apis enables developers to do this:

  1. Rerequest cached content in the browser background.
  2. Set an upper limit on the maximum number of assets to cache.
  3. Add a user-defined expiration policy.
  4. Compare caches and network responses.

8. Asynchronous Clipboard API

The asynchronous Clipboard API can be used to copy an image and paste it into a browser. The image that needs to be copied is stored as a Blob object. Therefore, no request is made to the server every time an image needs to be copied.

You can now write an image to a canvas element on a Web form directly from the clipboard using htmlCanvasElement.toblob (). Although currently only one image can be copied, future versions will allow multiple images to be copied simultaneously. When an image is pasted, the API updates it in the clipboard in an asynchronous, promise-based fashion.

Custom paste handlers and custom copy handlers allow you to handle image paste and copy events. One of the major problems with copying and pasting images on Chrome is accessing image “compression bombs”. This refers to large compressed image files that, once uncompressed, cannot be processed on a Web form. These images can also be malicious, potentially taking advantage of known vulnerabilities in the operating system.

How to use the API:

First, we need an image as a Blob object, which is requested from the server by calling the fetch() method, and we set the return type to Blob. The wirte() method is then called by passing in an array of ClipboardItem.

try {
  const imgURL = '/images/generic/file.png';
  const data = await fetch(imgURL);
  const blob = await data.blob();
  await navigator.clipboard.write([
	new ClipboardItem({
  	[blob.type]: blob
	})
  ]);
  console.log('Image copied.');
} catch(e) {
  console.error(e, e.message);
}

Copy the code

When pasting, navigator.clipboard.read () is used to iterate over the Clipboard object and read the items.

async function getClipboardContents() {
  try {
	const clipboardItems = await navigator.clipboard.read();
	for (const clipboardItem of clipboardItems) {
  	try {
    	for (const type of clipboardItem.types) {
      	const blob = await clipboardItem.getType(type);
      	console.log(URL.createObjectURL(blob)); }}catch (e) {
    	console.error(e, e.message); }}}catch (e) {
	console.error(e, e.message); }}Copy the code

How to use the API:

Images that support the asynchronous Clipboard API

9. Web target sharing API

Sharing files with other devices or users on mobile apps is as simple as a few mouse clicks. The Web Sharing target API allows you to do the same on a Web App.

To use this feature you need:

  1. Register your App as a shared target.
  2. Update the Manifest of the Web App with target sharing.
  3. Adds basic information to be received by the target application. Data, links, text, and more can be added to JSON files.
  4. Accept the changes applied to the shared target. This will allow data changes to be made in the target application, such as creating bookmarks or accepting file requests in the application.
  5. The incoming content is handled by handling the fetch share and the publish share.

The following code shows how to create manifest.json to receive basic information files.

"share_target": {
  "action": "/share-target/",
  "method": "GET",
  "params": {
	"title": "title",
	"text": "text",
	"url": "url"
  }
}
Copy the code

10. Periodically synchronize apis to the background

Native apps do a good job of getting new data, even when connectivity is unsatisfactory. The latest articles and news will be updated constantly. Regular background synchronization apis provide similar functionality for Web apps. It enables Web Apps to synchronize data periodically.

The API synchronizes data in the background, so the Web App doesn’t get the data when it starts or restarts. This reduces page load time and optimizes performance.

Considering that the API is highly likely to be used by every developer, and that it can lead to battery and network abuse, Chrome has designed a way to limit its use. It won’t be open to every browser TAB, but managed through a site engagement score, which ensures that the API is only active on tabs that users are actively participating in.

The following code is an example of regular background synchronization for updating articles on a news site.

async function updateArticles() {
  const articlesCache = await caches.open('articles');
  await articlesCache.add('/api/articles');
}

self.addEventListener('periodicsync', (event) => {
  if (event.tag === 'update-articles') { event.waitUntil(updateArticles()); }});Copy the code

conclusion

When using an App, users expect a Web App to have the same functionality as a native App. If not, the user will refuse to use the App or find an alternative. As such, the Chrome API is a much needed good thing for developers.

However, it is important to note that these apis have some limitations. Developers need to pay attention to this in order to provide a perfect App experience. Simply calling every API is worthless and useless.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.