Copy to clipboard in JavaScript

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

In this article, we have explored techniques in JavaScript to copy text to clipboard and use the data stored in clipboard. This involves using navigator.clipboard.

Table of contents:

  1. Introduction to clipboard
  2. Use Cases of Clipboard
  3. The old vs the new technique in JavaScript
  4. Using the clipboard with JavaScript
    • navigator.clipboard
    • navigator.clipboard.writeText
    • navigator.clipboard.readText
    • navigator.clipboard.write
    • navigator.clipboard.read
  5. Conclusion

Let us get started with Copy to clipboard in JavaScript.

Introduction to clipboard

The clipboard is a very useful tool when working on your system, it lets you transfer data (text, images etc.) between applications on your system. In the context of web development, the clipboard proves even more usefull in helping users copy a block of text to reference later, save images and other data on their systems.

Use Cases of Clipboard

Some examples where the clipboard comes in handy include:

  • Copying a block of text from a website to a text editing software like ms word
  • Displaying data copied from other sources in to a web application
  • Copying code snippets from a site to try out on ur system.

The old vs the new technique in JavaScript

Using JavaScript there are two ways in which you can get access to the clipboard, they are:

  1. Using document.execCommand() (This method is now deprecated).
  2. Using navigator.clipboard Interface (The new way).

Using the clipboard with JavaScript

We'll be focusing mainly on accessing the clipboard using the new navigator.clipboard interface because the other method (document.execCommand) is now deprecated (even though it still works on some browsers).
The navigator.clipboard interface is supported by the latest versions of all major browsers. It allows us access the clipboard through the clipboard api which is a property on the navigator object provided by the browser window object. The navigator object is an object which provides information about the user agent (the browser) which is being used to view a web page.You can get access to the navigator object by using window.navigator or just navigator directly in ur code. It provides several properties which include geolocation (used to determine user location), keyboard, languages, maxTouchPoints, onLine(used to determine if browser is online), permissions, clipboard etc. We are only going to focus on the clipboard property of the navigator object because that is all we need to achieve the copy functionality in our code.

The clipboard property on the navigation object is an object which allows a webpage to access the system clipboard in order to read and write data to and from it. The clipboard object has four methods which are:

  • read(): this is used to request for different types of data from the clipboard like images, text etc.
  • readText(): this is used to request for only text content from the clipboard.
  • write(): Using this method different types of data can be written from our webpage to the system clipboard.
  • writeText(): This method only allows us to write text from our webpage to the system clipboard.

All of the clipboards methods are asynchronous (promise based), so in order to use them u have to understand how promises work in JavaScript. Also, while permission to write to the clipboard is granted automatically to the webpage, reading data from the clipboard requires permission from the user. Let's see how to use them with some examples.

Before we start we are going to create a simple webpage with a few elements which we would use to demonstrate how the various clipboard methods work. Code for the webpage is displayed below

    <html>
        <head>
            <title>clipboard methods demonstration</title>
        </head>
        <body>
            <div>
                <input type="text" value="Dummy text" />
                <button onclick="copyText()">Copy Input text</button>
            </div>
    </html>

Above we have a very simple webpage consisting of a div element which contains an input element with a default value of "Dummy text" and a button who's onclick event listener is set to call a function named copyText. With that we have everything we need to work on our first example navigator.clipboard.copyText :). We would add more elements as we work on the other examples.

As mentioned earlier the copyText method allows us to copy text from our webpage on to the clipboard. In our sample webpage we have an input element and a button, we are going to implement the copyText function which is the click event handler of the button. We want to copy the text in the input to the clipboard whenever the button is clicked.

    function copyText(){
        //We start by getting a reference to the input element
        let myInput = document.querySelector("input");
        
        //Use the clipboard's writeText method to pass the inputs text to the clipboard
        navigator.clipboard.writeText(myInput.value).then(res=>{
            console.log("Input data copied to clipboard successfully");
        })
    }

