Solved: This function must be called during a user gesture
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.
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
Problem in practice
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.