0

I'm wondering if it's even possible to save some js code and pull it up later and execute.

There are basically two problems I'm facing:

  • How to stringify the javascript code?
  • How to execute the stringified javascript code?

1 Answer 1

2

You should be able to retrieve the text blob and dynamically drop it inside a <script> tag.

This works in the Chrome and MSIE 9 consoles - I didn't try Firefox yet:

var s = document.createElement('script'); s.appendChild(document.createTextNode('alert("hello")')); document.head.appendChild(s); 

As for stringifying the code, it's normally possible to call myFunction.toString() on user supplied functions.

Sign up to request clarification or add additional context in comments.

13 Comments

@Imp because eval is evil and can almost always be avoided.
We are targeting QT webkit, so if it works on chrome, it should work for us for the most part too. Do you think it's possible to use .toString() on the whole Javascript MVC class? Or would you suggest to wrap them into a function and use myFn.toString() ?
@shershams dunno - suggest you just try it! ;-) Note that anything wrapped up in an immediately invoked function expression won't work - you need some sort of handle to the function.
@Alnitak But why is eval evil? Because someone said so? No, it is because opens space for malicious code. But in this case, you are downloading your own code and it absolutely no difference if you put it in eval or <script>. Besides, eval is well implemented in all browsers - on the other hand, dynamically adding scripts with <script> tag works a little different on different browser (done wrong way, the code wouldn't execute).
IE treats <script> and <style> tags in a special way, as they don't represent visible elements of the page. It is impossible to append a text node as a child to these elements in IE.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.