我创建了一个书签,它在页面中附加了一种 REPL,专为主要的五种浏览器(Chrome 1+、IE 6+、Firefox 1+、Safari 3+、Opera 9+不记得确切的版本)而设计.
评估代码的核心组件发布在下面,稍作修改+注释。
/**
* Evaluates some code in the global scope.
* @param String code: Code to eval
* @return Stringified result, prefixed with 'E:' if error.
*/
function globalEval(/*string*/ code) {
var win = window, r, raw;
try {
if (win.execScript) { // eval in IE sucks, so use execScript instead
r = win.$_$_$globalEval$_$_$ = {c:code};
win.execScript('try{$_$_$globalEval$_$_$.r=eval($_$_$globalEval$_$_$.c);}catch(e){$_$_$globalEval$_$_$.e=e}');
// /*Optional clean-up:*/ delete win.$_$_$globalEval$_$_$;
if (r.e) throw r.e; // Error
raw = r.r;
} else {
raw = win.eval(code);
}
r = '' + raw; // Stringify in the try-block
// It is possible that an error is thrown
// for example, for the following code: ({toString:1})
} catch(err) {
r = (err + ''); // Convert error to string
// IE: If found, "[object" will be at index zero, which is falsy
if (!r.indexOf('[object')) r = err.message;
// r =
r = 'E:' + (raw=r);
} finally {
// raw = unmodified result (or Error instance)
// FOR THIS EXAMPLE, raw is not used, and string r is returned
return /*string*/ r;
}
}
我已经在一个表单中实现了该功能,其中包含几个控件,包括一个输入+输出文本区域。
Note: The code is evaluated in the global context. And such, any variables in code
will be leaked to the global scope. For an interpreter, you could use an iframe to create a new scope (and modify var win
in my function).
var win = frames['name_of_frame'], ... // or
var win = frame_DOM_element.contentWindow, ...