Intercepting Clipboard Events with JavaScript

Hero image for Intercepting Clipboard Events with JavaScript. Image by Victor Li.
Hero image for 'Intercepting Clipboard Events with JavaScript.' Image by Victor Li.

The JavaScript copy event allows us to react to clipboard events within our web applications. Although still in a working draft state, support is pretty good across modern browsers.

Handling this event we are able to modify clipboard contents, but cannot read from the clipboard data (as this would otherwise be a security concern). What can do however is use window.getSelection() to identify the highlighted items.

Implementing this is as simple as tying an event listener to document:

document.addEventListener('copy', handleClipboard);

From there, we can modify what happens. If we really just wanted to stop people from being able to copy at all, we can just use event.preventDefault():

const handleClipboard = e => e.preventDefault();

My use for this is a little involved: I want to make sure that people can copy off my website, but I also want to make sure that they are aware that they are copying copyrighted work.

const handleClipboard = (e) => {  const selection = window.getSelection().toString();  const thisURL = `https://johnkavanagh.co.uk${window.location.pathname}`;  const copyright = `Copyright (c) ${getCurrentYear()} John Kavanagh. All rights reserved.`;  const source = `Original source: https://johnkavanagh.co.uk${window.location.pathname}`;  const newClipboard = `${selection}\n\n${copyright}\n${source}`;  e.clipboardData.setData('text/plain', newClipboard);  e.preventDefault();};

What this is doing is:

  1. Getting the selected text from the window object, as a string;
  2. Building a copyright notice (over two lines);
  3. Combining the selection and copyright notice together with line breaks;
  4. Placing this within the clipboard (in place of the original copy) via setData.

When you paste back off your clipboard you will get:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fringilla arcu.Copyright (c) 2021 John Kavanagh. All rights reserved. Original source: https://johnkavanagh.co.uk/page-visited/

You can easily extend this yet further to avoid the copyright notice from being injected where the user is for example only copying out of a <code> or <pre> block:

const { path } = e;const { tagName } = path[0];const isCode = tagName === 'PRE' || tagName === 'CODE';if (isCode) {  return;}

I also modify this a little further so that I can avoid intercepting very short copies (e.g., where somebody is copying my email address), and to generate a store of what has been copied off the site to try and head off potential duplicate content issues. You can probably work those bits out for yourself, though!


Categories:

  1. Accessibility
  2. Development
  3. Front‑End Development
  4. JavaScript