Skip to content
jshacks.dev
Browser

How to Handle Paste Events in JavaScript

Handle paste events in JavaScript with clipboardData: read text, HTML and files, strip formatting, paste images, sanitize input and keep undo working.

8 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Google Chrome, Socket.io and Redis logos.

Pasting is one of the most common things people do in a form, and the page rarely sees it coming. A phone number arrives with spaces and dashes, a name with trailing whitespace, a table from a spreadsheet, a screenshot from the clipboard, a block of formatted text from a document that carries its fonts and colors along. The paste event gives your code a chance to look at the data before it lands, and to change what happens: clean it, split it across fields, upload an image or refuse it. The event is simple, but the clipboard carries data in several formats at once, handling it wrongly breaks undo and security rules apply to what you insert. This guide shows how to handle paste events in JavaScript: the paste event and clipboardData, reading plain text, HTML and files, cleaning and normalizing input, inserting text at the caret without breaking undo, pasting into a contenteditable element and stripping formatting, handling pasted images and files, splitting a pasted code across several inputs, security considerations, the asynchronous Clipboard API as an alternative and testing. The APIs are documented on MDN and work in all current browsers.

The paste event

A paste event fires on the focused editable element, an input, textarea or an element with contenteditable, or on the document when nothing is editable, when the user pastes with the keyboard, the context menu or a menu command. It is cancelable: calling preventDefault() stops the browser from inserting the data, so that you can do it yourself. The data is in event.clipboardData, a DataTransfer object.

basic.jsJavaScript
const field = document.querySelector("#phone");

field.addEventListener("paste", (event) => {
  const text = event.clipboardData.getData("text/plain");
  console.log("pasted:", JSON.stringify(text));
});
Text
pasted: "+1 (555) 010-9999\n"

The event does not fire for programmatic changes to the value, and it is not the same as the input event, which fires after the value has changed. Use paste when you need to inspect or alter the data before it is inserted, and input to react to the result of any change.

What the clipboard holds

The clipboard can store the same content in several formats, listed in clipboardData.types. Copying text from a web page typically provides text/plain and text/html. Copying cells from a spreadsheet provides text/plain with tabs and newlines, and text/html with a table. Copying a file in the file manager provides Files. A screenshot provides an image file. You pick the format you want with getData(type) for text formats or read clipboardData.files for files.

types.jsJavaScript
field.addEventListener("paste", (event) => {
  const data = event.clipboardData;
  console.log([...data.types]);
  console.log(data.files.length);
  console.log([...data.items].map((item) => `${item.kind}:${item.type}`));
});
Text
[ 'text/plain', 'text/html' ]
0
[ 'string:text/plain', 'string:text/html' ]

The items list gives each entry with a kind, string or file, and a type. Use item.getAsFile() for file items and item.getAsString(callback) for strings, though getData() is simpler for text. Reading must happen synchronously inside the event handler, because the data is available only while the event is being dispatched.

Clean pasted text in an input

A common task is normalizing what the user pasted: trimming, removing separators and keeping only the characters that are valid. Prevent the default, clean the text and insert it at the caret, replacing any selection.

clean.jsJavaScript
const phone = document.querySelector("#phone");

phone.addEventListener("paste", (event) => {
  event.preventDefault();
  const raw = event.clipboardData.getData("text/plain");
  const cleaned = raw.replace(/[^\d+]/g, "").slice(0, 16);

  phone.setRangeText(cleaned, phone.selectionStart, phone.selectionEnd, "end");
  phone.dispatchEvent(new Event("input", { bubbles: true }));
});
Text
(pasting "+1 (555) 010-9999" inserts "+15550109999")

setRangeText() replaces the selected range of an input or textarea and, with the "end" mode, moves the caret after the inserted text. It does not create an undo step in all browsers, and it does not fire an input event, so the code dispatches one, so frameworks and validators see the change. If undo is important, prefer the next technique.

Insert text and keep undo working

Setting the value of an input directly clears the browser's undo history for that field. The document.execCommand("insertText") command inserts at the caret and participates in undo, in all browsers where the field has focus. It is deprecated in the specification but remains the only way to insert text while keeping the native undo stack, and it is widely supported.

undo.jsJavaScript
field.addEventListener("paste", (event) => {
  event.preventDefault();
  const text = event.clipboardData.getData("text/plain").trim();

  if (!document.execCommand("insertText", false, text)) {
    field.setRangeText(text, field.selectionStart, field.selectionEnd, "end");
    field.dispatchEvent(new Event("input", { bubbles: true }));
  }
});
Text
(the pasted text is inserted, and Ctrl+Z removes it in one step)

The fallback to setRangeText() covers the case where the command is unavailable. Check how your target browsers behave, since this area has quirks, and keep the interception light: when the default behavior is acceptable, do not prevent it, and clean up afterwards in the input event.

Paste plain text into a rich editor

In a contenteditable element, the default paste inserts the source's HTML, with its fonts, colors and sometimes enormous amounts of markup from word processors. Many editors want plain text, or a restricted set of formatting.

rich.jsJavaScript
const editor = document.querySelector("#editor");

editor.addEventListener("paste", (event) => {
  event.preventDefault();
  const text = event.clipboardData.getData("text/plain");
  document.execCommand("insertText", false, text);
});
Text
(pasted formatting is dropped and only the text is inserted)

