Reputation: 964
I'm trying to run javascript code from a textarea. At the beginning I though of using eval, according to this question, but according to the answers eval is not the best way for accomplishing this.
Later I found this question, which talks about many alternatives libraries I could use. I try some but the documentation wasn't so clear or the projects are death.
One of the only "solutions" I found is the js.js lib. But there's not documentation (or I don't get it how it works from the examples) explaining how to pass the code I have from the textarea to the lib.
Do you know a lib for doing this? Does the webworker will work? Any idea in how I can accomplish this?
Thanks
Upvotes: 0
Views: 827
Reputation: 6684
I think if you do actually want to run whatever arbitrary Javascript the user enters, and you're ok with the security implications of that, then eval
is a reasonable way to do it. If the code the user enters is never saved then it might be ok, but if the text in the textarea could have been entered by another user, then no. In that case maybe this will be helpful: How can I sandbox untrusted user-submitted JavaScript content? .
Here's an example of using Caja to execute some Javascript as a string:
<html>
<head>
<title>Caja host page</title>
<script type="text/javascript"
src="//caja.appspot.com/caja.js">
</script>
</head>
<body>
<h1>Caja host page</h1>
<div id="guest"></div>
<script type="text/javascript">
caja.initialize({
cajaServer: 'https://caja.appspot.com/',
debug: true
});
caja.load(document.getElementById('guest'), undefined, function(frame) {
// This URL is actually ignored and yet the caja API requires
// a URL to be passed and for it not to be null or empty (!)
var url = 'http://example.com/example.js';
// A string that will be run in the context of the virtual document
// in the div with id "guest" identified above.
var javascriptString = 'document.write("hello")';
// Execute the code.
frame.code(url, 'application/javascript', javascriptString).api({}).run();
});
</script>
</body>
</html>
Upvotes: 1