AllocSystems
AllocSystems

Reputation: 1089

Executing jquery from a textarea

I created a little project to execute javascript inside a textarea using eval()

HTML

<textarea id='js'><textarea>

<iframe id="inlineframe"></iframe>

JAVASCRIPT

(function(){
$('#js').on('keyup', runjs);
});

function runjs(){ document.getElementById('inlineframe').contentWindow.eval($('#js').val());
}

It works great? But what if I didn't just want to execute javascript? What if I wanted it to execute jquery? How to I include that in the function?

Upvotes: 0

Views: 54

Answers (1)

0xnoob
0xnoob

Reputation: 1057

There are a few bugs in your HTML and JS.

  • no closing textarea tag, just another textarea element (forgot the /)
  • you have an anonymous function encapsulated but don't call it (forgot the () at the end, so it isn't an IIFE)

besides that, there is a simple way to add jQuery to the iFrame: By adding a src attribute to the iFrame and point it to another html-file which has jQuery included just like your current html-file.

If you don't want to create another file, you can add the jQuery file via JS like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="js"></textarea>
<iframe id="inlineframe"></iframe>
<script>
  function runjs() {
    document
      .getElementById("inlineframe")
      .contentWindow.eval($("#js").val());
  }
  (function() {
    $("#js").on("keyup", runjs);
  })();

  const iFrameHead = document.getElementById("inlineframe").contentDocument
    .head;
  const script = document.createElement("script");
  script.src =
    "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js";
  iFrameHead.appendChild(script);
</script>

Upvotes: 1

Related Questions