Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript using replace method inside an iframe

I wonder if it's possible to replace certain words inside an iframe.

I've used jQuery to change the content inside the iframe with the same content, but with replacements. The problem here is that 'the cursor resets' to the start of the input field, so you have to write from start again.

So here is what I did

<html>
<head>
<script>
function iFrameOn(){
    richTextField.document.designMode = 'On';
}

</script>
</head>
<body onLoad="iFrameOn();">

<!-- Hide(but keep)your normal textarea and place in the iFrame replacement for it -->
<textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
<iframe name="richTextField" id="richTextField" style="border:#000000 1px solid; width:100px; height:20px;">
</iframe>
<!--End replacing your normal textarea -->
</p>
<script>
      function ReplaceWords(){
          var textfield = document.getElementById("richTextField");

          textfield.contentWindow.document.body.onkeyup = function(e){
              var content   = textfield.contentWindow.document.body.innerHTML;
              var Fixed_Content = content.replace("hey", "yo");
              $(document).ready(function() {
                  $('#richTextField').contents().find('body').html(Fixed_Content);
              });
          };
        };
      ReplaceWords();
</script>

</body>
</html>

The question is: if you can replace some of the content inside the iframe without the cursor resets, because it's not appreciated when you type and it just starts from start again.

Update: Basically it's not the textarea that is in focus, it's hidden inside the iframe therefore I use document.designMode = 'On';.

I have updated the post again, this is how it should have been from the start.

Link to jsfiddle: https://jsfiddle.net/tqf3v2sk/8/

like image 598
Frederik Avatar asked Jan 05 '16 08:01

Frederik


People also ask

Can you use JavaScript in an iframe?

It is called an inline frame because to the user it is all one web page. The child iframe is a complete browsing environment within the parent frame. It can load its own JavaScript and CSS separate from the parent.

Can I get element inside iframe?

Getting the element in IframegetElementById() method by passing iframe id as an argument. const iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.

Can you edit content in an iframe?

You can't edit the content of an iframe tag.

Can we use Replace in HTML?

The JavaScript replace() method is used to replace any occurrence of a character in a string or the entire string. It searches for a string corresponding to either a particular value or regular expression and returns a new string with the modified values.


1 Answers

Working with iFrames in the same domain is not much different from working with DOM elements. You just have to make sure the methods you use are called on the proper window and document object. But once you target correctly the window and document, you can call them from the parent window pretty much in the same way as if it was in the same window as your script.

As for replacement while you type, there are a couple of ways to to it. One way would be to use document.execCommand('insertText') and Selection. You detect if the key being entered matches last character of the word to replace, if so you select the length of the word to replace and check if it matches. If it matches, you call execCommand and it'll replace it leaving the cursor at the end of the replacement.

function replaceOnKeyDown(e, toReplace, replaceWith) {

  var iptFld = e.target;
  var lastLetter = toReplace[toReplace.length - 1];
  var keyEntered = String.fromCharCode(e.keyCode);
    console.log(keyEntered)
  // To make it more efficient, you can call the rest only if the
  // key just pressed is the same as the last of the word you
  // need to replace.
  if (lastLetter.toLowerCase() === keyEntered.toLowerCase()) {
    // Set selection to your word length
    var range = frameWindow.getSelection().getRangeAt(0);
    var caretPosition = range.startOffset;
    // Since you're on key down, the caret position is before the
    // last letter is entered.
    var toReplaceStart = caretPosition - toReplace.length + 1;

    range.setEnd(range.startContainer, caretPosition);
    range.setStart(range.startContainer, toReplaceStart);
    frameWindow.getSelection().addRange(range);
    // Check if the selection matches the word to replace
    // Since you're on mouse down, the range will only include 
    // up until the letter being entered. So you need to validate
    // that the word without the last letter equals
    // the selection.
    if (range.toString() + lastLetter === toReplace) {

      frameDocument.execCommand('insertText', false, replaceWith);
      // prevent last letter to be entered
      e.preventDefault();

    } else {

      frameWindow.getSelection().collapse(range.startContainer, caretPosition);

    }
  }
}

var textfield = document.getElementById("richTextField");
var frameWindow = textfield.contentWindow
var frameDocument = frameWindow.document
frameDocument.designMode = 'on'
frameDocument.body.onkeydown = function(e) {
  replaceOnKeyDown(e, 'hey', 'yo')
};

https://jsfiddle.net/k0qpmmw1/6/

like image 72
Julien Grégoire Avatar answered Sep 20 '22 09:09

Julien Grégoire