Detecting and Retrieving Pasted Data in JavaScript (Cross-Browser)
Web applications often need to capture and pre-process data before it is pasted into a text editor. This may involve removing specific elements, such as HTML tags, while preserving existing formatting. However, traditional post-paste sanitization techniques can disrupt previous text formatting.
To address this challenge, let's explore a solution that utilizes modern browser APIs to intercept paste events and retrieve pasted data:
Solution #1: Plain Text Extraction (Firefox 22 and Modern Browsers)
For browsers supporting the DataTransfer API (e.g., IE9 , Firefox 22 , Chrome, Safari, Edge), the following approach allows selective extraction of plain text from the clipboard data:
function handlePaste(e) { var clipboardData, pastedData; // Stop data actually being pasted into div e.stopPropagation(); e.preventDefault(); // Get pasted data via clipboard API clipboardData = e.clipboardData || window.clipboardData; pastedData = clipboardData.getData('Text'); // Do whatever with pasteddata alert(pastedData); } document.getElementById('editableDiv').addEventListener('paste', handlePaste);
This solution leverages the e.clipboardData.getData('Text') method to extract the plain text content from the data transferred during the paste event.
The above is the detailed content of How Can I Intercept and Extract Plain Text from Pasted Data in JavaScript Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!