0

I'm currently working on a web editor where you can enter your HTML, CSS and JavaScript code and see the result in real time. Something similar to JSBin or JSFiddle. (I'm doing that to get an offline editor)

I've already been through many problems especially when it comes to CSS but I solved them by using an iframe and injecting all my code into it. And that works amazingly well until you type some JavaScript.

I'm sending the code between <script></script> but unlike CSS it won't run. What's very weird is that when I enter something like $('button').css('color', 'red');, the buttons of the editor effectively get affected but not those of my iframe. Exactly the opposite of what I expected. I've tried many things, looked at many topics on the forum, but nothing works. I also tried to load a blank page in my iframe. In that case, JavaScript runs but it becomes impossible to edit the code in the iframe! What's going on? Where am I going wrong? Thank you in advance for your help!

Here's my editor : https://jsbin.com/tuqite/edit?html,js,output/

Robin Dos Anjos
  • 309
  • 2
  • 11
  • See http://stackoverflow.com/questions/22740665/using-textareas-to-display-live-results-in-iframe-using-jquery-add-separate-te – guest271314 Apr 15 '16 at 15:35
  • Erm.. It doesn't really help... – Robin Dos Anjos Apr 15 '16 at 15:53
  • the js code is run in the parent that is why its affecting the buttons of the editor. – rajesh Apr 15 '16 at 16:11
  • So my question is, how to avoid this behavior? I want the code to be run inside the iframe. – Robin Dos Anjos Apr 15 '16 at 16:14
  • Not sure how you are running it. But i think you can try this way. Keep a js function in the iframe. And put your js code inside that function. and after the content is updated. try calling this function from the parent. some thing like: document.getElementById("childFrame").contentWindow.RunCode(); – rajesh Apr 15 '16 at 16:17

1 Answers1

1

Try updating the content of the iframe like this.

// this string contains both html and script
var html_string= "content";
document.getElementById('childFrame').src = "data:text/html;charset=utf-8," + escape(html_string);

By directly updating the iframe DOM like the way you are doing may not be the right way .

rajesh
  • 2,354
  • 1
  • 12
  • 15