1

I have javascript that is being generated at design time that needs to be executed to find a value at run time. The code is stored as a string in an object and I would like to be able to execute it and retrieve the value and then scrap the code. Is there a way to do this? Do I have to use eval()?

6
  • 1
    You can either use eval() or create a <script> node with the script as its contents. Commented May 6, 2013 at 22:30
  • 2
    What is "design time". If the code isn't generated at runtime, why isn't it a function? Commented May 6, 2013 at 22:30
  • @Barmar I'm concerned about using eval since it can be hijacked easily Commented May 6, 2013 at 23:48
  • @Charles Salvia Well, the code is being generated outside of the scope of my app, but prior to actually running it. My application can't be concerned with the actual contents of the script Commented May 6, 2013 at 23:50
  • 1
    That's true of any method that executes user-supplied code. It's not eval that's the problem, it's the fact that you're letting the user supply code. Commented May 6, 2013 at 23:50

2 Answers 2

2

You can use eval(String)

Or use new Function (String)

Or use document.createElement

[edited]

Depend on how it was done your code

1 - if those strings are saved in shared across different pages (with cookies or database), then SERVER-SIDE you can generate a tag <script> with the values ​​saved in a JSON for quick access.

2 - If the strings are saved only at runtime (ie in pagination are not recoverable values) you may not need to save these values ​​in Strings, talves you can create a global Json in Window Object (eg. window.MyObjectGlobal), making the values ​​accessible at any time on the page (since there is no paging) - is idea can also be reused in case of using the SERVER-SIDE, combined with Ajax (ajax only to save the data in your database), or document.cookie (but will have to use document.createElement("script") or eval)

Good luck

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

1 Comment

ok, I knew about these approaches already but I was wondering if there was any way to spin off like a separate javascript engine to execute the code like you can do in a native app.
0

Yes, you can do that using eval.

However, remember evalis evil and it could potentially introduce security risks. Anyway, if you know what you're doing, that's the way to go

2 Comments

I doubt the OP knows what they're doing, otherwise they wouldn't be asking!
true, but I warned him. He should first look up the security concerns I told him about :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.