2

I need to be able to preserve line breaks in text displayed on a web page when using a highlight+right click context menu function for a chrome extension.

So the text is displayed like this

Some information on one line
Some on the next line
Then some on the last line

When I highlight it and execute my function, it all gets put into the same line like this

Some information on one line Some on the next line Then some on the last line

Is there any way I can preserve the line spaces when processing my highlighted text in javascript?

Here's my code I'm using to grab the highlighted text:

// Set up context menu at install time.
chrome.runtime.onInstalled.addListener(function() {
  var context = "selection";
  var title = "Get Text";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                       "id": "context" + context});  
});

// add click event
chrome.contextMenus.onClicked.addListener(onClickHandler);

// The onClicked callback function.
function onClickHandler(info, tab) {
  var message = info.selectionText;
  console.log(message);
};
Joshua Terrill
  • 1,995
  • 5
  • 21
  • 40
  • If you have control of the display, can you insert \r\n where it's needed? This would add line breaks in JavaScript. – Seano666 Oct 12 '15 at 22:59
  • Yeah, the thing is, is the text isn't always going to be the same so I'm not always going to know where to put the line breaks. – Joshua Terrill Oct 12 '15 at 23:01
  • Right, but there are dynamic ways to do this in most server-side languages, some sort of Replace() method. Search for the line break character and add /r/n after that, or something to that effect. – Seano666 Oct 12 '15 at 23:07
  • The problem is that my string has no line breaks in it. The variable `message` is one long string. – Joshua Terrill Oct 12 '15 at 23:11
  • Is the content controllable by you, as to what's displaying on the page in the first place? Or are you hoping to click on any web page on the internet and have the line breaks preserved. – Seano666 Oct 12 '15 at 23:23
  • Basically the latter. – Joshua Terrill Oct 12 '15 at 23:24
  • Might be some more useful info here. http://stackoverflow.com/questions/9996540/recognize-multple-lines-on-info-selectiontext-from-context-menu – Seano666 Oct 12 '15 at 23:25
  • If there was a way that I could get the element that the text was in, in jquery or something... that would probably work. – Joshua Terrill Oct 12 '15 at 23:25
  • I think you can inject a content script code into the active tab with `chrome.tabs.executeScript` and access the selection object the way it's done in the linked answer. – wOxxOm Oct 12 '15 at 23:31
  • Basically, you're getting `window.getSelection().toString()` here, which does not take into account while nodes make the line break. It's going to be complex.. Seano666's link provides a way to extract HTML instead of plaintext, but reducing that to plaintext is non-trivial. – Xan Oct 12 '15 at 23:42

0 Answers0