Search code examples
javascriptiframedesignmode

Inserting Text into a Designmode Iframe Triggered By a Button Outside the Iframe


I have an editable iframe and I would like to insert text at the cursor location when the user clicks a button that is outside the iframe. I am trying to use the following code to insert the text:

function insertAtCursor(iframename, text, replaceContents) {
      if(replaceContents==null){replaceContents=false;}
      if(!replaceContents){//collapse selection:
         var sel=document.getElementById(iframename).contentWindow.getSelection()
         sel.collapseToStart()
      }
      document.getElementById(iframename).contentWindow.document.execCommand('insertHTML', false,     text);
};

I think that this is failing because the focus changes when I go to click the button. However, I am not sure how to correct this. Thank you for your help.


Solution

  • You're correct about the focus shift affecting your code insert.

    Using the jQuery library, you can shift focus back to the iframe in the button's click binding:

    $('#button').click(function(event) {
        event.preventDefault();
        $('#iframe').focus();
        insertAtCursor('iframe', 'test-text', null);
    });
    

    In pure javascript, shift focus before executing insertAtCursor() like so:

    document.getElementById('iframe').focus()