Build Chrome extensions quicker with a TypeScript boilerplate project

Solved: This function must be called during a user gesture

ExtensionNinja | 2/12/2022

Some of Chrome extension API calls must be executed in the context of user gestures. Otherwise, the exception “This function must be called during a user gesture” is thrown and the API call fails. One such API is chrome.permissions.request. It allows developers to request optional permissions at runtime. We will use chrome.permission.request as the main example in this article.

UX intention

The intention behind user gesture requirement is that something like asking for a new permission should be a consequence of the user's action which would require the permission to complete. In theory this should provide the best UX for the user, but in practice can be quite an annoying restriction that does not fit with your browser extension structure.

What does user gesture mean

User gesture is any user interaction that generates an event in JavaScript code. Mouse click is the most common example. Any code that is synchronously called in the click event handler is considered to be executing during a user gesture. The key word here is “synchronously”. If code is executed asynchronously, even if it was called from the user gesture handler, it no longer executes in the same context.

Problem in practice

Asynchronous JavaScript execution is probably the most obvious problem that we already mentioned, but it is also the easiest to fix. Code just needs to be refactored to call Chrome API in the same context as the gesture.

Bigger problem awaits when the extension UI is built using content scripts on top of the website that the user has opened. The only way to communicate between content script and service worker is by message passing. Message passing is asynchronous by design. This means that it’s impossible to have a click handler in the content script, send a message to the service worker and expect that service worker will be able to request a new permission. It’s also impossible to request the new permission in the content script, because the API is not available in content script context.

Solving content script problem

What to do? The only way to solve the content script scenario is to change the approach. For example, a user could be redirected to the extension settings page, where he needs to grant the new permission and then can resume using the extension. Extension settings page has access to all chrome extension APIs and can call the needed method in the context of user gestures.

Don't miss latest Chrome extension developer news

Join Newsletter