clipboard.js (1893B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 /** 8 * Get the text of the element parameter, as provided by the Selection API. We need to 9 * rely on the Selection API as it mimics exactly what the user would have if they do a 10 * selection using the mouse and copy it. `HTMLElement.textContent` and 11 * `HTMLElement.innerText` follow a different codepath than user selection + copy. 12 * They both have issues when dealing with whitespaces, and therefore can't be used to 13 * have a reliable result. 14 * 15 * As the Selection API is exposed through the Window object, if we don't have a window 16 * we fallback to `HTMLElement.textContent`. 17 * 18 * @param {HTMLElement} el: The element we want the text of. 19 * @returns {string | null} The text of the element, or null if el is falsy. 20 */ 21 function getElementText(el) { 22 if (!el) { 23 return null; 24 } 25 // If we can, we use the Selection API to match what the user would get if they 26 // manually select and copy the message. 27 const doc = el.ownerDocument; 28 const win = doc && doc.defaultView; 29 30 if (!win) { 31 return el.textContent; 32 } 33 34 // We store the current selected range and unselect everything. 35 const selection = win.getSelection(); 36 const currentSelectedRange = 37 !selection.isCollapsed && selection.getRangeAt(0); 38 selection.removeAllRanges(); 39 40 // Then creates a range from `el`, and get the text content. 41 const range = doc.createRange(); 42 range.selectNode(el); 43 selection.addRange(range); 44 const text = selection.toString(); 45 46 // Finally we revert the selection to what it was. 47 selection.removeRange(range); 48 if (currentSelectedRange) { 49 selection.addRange(currentSelectedRange); 50 } 51 52 return text; 53 } 54 55 module.exports = { 56 getElementText, 57 };