I'm trying to write a little bookmarklet that can extract some text from the active page and load that into the clipboard.
The extraction is easy enough, but I'm really stuck doing the clipboard-copying part. Currently, I'm just alert
ing the text and hitting Ctrl+C to copy the text from the message-box, which isn't ideal.
I've read How to Copy to Clipboard in JavaScript and other questions that suggest I use zeroclipboard, but I have no idea how one would make that work from a bookmarklet, considering I have to load external flash and javascript resources to be able to use the library.
I have no issues with messing up the page's DOM to accomplish this or having to enable some permissions on my browser (Google Chrome), considering this is just a private bookmarklet.
Any pointers would be appreciated.
Since the new Clipboard API, this is easy in browsers that support it:
javascript: navigator.clipboard.writeText('some text from somewhere');null;
Caveat: Any alerts or prompts in your bookmarklet will cause the document to lose focus, and the clipboard API will become unavailable. In that case you need to move focus back into the document before any subsequent clipboard operations will work:
const oldFocus = document.activeElement;
/* do popup stuff here */
oldFocus.focus();
/* do clipboard stuff here */