Удобная JavaScript консоль

Хотели бы вы иметь возможность работать с JavaScript консолью в любом веб броузере? Прекрасное решение, реализующее эту возможность, создал Антон Теряев. Его консоль представляет собой динамически генерируемое перетаскиваемое окно, в которое можно вводить и выполнять программы JavaScript.

JavaScript консоль

Чтобы выполнить что-либо в этой консоли, нужно ввести в главную панель свою программу и нажать кнопку "run script". Скрипт для создания такой консоли достаточно прост:

//mouse down on dragged DIV element
function startdrag(t, e) {
	if (e.preventDefault) e.preventDefault(); //line for IE compatibility
	e.cancelBubble = true;
	window.document.onmousemoveOld = window.document.onmousemove;
	window.document.onmouseupOld = window.document.onmouseup;
	window.document.onmousemove=dodrag;
	window.document.onmouseup=stopdrag;
	window.document.draged = t;
	t.dragX = e.clientX;
	t.dragY = e.clientY;
	return false;
}
//move the DIV
function dodrag(e) {

	if (!e) e = event; //line for IE compatibility
	t = window.document.draged;
	t.style.left = (t.offsetLeft + e.clientX - t.dragX)+"px";
	t.style.top = (t.offsetTop + e.clientY - t.dragY)+"px";

	t.dragX = e.clientX;
	t.dragY = e.clientY;
	return false;
}
//restore event-handlers
function stopdrag() {
   window.document.onmousemove=window.document.onmousemoveOld;
   window.document.onmouseup=window.document.onmouseupOld;
}
function WRITE(s) {
	document.getElementById('ScriptOutArea').innerHTML+= s.toString().replace("\n", "<BR>");
}
function runScipt() {
	new Function("{\n"+document.getElementById('ScriptArea').value+"\n}")();
	document.getElementById('ScriptOutArea').scrollTop = document.getElementById('ScriptOutArea').scrollHeight;
}
function clearOut() {
	document.getElementById('ScriptOutArea').innerHTML = "";
}
function onerrorscript(err) {
	document.getElementById('ScriptOutArea').innerHTML += "<FONT color=red>"+err.replace("\n", "<BR>")+"</FONT><BR>";
	document.getElementById('ScriptOutArea').scrollTop = document.getElementById('ScriptOutArea').scrollHeight;
}

function initJavaScriptConsole() {
	if (document.getElementById('javascriptconsolediv') != null) {
		document.body.removeChild(document.getElementById('javascriptconsolediv'));
		return;
	}
	s = "";
	s+="<TABLE cellpadding=1 cellspacing=0 width=400>";
	s+="<TR><TD><DIV style='background:#bbccdd;color:black;border:1px solid black;font:11px courier new' onmousedown=startdrag(getElementById('javascriptconsolediv'),event)>javascript console, Anton Teryaev, 2008</DIV></TD></TR>";
	s+="<TR><TD><DIV style='border:1px solid black;padding:0px'><TEXTAREA style='padding:0px;width:100%;height:200px;border:0px solid black' id=ScriptArea>";
	s+="i = document.getElementsByTagName('BR');\n";
	s+="WRITE('There are '+i.length+' BR elements here\\n');";
	s+="</TEXTAREA></DIV></TD></TR>";
	s+="<TR><TD><INPUT TYPE=BUTTON VALUE='run script' onclick=runScipt() style='width:100px;background:#eeeeee;color:black;border:1px solid black;font:11px courier new'> <INPUT TYPE=BUTTON VALUE='clear output' onclick=clearOut() style='width:100px;background:#eeeeee;color:black;border:1px solid black;font:11px courier new'></TD></TR>";
	s+="<TR><TD><DIV style='background:#eeeeee;overflow:auto;height:100px;color:gray;border:1px solid black;font:11px courier new' id='ScriptOutArea'>";
	s+="<i>Output area, use WRITE(string) function.</i><BR>";
	s+="</DIV></TD></TR>";
	s+="</TABLE>";

	var sd = document.createElement("DIV");
	sd.style.position="absolute";
	sd.style.background="white";
	sd.style.border="1px solid black";
	sd.style.font="11px courier new";
	sd.style.top = (document.documentElement.scrollTop+document.documentElement.clientHeight/2-180)+"px";
	sd.style.left = (document.documentElement.scrollLeft+document.documentElement.clientWidth/2-200)+"px";
	sd.id = "javascriptconsolediv";
	sd.innerHTML=s;

	document.body.appendChild(sd);

	window.onerror = onerrorscript;
	window.onscroll = onwinscroll;
}
function onwinscroll() {
	md = document.getElementById('javascriptconsolediv');
	if (md.offsetTop > document.documentElement.scrollTop+document.documentElement.clientHeight-350) md.style.top = (document.documentElement.scrollTop+document.documentElement.clientHeight-350) + "px";
	if (md.offsetTop < document.documentElement.scrollTop) md.style.top = document.documentElement.scrollTop + "px";
	if (md.offsetLeft < document.documentElement.scrollLeft) md.style.left = document.documentElement.scrollLeft + "px";
}

Ну и неменее прост этот скрипт в использовании. Для того чтобы включить или выключить консоль, нужно вызвать одну единственную функцию:

initJavaScriptConsole();

Увидеть скрипт в действии можно на блоге автора.

Maklay.com - Большой каталог товаров для спорта и активного отдыха
  • http://blog.arty.name/2008/tam-gde-net-firebug/ там, где нет firebug — software simian’s typewritings

    [...] русскоязычном блоге о яваскрипте JSToolbox появилась заметка об очередной альтернативной консоли, которая мне кажется слишком примитивной. [...]

  • http://blogs.sun.com/ahot/ Ahot

    Забавно видеть это ревью здесь. Оперативно сработано.
    Консоль примитивная. Зато понятно как работает :) .

  • admin

    @Ahot
    Ссылка на консоль оперативно появилась в Dzone.com :)
    Может и примитивная, но мне консоль понравилась, простая и удобная.

  • http://stroj-potrebitel.ru/ Алекс

    Я пишу javaScript в visusl Studio, однако там слабая поддержка Intellisense. не водскажите какую другую хорошую ИДЕ можно выбрать?

  • admin

    @Алекс
    Aptana, NetBeans.

  • WU

    Косяк в вашем скрипте. Попробуйте в IE перетащить за пределы экрана и отпустить там кнопку.

  • admin

    Ну это не мой скрипт вовсе ))

JSToolbox создан на основе WordPress