Admittedly not the catchiest of titles but if you’re seeing a message like this
Disabled in this document by Feature Policy
in Google Chrome
then you are probably running in to the same problem as me. I’m writing a fulfilment application for Shopify and the UI has a handy ‘Copy’ button for some useful details. Shopify uses an iframe to load apps inside the admin area but here lies the problem!
The solution to this error is to simply allow clipboard-write in the iframe like so;
<iframe src="index.html" allow="clipboard-write"></iframe>
But wait… My app is inside the iframe; I don’t have access to the iframe tag attributes. It seems like I’m not the only person who ran in to this issue but after a year of no response I didn’t have much hope that this would get fixed soon. https://community.shopify.com/c/shopify-apps/using-the-clipboard-api-in-the-app-iframe/td-p/1007594
So for the workaround, we can check if we have the correct permission and use document.execCommand(“copy”) as a fallback;
navigator.permissions.query({name:'clipboard-write'})
.then(function(result) {
if (result.state == 'granted') {
navigator.clipboard.writeText(copyText.value);
} else {
document.execCommand("copy");
}
});
And the whole function, passing in the id of an input element;
function copyToClipboard(id){
var copyText = document.getElementById(id);
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.permissions.query({name:'clipboard-write'})
.then(function(result) {
if (result.state == 'granted') {
navigator.clipboard.writeText(copyText.value);
} else {
document.execCommand("copy");
}
});
}
Now, if the permission is not available, the function falls back onto the deprecated method. If the mighty ruler of the iframe tag grants those permissions, the function doesn’t need to change, the preferred method using Clipboard API is chosen.