To keep some formatting safely, read text/html, sanitize it with an allow list of tags and attributes, and insert the result with insertHTML. Never insert clipboard HTML as it is: it is untrusted, and can contain scripts in event attributes, hidden content and tracking markup. Use Element.setHTML() where supported or a sanitizer library such as DOMPurify.

html.jsJavaScript
editor.addEventListener("paste", (event) => {
  const html = event.clipboardData.getData("text/html");
  if (!html) return;

  event.preventDefault();
  const clean = DOMPurify.sanitize(html, {
    ALLOWED_TAGS: ["p", "br", "strong", "em", "ul", "ol", "li", "a"],
    ALLOWED_ATTR: ["href"],
  });
  document.execCommand("insertHTML", false, clean);
});
Text
(only paragraphs, line breaks, emphasis, lists and links survive the paste)

Pasted images and files

When the clipboard contains files, such as a screenshot, clipboardData.files lists them. Handle them for features like "paste an image to attach it", and preview or upload them.

image.jsJavaScript
document.addEventListener("paste", (event) => {
  const files = [...event.clipboardData.files].filter((file) => file.type.startsWith("image/"));
  if (files.length === 0) return;

  event.preventDefault();
  for (const file of files) {
    const url = URL.createObjectURL(file);
    const img = document.createElement("img");
    img.src = url;
    img.alt = "Pasted image";
    img.width = 200;
    img.addEventListener("load", () => URL.revokeObjectURL(url), { once: true });
    document.querySelector("#attachments").append(img);
    console.log(file.name, file.type, file.size);
  }
});
Text
image.png image/png 48213

A pasted screenshot has a generic name such as image.png, so give it a better one before upload. Check the type and the size before accepting. For uploads, append the file to a FormData and send it, as covered in the guides on uploading files. When you copy an image from a web page, browsers may provide only HTML containing an <img> tag, not the file, so also look at text/html if you need to support that.

Split a pasted code across fields

One-time codes are often entered in separate boxes, one digit each. A paste into the first box should distribute the characters.

otp.jsJavaScript
const boxes = [...document.querySelectorAll(".otp-digit")];

boxes[0].addEventListener("paste", (event) => {
  event.preventDefault();
  const digits = event.clipboardData.getData("text/plain").replace(/\D/g, "").slice(0, boxes.length);

  boxes.forEach((box, index) => {
    box.value = digits[index] ?? "";
  });
  boxes[Math.min(digits.length, boxes.length - 1)].focus();
});
Text
(pasting 482913 fills six boxes and focuses the last one)

Better still, use a single input with autocomplete="one-time-code" and inputmode="numeric", styled to look like boxes, which works with autofill from text messages and keeps paste trivial.

Limits and confirmation

Reject data that does not fit. A paste into a field with a maximum length should stop at the limit, and tell the user when it truncated. A paste of thousands of characters into a small field is likely a mistake. For a table paste, parse the rows and columns: text/plain from spreadsheets separates cells with tabs and rows with newlines, which you can split into a two-dimensional array.

table.jsJavaScript
function parseTable(text) {
  return text
    .replace(/\r\n/g, "\n")
    .replace(/\n$/, "")
    .split("\n")
    .map((row) => row.split("\t"));
}

console.log(parseTable("name\tqty\nPen\t3\nBook\t1\n"));
Text
[ [ 'name', 'qty' ], [ 'Pen', '3' ], [ 'Book', '1' ] ]

Values that contain tabs or newlines are quoted in the spreadsheet's output, so a robust parser handles quotes, or reads text/html and parses the table element.

Security and privacy

Pasted content is untrusted input. Do not insert it as HTML without sanitizing, do not execute it, validate it as you would any form field and enforce limits on the server, as the client can be bypassed. Be careful about what you do with pasted files, scan or restrict them as appropriate. Avoid sending clipboard content to a server without the user knowing, since people paste passwords and personal information. Note that a paste handler sees the clipboard only when the user performs a paste in your page, and cannot read it silently, unlike a script that tries to call navigator.clipboard.readText(), which needs permission.

The Clipboard API alternative

A custom "Paste" button cannot use the event, since there is no user paste action. It can call navigator.clipboard.readText() or read() from a click, in a secure context, and the browser asks for permission or shows a small paste prompt. Use it for such buttons, and use the event for real pastes.

button.jsJavaScript
document.querySelector("#paste-button").addEventListener("click", async () => {
  try {
    const text = await navigator.clipboard.readText();
    document.querySelector("#coupon").value = text.trim();
  } catch {
    console.log("Clipboard access was not allowed. Use Ctrl+V instead.");
  }
});
Text
(the coupon field is filled from the clipboard when the user allows it)

Test paste handling

In tests, create a ClipboardEvent with a DataTransfer, or use a browser driver that can paste for real. A synthetic version looks like this.

test.jsJavaScript
const data = new DataTransfer();
data.setData("text/plain", "+1 (555) 010-9999");

const event = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true });
phone.dispatchEvent(event);

console.log(event.defaultPrevented, phone.value);
Text
true +15550109999

Also test in each browser by pasting real data from a spreadsheet, a word processor, a web page and an image, since the formats differ, and check that undo and redo behave sensibly after a handled paste.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.