"Copy to clipboard" button

i use copy to clipboard ina bunch of my apps, heres an example https://anvil.works/build#clone:PAN6HXWFPLTW4N7A=SNEZV5EYB7CKRKFS6GGE23BW

3 Likes

Update on this topic: It has now become much easier!

navigator.clipboard is now fully supported by most modern browsers, and Anvil have exposed that functionality through the anvil.js module. So really it’s just an import and a one-liner:

from anvil.js.window import navigator

class MyForm(MyFormTemplate):
    def __init__(self, **properties):
        self.init_components(**properties)

    def copy_button_click(self, **event_args):
        navigator.clipboard.writeText("Hello World!")
15 Likes

Thanks for the update @james.campbell, I just came across this and very pleased with the simple solution! Though readers should be aware you’ll get an error when testing the app from the Anvil editor preview if using Google Chrome. I get this error using version 93.0.4577.82:

ExternalError: NotAllowedError: The Clipboard API has been blocked because of a permissions policy applied to the current document. See https://goo.gl/EuHzyv for more details.

It works like a charm using the Share app... > Run your app link however, I assume because the editor previews the app using a ‘cross-origin iframe’ as described in the Deprecating Permissions in Cross-Origin Iframes - The Chromium Projects article linked in the error, while the Share app... > Run your app does not.

No problems in Firefox version 92.0.1 in either the Anvil editor preview or a Share app... > Run your app link.

3 Likes

Welcome to the Forum.

There are many restrictions on an Iframe in various browsers. But thankfully, you can run the app in a new tab when using Beta Editor which will solve any issues during testing.

5 Likes

Nice - thanks for the update!

3 posts were split to a new topic: Copy to clipboard troubleshooting

this is the best solution from all ABOVE - JUST WRITE
ANY VARIABLE
X = “I AM GREAT”
navigator.clipboard.writeText(X) # THIS SUPPORT VARIABLE ALSO

THANKS MAN I APPRECIATE IT