Home >Web Front-end >JS Tutorial >How Can I Reliably Retrieve Clipboard Data on Paste Across Different Browsers?

How Can I Reliably Retrieve Clipboard Data on Paste Across Different Browsers?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 20:25:11397browse

How Can I Reliably Retrieve Clipboard Data on Paste Across Different Browsers?

Cross-Browser Method to Retrieve Clipboard Data on Paste Event

Problem

Capturing the paste event and accessing the data to be pasted proves challenging across browsers. The goal is to preemptively remove HTML tags from incoming pasted text while preserving existing formatting within the rich text editor.

Solution

Solution #1 (Plain Text Only, Firefox 22 ):

This method works in IE6 , Firefox 22 , Chrome, Safari, and Edge (tested in IE9 ). It excels in capturing plain text but lacks support for HTML pasting or Firefox versions earlier than 22.

function handlePaste(e) {
  // Prevent data from being pasted directly into the div
  e.stopPropagation();
  e.preventDefault();

  // Access the clipboard data through the API
  let clipboardData = e.clipboardData || window.clipboardData;

  // Extract the pasted text
  let pastedData = clipboardData.getData('Text');

  // Process the pasted data as desired
  alert(pastedData);
}

// Register the paste event listener on the editable div
document.getElementById('editableDiv').addEventListener('paste', handlePaste);
<div>

The above is the detailed content of How Can I Reliably Retrieve Clipboard Data on Paste Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn