In my React app, I'm displaying cards after looping through an array (so there can theoretically be n
cards).
I want the text displayed in a card to be copied when the user clicks on that card. The issue however, is that the react app is rendered inside an iframe.
The copy functionality works when the app is in an individual tab. However when tried from within an iframe, I run into this error:
Uncaught (in promise) DOMException: Disabled in this document by Feature Policy.
This is linked to this policy change from Google. Is there a way in which I can get this functionality working?
Additional info: The app rendered inside the iframe does not share the same domain as the parent app
Background reading links:
The select() method is used to select the contents of an element that includes text field (like input or textarea). Copy the content of the text field by writing document. execCommand("copy"). The execCommand() method is used to execute a command for the selected part of an editable region.
* Copy to clipboard can be executed from the context menu, the tool button, or keyboard shortcut (Alt+Shift+C).
As mentioned here:
To use the API in iframes, you need to enable it with Permissions Policy, which defines a mechanism that allows for selectively enabling and disabling various browser features and APIs. Concretely, you need to pass either or both of
clipboard-read
orclipboard-write
, depending on the needs of your app.
<iframe src="index.html" allow="clipboard-read; clipboard-write"></iframe>
If you only want to be able to copy text to the clipboard (i.e. you don't need to be able to read the clipboard programmatically), then you only need the clipboard-write
permission:
<iframe src="index.html" allow="clipboard-write"></iframe>
To add to joe's answer, if you need to allow clipboard access to a iframed site from a different origin than the parent page (especially if the child redirects to a yet another origin), you'll need to specify the allowed origin in the 'allow' attribute value. For example, to allow clipboard read access to https://trustedsite.com/somefolder/index.html, use:
<iframe src="index.html" allow="clipboard-read self https://trustedsite.com/somefolder/index.html"></iframe>
If you embed a cross-origin URL and you don't supply the trusted domain in 'allow', you'll see the following error in Chrome:
"The Clipboard API has been blocked because of a permissions policy applied to the current document."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With