8

We are developing a Chrome extension in which we tried to get the selected text in a browser tab. To do so, we are using a context menu option but we got an empty string as selected text by using the following method in background.js:

window.getSelection().toString()

Then referred this link and changed the method to get the selected text as:

chrome.contextMenus.create({
  title: "Click",
  contexts: ["selection"],
  onclick: function(info, tab) {
    selectedText = info.selectionText;
  };
});

Using this method we are able to get the selected text as string (single line) but with no line break. Is it possible to get the selected text while preserving line breaks?

For example, if the selected content is:

Text first line
Text second line

We are getting the selected text as Text first line Text second line (on a single line, with no line break).

rd3n
  • 4,440
  • 1
  • 33
  • 45
Barani
  • 552
  • 4
  • 18
  • Unclear what you're asking. Examples, more code are welcome. – Xan Sep 02 '14 at 11:56
  • I'm not testing in a Chrome extension (just running a console on a regular page in Chrome) and I do see newlines in my result. For example, in your example on this page, if I select the final `e` of the first line and the first `T` of the second line, when I run `window.getSelection().toString()[1] == "\n"`, I get `true`. – apsillers Sep 02 '14 at 15:27
  • 1
    Ya It's working in console but if we used this in background.js inside chrome.contextMenus.create gives empty string. (corrected my question) – Barani Sep 06 '14 at 07:27
  • 2
    I'm encountering this issue too even in manifest v3 8 years after the original question was posted - newlines are converted to space characters from `selectionText` entered from a text file page. Firefox doesn't have this problem. – wesinat0r Jul 21 '22 at 03:00

0 Answers0