selection

The selection module provides a means to get and set text and HTML selections in the current Firefox page. It can also observe new selections.

Registering for Selection Notifications

To be notified when the user makes a selection, register a listener for the "select" event. Each listener will be called after a selection is made.

function myListener() {
  console.log("A selection has been made.");
}
var selection = require("selection");
selection.on('select', myListener);

// You can remove listeners too.
selection.removeListener('select', myListener);

Iterating Over Discontiguous Selections

Discontiguous selections can be accessed by iterating over the selection module itself. Each iteration yields a Selection object from which text, html, and isContiguous properties can be accessed.

Examples

Log the current contiguous selection as text:

var selection = require("selection");
if (selection.text)
  console.log(selection.text);

Log the current discontiguous selections as HTML:

var selection = require("selection");
if (!selection.isContiguous) {
  for (var subselection in selection) {
     console.log(subselection.html);
  }
}

Surround HTML selections with delimiters:

var selection = require("selection");
selection.on('select', function () {
  selection.html = "\\\" + selection.html + "///";
});

API Reference

Properties

text : string

Gets or sets the current selection as plain text. Setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. Getting the selection when there is no current selection returns null. Setting the selection when there is no current selection throws an exception. Getting the selection when isContiguous is true returns the text of the first selection.

html : string

Gets or sets the current selection as HTML. Setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. Getting the selection when there is no current selection returns null. Setting the selection when there is no current selection throws an exception. Getting the selection when isContiguous is true returns the text of the first selection.

isContiguous : boolean

true if the current selection is a single, contiguous selection, and false if there are two or more discrete selections, each of which may or may not be spatially adjacent. (Discontiguous selections can be created by the user with Ctrl+click-and-drag.)

Events

select

This event is emitted whenever the user makes a new selection in a page.