One day I accidentally opened a Pandora's box while trying to fix an ancient bug. The issue involved copy & paste functionality for items in our template editor (JSON under the hood) in Safari. My fix solved the original problem but created new ones in Windows and introduced other quirks in Safari. This fascinating journey made me relearn the complexity of copy & paste APIs—something I'd previously dismissed as just a single line of code throughout my career. 🙈
We know that there are 2 ways to trigger copy & paste diagrammatically now:
-
document.execCommand()
- widely known but deprecated for years -
navigator.clipboard
APIs
No matter in flexibility, security, and content support, navigator.clipboard
appears to be a better choice now, and the browser support looks very promising.
However, there are 3 things you may need to know when you want to work with it.
Copy & paste event aren’t triggered
In MDN it confuses us with:
Events are fired as the result of
cut
,copy
, andpaste
operations modifying the clipboard.
However, reading and writing content with navigator.clipboard
APIs won’t trigger the copy or paste events. Here is a demo (open console):
This makes sense as we are firing the copy & paste programmatically instead of interacting with the UI.
The unremovable? “Paste” menu in Safari
Running the above example on Safari, you may find this interesting “Paste” menu popup on top of our “Paste” button if you copy the text with shortcut or context menu, and ONLY trigger the click event if you dismissed this menu:
What makes things more fun is that if you copied by my “Copy” button, then click on “Paste” button, this menu won’t appear. ☹️
Here is an reference of this issue: https://developer.apple.com/forums/thread/133001
System will modify your content
Another fun fact was found when I copied content including line break and use as a source for comparison. That is Windows does modify your written text!
Try this on Mac and Windows Chrome (Does not work on Edge because of security policy):
If you copy text with \n
symbol on Windows, it will replace them with \r\n
:
The reason of this behavior was that \r\n
is the valid new line symbol on Windows instead of \n
. I guess the difference made some complains on Windows and then it decided to convert the content when user copy text.
To be fair, this won’t create a big problem unless you are the unlucky person like me trying to do some comparison.
Lastly
Thanks for reading and hope these information make your day better.