Getting Selected Text/Cursor Position in Content Editable Element in Iframe

(Matthew G. Saroff) #1

I have a context menu bbCode/HTML tagger (see here), and it works fine on ordinary text boxes, but it does not on contenteditable elements, such as the WYSIWYG modes of the editors in Blogspot and Wordpress, though it does in the code modes.

I want to add this functionality, because I want to add symbols, ™ € ⅔ ® etc., which would be directly useful in rich text editing mode.

For the text mode boxes, I use document.activeElement.value to get the contents of the box, clickedElement.selectionStart to get the start of the selection, and clickedElement.selectionEnd to get the end of the selection, which allows me to process the argument.

For the WYSIWYG mode, all these elements fail, though document.activeElement.contentWindow.document.body.innerHTML does give the contents of the edit window, and I can get the id by using document.activeElement.id;.

What I cannot figure out is how to get the selected text, or the start and end indices of the selection (would be the same if just an insertion point) for a contenteditable type element, at least when inside an iframe. (The case for both Blogspot and Wordpress).

A typical editor iframe looks like this:

<iframe style="padding: 0px; background-color: white; height: 100%;" class="composeBox editable" id="postingComposeBox" name="Rich text editor" aria-label="Edit post. Compose mode." frameborder="0">
   <html style="background:none transparent;min-width:0;">
      <head>
         <style>
<!-- omitted for brevity -->            
         </style>
      </head>
      <body g_editable="true" hidefocus="true" class="editable " id="postingComposeBox" style="min-width: 0px; width: 653px;" role="textbox" contenteditable="true">
         <p>[b][b][b][b][b]aaa[/b]</p>
         <p>bbb</p>
         <p>[b]ccc[/b][/b][/b][/b][/b]</p>
      </body>
   </html>
</iframe>```
0 Likes