24

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:

nav
  • 241
  • 1
  • 2
  • 5

3 Answers3

31

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 or clipboard-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>
joe
  • 3,752
  • 1
  • 32
  • 41
7

To add to joe's answer, if you need to allow clipboard access to an 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.

bflemi3
  • 6,698
  • 20
  • 88
  • 155
colin moock
  • 1,038
  • 11
  • 15
1

The Clipboard API has been blocked because of a permissions policy applied to the current document. Solution:

function copyToCustomCode() {
    let custom_code = document.querySelector("#custom_code").select();
    document.execCommand('copy'); 
    }
<textarea id="custom_code" placeholder="here is embed code" readonly="readonly">Copy Code Here</textarea>
 <button class="sh-btn" onclick="copyToCustomCode();">Copied</button>