Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h1>Solution #1 (Plain Text only and requires Firefox 22+)</h1> <p>Works for IE6+, FF 22+, Chrome, Safari, Edge (Only tested in IE9+, but should work for lower versions)</p> <p>If you need support for pasting HTML or Firefox &lt;= 22, see Solution #2.</p> <h2>HTML</h2> <pre><code>&lt;div id='editableDiv' contenteditable='true'&gt;Paste&lt;/div&gt; </code></pre> <h2>JavaScript</h2> <pre><code>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); </code></pre> <p>JSFiddle: <a href="https://jsfiddle.net/swL8ftLs/12/" rel="noreferrer">https://jsfiddle.net/swL8ftLs/12/</a></p> <p>Note that this solution uses the parameter 'Text' for the <code>getData</code> function, which is non-standard. However, it works in all browsers at the time of writing.</p> <hr> <h1>Solution #2 (HTML and works for Firefox &lt;= 22)</h1> <p>Tested in IE6+, FF 3.5+, Chrome, Safari, Edge</p> <h2>HTML</h2> <pre><code>&lt;div id='div' contenteditable='true'&gt;Paste&lt;/div&gt; </code></pre> <h2>JavaScript</h2> <pre><code>var editableDiv = document.getElementById('editableDiv'); function handlepaste (e) { var types, pastedData, savedContent; // Browsers that support the 'text/html' type in the Clipboard API (Chrome, Firefox 22+) if (e &amp;&amp; e.clipboardData &amp;&amp; e.clipboardData.types &amp;&amp; e.clipboardData.getData) { // Check for 'text/html' in types list. See abligh's answer below for deatils on // why the DOMStringList bit is needed. We cannot fall back to 'text/plain' as // Safari/Edge don't advertise HTML data even if it is available types = e.clipboardData.types; if (((types instanceof DOMStringList) &amp;&amp; types.contains("text/html")) || (types.indexOf &amp;&amp; types.indexOf('text/html') !== -1)) { // Extract data and pass it to callback pastedData = e.clipboardData.getData('text/html'); processPaste(editableDiv, pastedData); // Stop the data from actually being pasted e.stopPropagation(); e.preventDefault(); return false; } } // Everything else: Move existing element contents to a DocumentFragment for safekeeping savedContent = document.createDocumentFragment(); while(editableDiv.childNodes.length &gt; 0) { savedContent.appendChild(editableDiv.childNodes[0]); } // Then wait for browser to paste content into it and cleanup waitForPastedData(editableDiv, savedContent); return true; } function waitForPastedData (elem, savedContent) { // If data has been processes by browser, process it if (elem.childNodes &amp;&amp; elem.childNodes.length &gt; 0) { // Retrieve pasted content via innerHTML // (Alternatively loop through elem.childNodes or elem.getElementsByTagName here) var pastedData = elem.innerHTML; // Restore saved content elem.innerHTML = ""; elem.appendChild(savedContent); // Call callback processPaste(elem, pastedData); } // Else wait 20ms and try again else { setTimeout(function () { waitForPastedData(elem, savedContent) }, 20); } } function processPaste (elem, pastedData) { // Do whatever with gathered data; alert(pastedData); elem.focus(); } // Modern browsers. Note: 3rd argument is required for Firefox &lt;= 6 if (editableDiv.addEventListener) { editableDiv.addEventListener('paste', handlepaste, false); } // IE &lt;= 8 else { editableDiv.attachEvent('onpaste', handlepaste); } </code></pre> <p>JSFiddle: <a href="https://jsfiddle.net/nicoburns/wrqmuabo/23/" rel="noreferrer">https://jsfiddle.net/nicoburns/wrqmuabo/23/</a></p> <h1>Explanation</h1> <p>The <code>onpaste</code> event of the <code>div</code> has the <code>handlePaste</code> function attached to it and passed a single argument: the <code>event</code> object for the paste event. Of particular interest to us is the <code>clipboardData</code> property of this event which enables clipboard access in non-ie browsers. In IE the equivalent is <code>window.clipboardData</code>, although this has a slightly different API.</p> <p>See resources section below.</p> <hr> <p><strong>The <code>handlepaste</code> function:</strong></p> <p>This function has two branches.</p> <p>The first checks for the existence of <code>event.clipboardData</code> and checks whether it's <code>types</code> property contains 'text/html' (<code>types</code> may be either a <code>DOMStringList</code> which is checked using the <code>contains</code> method, or a string which is checked using the <code>indexOf</code> method). If all of these conditions are fulfilled, then we proceed as in solution #1, except with 'text/html' instead of 'text/plain'. This currently works in Chrome and Firefox 22+.</p> <p>If this method is not supported (all other browsers), then we</p> <ol> <li>Save the element's contents to a <code>DocumentFragment</code></li> <li>Empty the element</li> <li>Call the <code>waitForPastedData</code> function</li> </ol> <hr> <p><strong>The <code>waitforpastedata</code> function:</strong></p> <p>This function first polls for the pasted data (once per 20ms), which is necessary because it doesn't appear straight away. When the data has appeared it:</p> <ol> <li>Saves the innerHTML of the editable div (which is now the pasted data) to a variable</li> <li>Restores the content saved in the DocumentFragment</li> <li>Calls the 'processPaste' function with the retrieved data</li> </ol> <hr> <p><strong>The <code>processpaste</code> function:</strong></p> <p>Does arbitrary things with the pasted data. In this case we just alert the data, you can do whatever you like. You will probably want to run the pasted data through some kind of data sanitising process.</p> <hr> <p><strong>Saving and restoring the cursor position</strong></p> <p>In a real sitution you would probably want to save the selection before, and restore it afterwards (<a href="https://stackoverflow.com/questions/1181700/set-cursor-position-on-contenteditable-div/3323835#3323835">Set cursor position on contentEditable &lt;div&gt;</a>). You could then insert the pasted data at the position the cursor was in when the user initiated the paste action.</p> <h1>Resources:</h1> <ul> <li>MDN paste event: <a href="https://developer.mozilla.org/en-US/docs/Web/Events/paste" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Events/paste</a></li> <li>MSDN clipboard: <a href="https://msdn.microsoft.com/en-us/library/ms535220(v=vs.85).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/ms535220(v=vs.85).aspx</a></li> <li>MDN DocumentFragment: <a href="https://developer.mozilla.org/en/docs/Web/API/DocumentFragment" rel="noreferrer">https://developer.mozilla.org/en/docs/Web/API/DocumentFragment</a></li> <li>MDN DomStringList: <a href="https://developer.mozilla.org/en/docs/Web/API/DOMStringList" rel="noreferrer">https://developer.mozilla.org/en/docs/Web/API/DOMStringList</a></li> </ul> <p>Thanks to Tim Down to suggesting the use of a DocumentFragment, and abligh for catching an error in Firefox due to the use of DOMStringList instead of a string for clipboardData.types</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload