How to check whether user has granted clipboard read permisssion or not using javascript?
I am trying to get as a boolean value indicating the current clipboard permission status.
How to check whether user has granted clipboard read permisssion or not using javascript?
I am trying to get as a boolean value indicating the current clipboard permission status.
Share Improve this question asked Oct 26, 2020 at 16:51 FIROSH GTFIROSH GT 431 silver badge6 bronze badges2 Answers
Reset to default 6You can check if you have permission to access the clipboard using the Permissions API:
await navigator.permissions.query({ name: 'clipboard-read' });
// or 'clipboard-write' for permission to write
// sample result: {state: 'granted'}
The clipboard read permission has 3 states: granted, denied, or prompt "neither denied or nor granted".
Therefore, your code should look something like:
const queryOpts = { name: 'clipboard-read', allowWithoutGesture: false };
const permissionStatus = await navigator.permissions.query(queryOpts);
// Will be 'granted', 'denied' or 'prompt':
console.log(permissionStatus.state);
// Listen for changes to the permission state
permissionStatus.onchange = () => {
console.log(permissionStatus.state);
};
code citation: https://web.dev/async-clipboard/
So from the code above, you can write a function that returns true or false like:
// you pass permissionStatus.state to this function
const checkClipboardPermission = (state) => {
if(state == "granted"){
return true;
}
else if(state == "denied"){
return false;
}
else {
return false;
}
}