Copying Objects from the Console to the Clipboard

Published: Wednesday, June 29, 2022
Updated: Tuesday, August 9, 2022

Greetings, friends! Did you know that multiple browsers have a secret console utilities API? They let you run special commands that only work within the console. In this tutorial, I'll discuss the copy utility function.

The copy function works in popular browsers such as Google Chrome, Firefox, and Safari. If you're using Google Chrome, you can open up the Chrome DevTools console using the keyboard shortcut Option + Command + J on a Mac or Ctrl + Shift + J on Windows. Then, copy the following script and paste it to the console.

javascript
Copied! ⭐️
copy('You are awesome!');

After running this code, Your are awesome! should be copied to your computer's clipboard, and you can paste it anywhere! Copying strings may not seem super helpful, so let's try copying an array instead.

javascript
Copied! ⭐️
copy([1, 2, 3, 4, 5]);

When you run this code and try to paste this array somewhere, it may look different than you'd expect.

javascript
Copied! ⭐️
[
    1,
    2,
    3,
    4,
    5
]

The browser will copy a string representation of the specified object to your clipboard, so it may cause objects to be formatted differently compared to how we normally see objects logged to the console. If you copy an object instead of an array, you'll definitely notice a big difference.

javascript
Copied! ⭐️
const obj = {
  a: 1,
  b: 2,
  c: 3
}

copy(obj);

After running this code in the console, the clipboard will contain a string representation of this object.

javascript
Copied! ⭐️
{
    "a": 1,
    "b": 2,
    "c": 3
}

No worries though! You can still assign this object to another variable in the console, since it's still a valid JavaScript object.

javascript
Copied! ⭐️
const obj2 = {
    "a": 1,
    "b": 2,
    "c": 3
}

console.log(obj2); // {a: 1, b: 2, c: 3}

You can copy arrays of objects as well!

javascript
Copied! ⭐️
const food = [
  { name: 'pizza', isTasty: true },
  { name: 'durian', isTasty: false },
  { name: 'potato', isTasty: true },
];

copy(food)

When you run this code and try to paste this array, it'll get reformatted again.

javascript
Copied! ⭐️
[
    {
        "name": "pizza",
        "isTasty": true
    },
    {
        "name": "durian",
        "isTasty": false
    },
    {
        "name": "potato",
        "isTasty": true
    }
]

The copy utility is a great way to share information with your coworkers! It's also handy for quickly copying data from an object. Instead of logging it to the console and then copying it, you can just use the copy function to copy data directly to the clipboard. This function works in multiple browsers, not just Google Chrome!