Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get selected html in ckeditor

I'm working on a custom generator of link in CKEditor. What I would like to do is getting the html that has been selectioned by the user. I tried a lot of thing, my last function is that

function getTheHtml(editor) {
    var selection = editor.getSelection();
    if (selection.getType() == CKEDITOR.SELECTION_ELEMENT) {
        var selectedContent = selection.getSelectedElement().$.outerHTML;
    } else if (selection.getType() == CKEDITOR.SELECTION_TEXT) {
        if (CKEDITOR.env.ie) {
            selection.unlock(true);
            selectedContent = selection.getNative().createRange().text;
        } else {
            selectedContent = selection.getNative();
        }
    }
    return selectedContent;
}

this works pretty well but I still have issue, if the user select text it works, if he select an image it works but when the user select an image plus some text i only get the text for exemple this is what the user really select

 <img align="" alt="" border="0" class="donotlink" hspace="5" src="image/pic.jpg" vspace="5" />Some Random Text

and this is what i get from my function

Some Random Text

I also tried to do this:

function getSelectionHtml(editor) {
    var sel = editor.getSelection();
    var ranges = sel.getRanges();
    var el = new CKEDITOR.dom.element("div");
    for (var i = 0, len = ranges.length; i < len; ++i) {
        el.append(ranges[i].cloneContents());
    }
    return el.getHtml();
}

but then it select the first closest node and when I try to wrap the selection with the "a" tag it I can't wrap what the user selected in the first place

I know this has been a frequent topic but since I didn't found how to fix... Thanks in advance.

like image 559
ponayz Avatar asked Sep 10 '13 10:09

ponayz


2 Answers

Use range.cloneContents(). With anything selected in your editor, call the following code in the console:

var editor = CKEDITOR.instances.editor1,
    range = editor.getSelection().getRanges()[ 0 ],
    el = editor.document.createElement( 'div' );

el.append( range.cloneContents() );
console.log( el.getHtml() );
like image 174
oleq Avatar answered Oct 28 '22 14:10

oleq


It is working for both image and text.

var selection = CKEDITOR.instances.getSelection();
if (selection.getType() == CKEDITOR.SELECTION_ELEMENT) {
  var selectedContent = selection.getSelectedElement().$.outerHTML;
} else if (selection.getType() == CKEDITOR.SELECTION_TEXT) {
  if (CKEDITOR.env.ie) {
    selection.unlock(true);
    selectedContent = selection.getNative().createRange().text;
  } else {
    selectedContent = selection.getNative();
    console.log("The selectedContent is: " + selectedContent);
  }
}
like image 3
Shafiqul Islam Avatar answered Oct 28 '22 15:10

Shafiqul Islam