-
-
Save jonurry/e51cf6b923e9b708e332a5aa6ff15ced to your computer and use it in GitHub Desktop.
<textarea id="code">return "hi";</textarea> | |
<button id="button">Run</button> | |
<pre id="output"></pre> | |
<script> | |
let button = document.getElementById('button'); | |
let code = document.getElementById('code'); | |
let output = document.getElementById('output'); | |
button.addEventListener('click', () => { | |
let result; | |
try { | |
let fn = new Function(code.value); | |
result = fn.call().toString(); | |
} | |
catch(e) { | |
result = e.message; | |
} | |
finally { | |
output.textContent = result; | |
} | |
}); | |
</script> |
Hints
Use document.querySelector
or document.getElementById
to get access to the elements defined in your HTML. An event handler for "click"
or "mousedown"
events on the button can get the value
property of the text field and call Function
on it.
Make sure you wrap both the call to Function
and the call to its result in a try
block so that you can catch exceptions that it produces. In this case, we really don’t know what type of exception we are looking for, so catch everything.
The textContent
property of the output element can be used to fill it with a string message. Or, if you want to keep the old content around, create a new text node using document.createTextNode
and append it to the element. Remember to add a newline character to the end so that not all output appears on a single line.
18.2 A JavaScript Workbench
Build an interface that allows people to type and run pieces of JavaScript code.
Put a button next to a
<textarea>
field, which, when pressed, uses theFunction
constructor we saw in Chapter 10 to wrap the text in a function and call it. Convert the return value of the function, or any error it raises, to a string and display it below the text field.