Reputation: 43
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.
Upvotes: 1
Views: 7738
Reputation: 113
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;
}
}
Upvotes: 2
Reputation: 4113
You 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'}
Upvotes: 6