Copy to clipboard troubleshooting

I have to resurrect this old thread…

navigator.clipboard.writeText("Hello World!")

This method works well, except when using Safari on iOS (maybe on desktop too), in which case I get:

copy to clipboard externalerror: notallowederror: the request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

It seems to be reported by other users on various platforms. Is there a solution to this other than going the JavaScript route?

Here is my code, as part of a button_click event:

  def btnCopy2_click(self, **event_args):
    """This method is called when the button is clicked"""
    navigator.clipboard.writeText(f'''
      {anvil.server.get_app_origin('debug')}#?id={anvil.http.url_encode(user.get_id())}&s=1
      ''')

It is not being called as part of an API call, but rather as a user interaction event, so the permissions should be fine, right? And it works on Android but not iOS.

Anyone encountered this or have ideas to resolve it?

UPDATE: Ok, it seems this is due to the data I am trying to pass into it… (anvil.server.get_app_origin) or some other data. When I change the .writeText() method to pass a simple “Hello”, or the contents of a label, the error is no longer present.

In your specific case, the results of anvil.server.get_app_origin are not going to change. You could call that once when the app starts and hold the results in a global module, so that you are not making the call as part of the clipboard call. Same with the anvil.http.url_encode, set that when the user logs in and reference a global string later, if that call also breaks the clipboard.