I’m working on app that requires the user’s permission to read/write his clipboard. I want to block the entrance to a part of my website if they haven’t granted those permissions. Also, if they haven’t granted permission display a button that when clicking it shows the small pop up at the top left corner of the browser to grant the permission. I already tried using this but it doesn’t work:
async function checkClipboardPermissionAndRequest() {
try {
const result = await navigator.permissions.query({ name: 'clipboard-read' });
if (result.state !== 'granted') {
const permissionRequest = await navigator.permissions.request({ name: 'clipboard-read' });
if (permissionRequest.state === 'granted') {
console.log('Clipboard read permission granted.');
} else {
console.log('Clipboard read permission denied.');
}
} else {
console.log('Clipboard read permission already granted.');
}
} catch (error) {
console.error('Error checking clipboard permission:', error);
}
}
// Call the function to check clipboard permissions and request if necessary
checkClipboardPermissionAndRequest();
This was just for web console testing, but I want to implement it in my Next.js app.
2
Answers
The main issue with the code snippet you provided is the use of navigator.permissions.request(). Currently, there is no method called request within the navigator.permissions API. This is why the function is not working as expected.
The navigator.permissions API allows you to query the permission status using navigator.permissions.query(), but it does not provide a method to directly request permissions. Permission to access the clipboard (or any other sensitive resource) is typically requested implicitly when attempting to perform an action that requires that permission, such as reading from or writing to the clipboard.
Here is a corrected approach on how you can manage clipboard permissions:
Use instead of const permissionRequest = await navigator.permissions.request({ name: ‘clipboard-read’ });
await navigator.clipboard.read()
The most important is browser support please check there and find alternative solution for permissions query and read the clipboard