Error When Copying to Clipboard From Iframe
Ugh Iframes…
Am I right? lol
As much as we hate them unfortunately sometimes they are a necessary evil. Recently I had the need to copy to my clipboard from a cross-origin site and had a hell of a time figuring out how to do it. So here is how.
The Problem
When using the amazing new Async Clipboard API trying to copy to the clipboard in an Iframe you may run into this error: “Uncaught (in promise) DOMException: Disabled in this document by Feature Policy.”
NOTE: This is only a problem if you want to programmatically copy something to the clipboard such as clicking a button to copy from an input. This SHOULD NOT be an issue when you highlight and press Ctrl+C or right click and copy on a page.
Why Do I Get This Error?
Long answer short security. If there were no permissions needed for writing to a clipboard a page could add malicious content to you clipboard. If all pages had read access to you clipboard they would be able to read anything you had copied to your clipboard. Imagine the things you have copied to you clipboard such as addresses, passwords, bank account numbers, etc. They would have access to all of it. So YAY security! But how do we get permission then?
How Do I Get Passed It?
Cross-Origin
First things first you need to have access to the code that is Iframing in the the content you are trying to copy.
As you may have found in your searching you have to allow the permissions for the Iframe to copy to the clipboard. To do this we need to add the allow attribute found in the Permissions API. What they DON’T tell you is when you are dealing with a site that is cross origin you HAVE to add the self parameter in the allow attribute with the URL for the site that you are copying from. If you just add the “allow="clipboard-read; clipboard-write“ you will still get the error.
If you do not need to read and write just use one or the other you do not need to use both.
<iframe src="test.html" allow="clipboard-read; clipboard-write self ${URL}" > </iframe>
NOTE: A lot of things will talk about adding a listener or changing Feature Policies for you pages you should not need to do this. This solution should be all you need.
Same Origin
This is much easier. You still need access to the code that is Iframing in the content you are trying to copy.
For this you only need to add the allow attribute. You do not need the self parameter to go with it. If you do not need to read and write just use one or the other you do not need to use both.
<iframe src="test.html" allow="clipboard-read; clipboard-write" > </iframe>
There are a lot of places that make this a lot more complicated than it needs to be. I hope this helps and saves you hours of agony! Happy coding!
If you need some more information on how to implement the actually reading and writing for the clipboard with the Async Clipboard API this article is also a great place for information and examples: Unblocking clipboard access