Console Form is a tiny Javascript library for embedding a command console into a webpage — think chat clients, text adventures or even interpreters. Its distinguishing features are:
You can navigate command line history with the up and down keys.
Save console-form.js (4.5K), that's all.
As of February 2019, Console Form is open source under the MIT license. See the source code for details.
As of March 2023, there's a new version with some changes and improvements.
Console Form needs an HTML element to serve as a container (note the explicit height to keep it from collapsing into nothing):
<div id="console" style="Height: 25em;"></div>
Once you have that, add the following code in a script tag somewhere:
window.addEventListener("load", function () {
var conform = new ConsoleForm(
document.getElementById("console"));
}, false);
If everything went well (you did include console-form.js
, right?) you should now have a working console. But it can only echo your lines. Let's override the default handler with something more interesting:
conform.oncommand = function (code) {
try {
this.log("js> " + code);
this.log(eval(code));
} catch (e) {
this.error(e.toString());
}
};
The console object has log()
, warn()
and error()
methods, just like the browser console. But you won't see any difference by default. Add a couple lines to your page styles:
#console .warning { Color: orange; Font-weight: bold; }
#console .error { Color: red; Font-weight: bold; }
Normally, Console Form doesn't care what you type on the command line. But you can ask it to call different handlers based on a prefix:
conform.commands["*"] = function (args) {
this.clear();
};
Now entering a line that starts with an asterisk — ignoring any whitespace — will clear the console output. (The rest of the line, if any, is passed to the handler, so each command can parse its own arguments.) If the line doesn't start with a recognized prefix, it gets passed to the general-purpose command handler as before.
That's it for main features. In the way of customization, you might want to change the logsize
and histsize
properties of the console object from the default of 100. The input
property holds a reference to the text field proper, which you can use to give it placeholder text and set up autocompletion via a datalist element.
Styling the console is up to you; the library only sets those properties it needs to put every element in its place. The Run button is an actual button
element; you can put anything in its innerHTML
, like an icon.
And that's about it. Enjoy!
(Similar project: Josh.js Toolkit for building a bash-like shell in the browser, including full readline support
.)