JavaScript's Clipboard Copy: Crafting with AI

JavaScript's Clipboard Copy: Crafting with AI

Dive into a reusable JavaScript Clipboard Copy Function crafted with AI, highlighting error handling & best practices.

When it comes to JavaScript, the devil is often in the details. Even seemingly simple functions can contain a world of complexity, especially when we aim to make our code robust, reusable, readable, and adaptable to varying browser capabilities.

Take, for instance, a function that copies text to the clipboard. It might seem straightforward, but there are multiple aspects to consider: What if the Clipboard API is not supported? How can we handle different types of input?

Enter Artificial Intelligence

To address these questions, I embarked on a journey to craft a copyTextToClipboard function that could stand the test of real-world applications. I had an AI partner on this journey: GPT-4.

So why choose this particular function? While I haven't encountered issues with existing Copy To Clipboard functions, the goal was to create one that not only functions effectively but is also built according to the latest JS standards and best practices.

Here's what we developed (Note: Click here to open the below code on CodePen.io)

/**
 * Copies the provided text to the clipboard.
 *
 * @param {string} text - The text to be copied to the clipboard.
 * @returns {Promise} A promise that resolves when the text has been successfully copied, or rejects when an error occurs or the Clipboard API is not supported.
 */
const copyTextToClipboard = (text) => {
  return new Promise((resolve, reject) => {
    // Check if the text is a string and not empty.
    if (typeof text !== "string" || text.trim() === "") {
      reject(new Error("Invalid text: Text should be a non-empty string."));
      return;
    }

    // Check if the Clipboard API is supported.
    if (!navigator.clipboard) {
      reject(new Error("Clipboard API not supported"));
      return;
    }

    // Try to write the text to the clipboard.
    navigator.clipboard
      .writeText(text)
      .then(resolve) // If successful, resolve the promise.
      .catch(reject); // If an error occurs, reject the promise with the error.
  });
};

So, why should you consider using this function over others? Here are some key reasons:

  1. Robust Error Handling: This function checks if the Clipboard API is supported and ensures that the text to be copied is a non-empty string. This makes it more robust against potential misuse.

  2. Asynchronous Operation: The function leverages JavaScript Promisesfor asynchronous execution, making it compatible with async/await syntax and suitable for applications that need non-blocking operations.

  3. Code Best Practices: The function is designed with modern JavaScript best practices in mind, from the use of const for function declaration, arrow functions, to template strings.

Learn To Prep AI Before Asking Questions

Working with GPT on this was quite an experience. I learned the hard waythat it's essential to define GPT's persona and provide as much context as possible-the more precise and specific the instructions, the more satisfactory and applicable the results.

Here's an example of what I asked GPT:

Act as a JavaScript Developer using the latest stable ECMA Script standards that are supported on modern browsers. You only write robust, reusable, readable, well-documented, performant, and secure code that conforms to best practices for production environments. Perform a code review of the following JavaScript function and if it fails your standards and practices, rewrite it with explanations of what you changed and why:

I then pasted a version of copyTextToClipboard that I felt was quite good.

In response, GPT not only followed my instructions but also added additional value, enhancing readability, reusability, and error handling in the function. The collaboration resulted in a piece of code I was happy to add to my project.

Considerations

It's important to understand the caveats when working with a function like this:

  1. The use of the Clipboard API: The Clipboard API requires permissionand only works in a secure context (HTTPS), which could limit the usability of your function in some situations.

  2. Browser Compatibility: Although the Clipboard API is widely supported, there may be compatibility issues with older browsers or less popular ones that do not fully support this API.

  3. Performance: While this function is unlikely to be a performance bottleneck, one has to keep in mind that varied results could occur depending on the size of the text to be copied.

Closing

As we continue to adopt AI tools like GPT and Google Bard in our coding journeys, we not only enhance our coding practices but also create new opportunities for innovation and improvement.

Feel free to use this function in your projects and, more importantly, reference this function on CodePen.io for the latest version.

Till next time - John 🙂