<trezy-who/>

From the Devtools to the Clipboard

Copy pasta doesn't have to be that hard.
Published 4 June, 2019 Updated 13 August, 2019

Have you ever spent far too long writing a clever little script in the browser’s devtools to get some information from a page? Maybe you’re trying to generate a list of recurring characters from the Marvel Cinematic Universe (MCU) with their names and secret identities from a Wikipedia page...

That wasn’t too bad...

Or maybe you’re trying to get a JSON representation of all of the MCU movies sorted by total profit...

Okay, that one took a little longer...

Or maybe you’re a true masochist, and you want to extract the Game of Thrones (GoT) character and actor names from the body of the GoT wiki page.

SERIOUSLY, WHY WOULDN’T YOU PUT THIS DATA IN A TABLE‽


Anyway.

The norm here is to log the data into the console as JSON, then manually select all of the text with your cursor. Not only is this a nightmarish task with large datasets, it also has the potential to have incomplete data. Long strings (especially data URIs) get collapsed with an ellipse (...) by the dev tools. If you want to copy even small data URIs, this approach will leave you — and I’m putting this delicately — completely boned.

Okay, how do we do it better?

With the copy() function! It just so happens the the devtools for Chrome, Firefox, and Safari (couldn’t test with Edge) all provide the copy() function for jamming anything you need into the clipboard!

✨🧙🏻‍♂️ IT’S MAGIC! 🧙🏻‍♂️✨

If you want to jam an object full of data into your clipboard, it’s as simple as stringifying the data and using copy():

const bigDataSet = [ ... ]
const bigDataSetAsJSON = JSON.stringify(bigDataSet)

copy(bigDataSet)

Now if you paste anywhere, you’ll find that your clipboard is chock full of JSON beautifulness.

Protip: If you want your data to be styled (with spaces, line breaks, etc) the JSON.stringify() method has you covered. For example, if you want the output to use 2 spaces as indentation:

JSON.stringify(bigDataSet, null, 2)

For more information on what all you can pass into JSON.stringify(), check out the docs on MDN.


Wow, Trezy! You sure are smart and amazing!

Oh, I know. I appreciate you saying as much, though. If you want to fiddle with any of the code in the examples at the beginning of the article, you can find them here, here, and here.