简体   繁体   中英

How can I run the code the user enters into the Ace Editor

I'm using Ace Editor in a project, and I was wondering on how to run the code the user inputs into the editor. I was thinking I could use something like this:

var editor = ace.edit("editor");
editor.setTheme("ace/theme/chaos");
editor.session.setMode("ace/mode/javascript");

function runProgram() {
    var code = editor.getValue();
    var display = document.getElementById("display");
    try {
       var result = eval(code);
       display.innerHTML = result;
    } catch(e) {
        alert('Error' + e);
    }
}

But I'm not sure about using eval() due to security. I was hoping to find some way to safely execute and display the users code. Please note that I'm a beginner in javascript.

If you are running the code written by user on the same users computer security is not a concern, since user could run the same code in the browser console.

But if you want to prevent the user from accidentally breaking the editor, you can use an iframe with sandbox attribute and appropriate CORS policies. If you load the iframe from a different domain, it will be running in a different process in chrome, and infinite loops will not block the editor.

A toy implementation of this would be

iframe = document.body.appendChild(document.createElement("iframe"))
iframe.sandbox="allow-modals allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts"

iframe.src="data:text/html," + encodeURIComponent(`<script>
function runProgram(e) {
    console.log(e)
    var code = e.data;
    var display = document.body;
    try {
       var result = eval(code);
       display.innerHTML = result;
    } catch(e) {
        alert('Error' + e);
    }
}

window.onmessage = runProgram</script>
waiting...`)

And then when user presses run button use postMessage.

iframe.contentWindow.postMessage(editor.getValue(), "*")

A real implementation would be much more complex see for example https://github.com/jsbin/jsbin for a popular open source project doing this kind of thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM