admin管理员组

文章数量:1317915

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

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'}

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;
    }

}

本文标签: javascriptcheck whether user granted Clipboard permisssion or notStack Overflow