In the code above we implemented the copyText function. In the function we started by getting a reference to the input element. We need the reference in order to be able to get it's value. After getting the reference we proceeded to call the navigator.clipboard.writeText method passing it the input element's value as a parameter. The writeText method is an asynchronous method, it returns a promise when called. We pass a callback function to the then method which is called when the promise resolves. If everything goes well and the text is copied to the clipboard we should see the text "Input data copied to clipboard successfully" in the broswer console.

The readText method allows us to read whatever text has been copied to the clipboard in to our webpage and use it however we want. In order to demonstrate this we are going to add a button to our page then add a click listener to the button so that whenever that button is clicked we get text from the clipboard and diplay it in our page.

    <div>
        <p id="displayText"></p>
        <button onclick="readClipboardText()">Read Clipboard Text</button>
    </div>
    function readClipBoardText(){
        navigator.clipboard.readText().then(text=>{
            document.getElementById("displayText").innerHTML = text;
        })
    }

In the code snippet above we added a div element to our html page, the div element contains a paragraph element with an id of displayText and a button which calls the readClipboardText function when clicked. In the JavaScript part, we implemented the readClipboardText function. In the function we call the readText function on the clipboard object, being an asynchronous function it returns a promise with the clipboard text to us which we handle by passing an arrow function to the then function. Our arrow function accepts the text as a parameter which we display in the displayText element on the page.

The write method of the clipboard object lets us write a variety of data types to the clipboard not just text. In this example, we will copy the contents of a canvas element to the clipboard.

    <canvas id="myCanvas"></canvas>
    <button onClick="copyCanvas('myCanvas')">Copy Canvas</button>
    function copyCanvas(canvasId){
        canvas.toBlob(blob=>{
            let clipboardItem = new ClipboardItem({[blob.type]: blob})
            navigator.clipboard.write([clipboardItem]).then(
                ()=>{
                    console.log("Data written to clipboard successfully")
                },
                err=>{
                    console.log("An error occurred")
                }
            )
        })
    }

In the code snippet above we started by adding a canvas element and a button to our html, when the button is clicked it calls the copyCanvas function passing it the id of the canvas element. The copyCanvas function accepts the id of the canvas, uses it to get a reference to the canvas element. After getting its reference we convert the canvas into a blob before we can copy it to the clipboard. We convert the canvas to a blob by calling its toBlob method which returns a promise that resolves with the blob object. Using the blob we create a clipboard item using the ClipboardItem constructor, now our data is all set to be written to the clipboard. To write our data to the clipboard we use the navigator.clipboard.write function passing it an array containing our clipboardItem. Note currently we can only write one clipboard item at a time. The write function returns a promise which either resolves if the write is successfull or rejects if unsuccessfull. We pass two functions to the then function, the first function is called if the data was written successfully, while the second function is called if an error occurred (the error object is passed to the function as a parameter).

The read method lets us read different types of data from the clipboard, not just text data. In this example we would add a button to our html page, which when clicked will read data from the clipboard using the read method and display read data in the console.

    <button onclick="readData()">Read data</button>
    function readData(){
        navigator.clipboard.read().then(
            clipboardItems=>{
                for(const item of clipboardItems){
                    for(const type of item.types){
                        let blob = await item.getType(type);
                        console.log(URL.createObjectURL(blob));
                    }
                }
             })
         )
    }

In the code snippet above we added a button to the html page. The button's onclick method calls the readData function we defined in our javascript. The readData method when called, starts off by calling the read method on the clipboard object. The read method returns a promise which we handle by passing a function to the then method. The promise resolves with an array of clipboardItems, we iterate over each clipboardItem using the for of loop and then still iterate through the list of types for each item calling the getType function in order to determine the items type. After determining the blobs type we use that information to get the actual blob using the getType() method with the retrieved type as an argument. Finally we display the blobs url in the console.

Conclusion

In conclusion with this article at OpenGenus, the clipboard object is a very usefull tool which makes it easy for developers to provide functionality which allows users to transfer data from the webpage to the clipboard and vice versa. One thing to note is that even though the clipboard property is supported by most popular browsers, their implementations might differ a little bit. So when using the clipboard it maybe usefull to provide fallbacks or error handling in case things break down unexpectedly.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.