Sidenote - a simple Javascript console
For our project My Journey to Postscript I needed a simple way to display and execute Javascript code. The wiki function javascript displays an editor and executes it.
The function has two parameters. The first are the options which can be
- -sandbox: show the editor
- -code: show the code but hide the run button
- -console: show the console output
- -wait: do not immediately run the code
Without any option, the code is just executed, but not visible. If you want to make it visible, use -code, if you want to make it interactive, use -sandbox.
The second is the code itself.
The wiki function creates Javascript code to handle the editor. Each editor gets a unique ID so you can have multiple editors on a page. The console.log(), window.error() and console.error() functions are redirected to the console of the editor. To run the code, the script creates a new script node with the content of the editor and appends it to the body.
That’s it. Global variables of the editors share the same space, so one editor can use the functions defined by another one. Global space also comes with limits: you will get errors if you run constants and standard function definitions multiple times. So on the global level, we will always define functions as variables and do not use constants
Example of communication
Opening the page, result is 2. If you run first and third again, result will be 1.
We can build our own Postscript editor with Javascript. For our development of PostScript interpreter, it would be more convenient to write the program directly than to insert it into Javascript code. The following functions redirectConsole and postScriptEditor add an editor that understands PostScript directly.
We write first a dummy function as interpreter.
The function redirectConsole(id) redirects the console message to HTML node with an id "console"+id. This allows us also to report errors directly on the HTML page and not hidden in the inspector panel of the browser.
The function postScriptEditor(code) provides an interface for a code editor. When you push the button, the edited code will be sent as arguments to rpn and the result will be shown in the console.
First I wrote the interface in HTML, but that needed much escaping of tags in wikitext. Using the DOM-model, it is cleaner. The script part uses the backtick-quote that allows multiline strings, and then replaces id, fn and code in the string. That makes the code more readable.
Finally, the line postScriptEditor("3 4 add");
creates the editor window below.
Now we use it. Click run.
The current code is now 158 lines ps20240625.js
If you want to try it for you locally, this minimal HTML page uses the postScriptEditor function to build 2 editors.
https://belle-nuit.com/site/files/minimal.html
The script ps20240625.js is expected to be in the same folder. Download both files to the same folder and run then the HTML in your browser.