Iframe shenanigans: how to allow web share and clipboard copy inside iframes
Some of the web apps I'm working on are often served embedded inside an iframe, on the client's website. This means two things.
First, the iframe will have a different origin, since the parent domain will be different from ours. Second, we have limited access to the code and sometimes it's almost impossible to make adjustments on their website so your code can work.
Recently we ran into some hurdles related to the content sharing options. First, the copy link feature was not working.
As usual, StackOverflow tends to have solution since other people have also ran into the problem and in this case the questions Can text within an iframe be copied to clipboard? had the answer.
You can get more details on the web.dev article Unblocking clipboard access but the gist of things is you need to pass the clipboard-write
or clipboard-read permission
, according to your needs. In our case, it was clipboard-write
, since all we needed to to was to write the sharing URL in the user's clipboard, so he could paste it wherever he needed. However, we also needed to pass the allowed origin, since we were also dealing with cross-origin URLs.
Here's how the allow
attribute should look like:
<iframe allow="clipboard-write self https://your.iframe.source"></iframe>
Second, the native share option was not working. The culprit was the cross-origin issue as well and this is something also fixable with the allow
attribute.
As detailed on the Chrome for developers article New requirements for the Web Share API in third-party iframes you need to pass the web-share permission, like this:
<iframe allow="web-share"></iframe>
And if you need both of them (or have multiple permissions in the allow atribute), you can separate them by semicolons, like this:
<iframe allow="clipboard-write self https://your.iframe.source;web-share"></iframe>