Getting selected text in a browser, cross-platform

Introduction to Range has some details on how different browsers give you access to the text selection.

My experience is that working with these different APIs directly is quite clumsy so if wrapSelection works for you I'd go with that.


Have a look at jQuery and the wrapSelection plugin. It may be what you are looking for.


These days this method should be enough:

function getSelectedText() {
    return window.getSelection ? window.getSelection().toString() : '';
}

It will return '' in rare occasions of really old browsers and may be in the case of Opera Mini (to be tested, though, this may be outdated) + see note for UC Browser for Android.


That jQuery plugin is cool but it accomplishes a very specific task: wrap the text you highlight with a tag. This may be just what you want. But if you don't want to (or are in a situation where you can't) add any extraneous markup to your page, you might try the following solution instead:

function getSelectedText() {
  var txt = '';

  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 

  return txt;
}

This function returns an object representing the text selection. It works across browsers (though I suspect the objects it returns will be slightly different depending on the browser and only dependable for the actual text of the result rather than any of the additional properties).

Note: I originally discovered that code fragment here: http://www.codetoad.com/javascript_get_selected_text.asp