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.
To copy output of a JavaScript variable to the clipboard, we can use the navigator. clipboard. writeText method. const copyToClipboard = (text) => { return navigator.
click hold and drag with the mouse over what you want to copy selecting it, press ENTER to copy. Right click to paste.
There is a nice little bookmarket in Github Gist that does the core of what you want -- copying to the clipboard. It does not use any external libraries, which I think of as an advantage.
As written, it copies some static text, but toward the bottom it talks about adapting it to other uses, such as copying the page title.
Since you've stated that 'The extraction is easy enough ...', you should be easily be able to adapt that gist to what you want to do.
I tried the plain vanilla version of the bookmarklet, because I have some static text that I often need to transfer to my clipboard. It works very well in Chrome 61 with no modifications. But make sure you read the comments; some people have suggestions on getting it to work in other browsers and scenarios.
Here is the code that I tested, already minified and ready to turn into a bookmarklet:
javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent=a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b)}("Text To Copy");
Gist has the pre-minified code as well.
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With