Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save Noitidart/9374173 to your computer and use it in GitHub Desktop.

Select an option

Save Noitidart/9374173 to your computer and use it in GitHub Desktop.
_ff-addon-snippet-HighlightTextInDocument - This takes from http://mxr.mozilla.org/mozilla-release/source/toolkit/modules/Finder.jsm#225 to try to highlight text in document.
function _getEditableNode(aNode) {
while (aNode) {
if (aNode instanceof Ci.nsIDOMNSEditableElement)
return aNode.editor ? aNode : null;
aNode = aNode.parentNode;
}
return null;
}
function _highlightRange(aRange, aController) {
let node = aRange.startContainer;
let controller = aController;
let editableNode = this._getEditableNode(node);
if (editableNode)
controller = editableNode.editor.selectionController;
let findSelection = controller.getSelection(Ci.nsISelectionController.SELECTION_FIND);
findSelection.addRange(aRange);
if (editableNode) {
// Highlighting added, so cache this editor, and hook up listeners
// to ensure we deal properly with edits within the highlighting
if (!this._editors) {
this._editors = [];
this._stateListeners = [];
}
let existingIndex = this._editors.indexOf(editableNode.editor);
if (existingIndex == -1) {
let x = this._editors.length;
this._editors[x] = editableNode.editor;
this._stateListeners[x] = this._createStateListener();
this._editors[x].addEditActionListener(this);
this._editors[x].addDocumentStateListener(this._stateListeners[x]);
}
}
}
function _getSelectionController(aWindow) {
// display: none iframes don't have a selection controller, see bug 493658
if (!aWindow.innerWidth || !aWindow.innerHeight)
return null;
// Yuck. See bug 138068.
let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell);
let controller = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsISelectionDisplay)
.QueryInterface(Ci.nsISelectionController);
return controller;
}
/*******************/
var doc = gBrowser.contentDocument;
var searchRange = doc.createRange();
searchRange.selectNodeContents(doc.documentElement);
_highlightRange(searchRange, _getSelectionController(gBrowser.contentWindow));
@Noitidart
Copy link
Copy Markdown
Author

README

Rev1

  • Work in progress - does not do anything yet, line 57 throws error obviously

Rev2

  • Copy paste working example. Highlights all text in the currently selected tab.
  • Beautified the code as well

Rev3

  • Updated file name to include snippet as word

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment