Skip to content

Instantly share code, notes, and snippets.

@garyfeng
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garyfeng/12a05ca337124a993b04 to your computer and use it in GitHub Desktop.
Save garyfeng/12a05ca337124a993b04 to your computer and use it in GitHub Desktop.
collection of code to work with bookmarks in CKEditor
// see range.js and selection.js for the source
// so we have 3 things to work with:
// CKEditor.dom selections, ranges, and bookmarks
// first, to get the CKeditor instance, use
var editor = CKEDITOR.instances.editor1;
// selection something in the editor, and get the selection:
var sel = editor.getSelection();
// make the selection to a range array
var ranges = sel.getRanges();
// to create bookmarks version 2 out of the ranges
var bm = ranges.createBookmarks2()
// ok, now you can selection something else in the editor
// and we will restore the bookmark
// this will return in the console a selection object.
CKEDITOR.instances.editor1.getSelection().selectBookmarks(bm)
// select ranges
CKEDITOR.instances.editor1.getSelection().selectRanges(ranges)
// there is a built-in function to get selected text
// but it returns an empty string for paragraph boundaries
// meaning that if there are two paragraphs, the texts will be jointed
// without new line marks \n\n
CKEDITOR.instances.editor1.getSelection().getSelectedText();
// to calcualte the text position of a bookmark
// create a new bookmark that is [1,0,0]+0 to start+startOffset
// say the current bookmark is
var bm1= {"start":[1,1,0],"startOffset":36,"end":null,"endOffset":36,"text":"","collapsed":true}
// we make something like
var bm2= {"start":[1,0,0],"startOffset":0,"end":[1,1,0],"endOffset":36,"text":"","collapsed":false}
// then we get a clone of the selection as a documentFragment
// then we get the text using html2text(frag).length
@garyfeng
Copy link
Author

the problem with this approach is that it will change the actual selection, unless we have a shadow DOM.

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