Backed out changeset b71c8c052463 (bug 1943846) for causing mass failures. CLOSED...
[gecko.git] / devtools / client / webconsole / utils / clipboard.js
blob72b064f323dfc29979cc075ea5d6619cabf8a1b0
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/. */
5 "use strict";
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.
15 * As the Selection API is exposed through the Window object, if we don't have a window
16 * we fallback to `HTMLElement.textContent`.
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.
21 function getElementText(el) {
22 if (!el) {
23 return null;
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;
30 if (!win) {
31 return el.textContent;
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();
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();
46 // Finally we revert the selection to what it was.
47 selection.removeRange(range);
48 if (currentSelectedRange) {
49 selection.addRange(currentSelectedRange);
52 return text;
55 module.exports = {
56 getElementText,