program tip

JavaScript 코드를 어떻게 디버깅 할 수 있습니까?

radiobox 2020. 7. 26. 12:51
반응형

JavaScript 코드를 어떻게 디버깅 할 수 있습니까? [닫은]


문제가있는 코드 스 니펫을 발견하면이를 디버깅하는 방법은 무엇입니까?


Firebug 는이 목적에 가장 많이 사용되는 도구 중 하나입니다.


모든 최신 브라우저에는 특정 형태의 내장 JavaScript 디버깅 응용 프로그램이 제공됩니다. 이에 대한 자세한 내용은 관련 기술 웹 페이지에서 다룰 것입니다. JavaScript 디버깅에 대한 개인적 선호 는 Firefox의 Firebug 입니다. 나는 Firebug가 다른 어떤 것보다 낫다고 말하지는 않는다. 그것은 개인 취향에 달려 있으며 어쨌든 모든 브라우저에서 사이트를 테스트해야하지만, 개인적으로 가장 먼저 선택하는 것은 항상 Firebug입니다.

Firebug를 예로 들어 아래의 고급 솔루션 중 일부를 다루겠습니다 .

Firefox

Firefox에는 자체 내장 JavaScript 디버깅 도구가 포함되어 있지만 Firebug 애드온을 설치하는 것이 좋습니다 . 기본 버전에 따라 몇 가지 추가 기능이 제공됩니다. 여기서는 Firebug에 대해서만 이야기하겠습니다.

Firebug가 설치되면 아래와 같이 액세스 할 수 있습니다.

먼저 요소를 마우스 오른쪽 버튼으로 클릭하면 Firebug로 요소를 검사 할 수 있습니다 .

Firebug에서 요소 검사

이것을 클릭하면 브라우저 하단에 Firebug 창이 열립니다 :

방화 창

Firebug는 몇 가지 기능을 제공하지만 관심이있는 기능은 스크립트 탭입니다. 스크립트 탭을 클릭하면 아래 창이 열립니다.

스크립트 탭

분명히 디버깅하려면 다시로드 를 클릭해야합니다 .

sctipt 탭의 JavaScript

중단 점 을 추가하려는 JavaScript 코드 왼쪽의 행을 클릭하여 중단 점추가 할 수 있습니다 .

중단 점 추가

중단 점에 도달하면 다음과 같이 표시됩니다.

중단 점이 발생했습니다

감시 변수를 추가 하고 일반적으로 최신 디버깅 도구에서 기대할 수있는 모든 작업을 수행 할 수도 있습니다 .

품종보기

Firebug에서 제공하는 다양한 옵션에 대한 자세한 내용은 Firebug FAQ를 참조하십시오 .

크롬

Chrome에는 자체 내장 된 자바 스크립트 디버깅 옵션도 있습니다.이 옵션은 마우스 오른쪽 버튼 클릭, 요소 검사 등 매우 유사한 방식으로 작동합니다 . Chrome 개발자 도구를 살펴보십시오 . 일반적으로 Firebug보다 Chrome 스택 추적 이 더 좋습니다.

인터넷 익스플로러

If your developing in .NET and using Visual Studio using the web development environment you can debug JavaScript code directly by placing breakpoints, etc. Your JavaScript code looks exactly the same as if you were debugging your C# or VB.NET code.

If you don't have this, Internet Explorer also provides all of the tools shown above. Annoyingly, instead of having the right click inspect element features of Chrome or Firefox, you access the developer tools by pressing F12. This question covers most of the points.


  • Internet Explorer 8 (Developer Tools - F12). Anything else is second rate in Internet Explorer land
  • Firefox and Firebug. Hit F12 to display.
  • Safari (Show Menu Bar, Preferences -> Advanced -> Show Develop menu bar)
  • Google Chrome JavaScript Console (F12 or (Ctrl + Shift + J)). Mostly the same browser as Safari, but Safari is better IMHO.
  • Opera (Tools -> Advanced -> Developer Tools)

There is a debugger keyword in JavaScript to debug the JavaScript code. Put debugger; snippet in your JavaScript code. It will automatically start debugging the JavaScript code at that point.

For example:

Suppose this is your test.js file

function func(){
    //Some stuff
    debugger;  //Debugging is automatically started from here
    //Some stuff
}
func();
  • When the browser runs the web page in developer option with enabled debugger, then it automatically starts debugging from the debugger; point.
  • There should be opened the developer window the browser.

I use old good printf approach (an ancient technique which will work well in any time).

Look to magic %o:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

%o dump clickable and deep-browsable, pretty-printed content of JS object. %s was shown just for a record.

And this:

console.log("%s", new Error().stack);

gives you Java-like stack trace to point of new Error() invocation (including path to file and line number!!).

Both %o and new Error().stack available in Chrome and Firefox.

With such powerful tools you make assumption whats going wrong in your JS, put debug output (don't forget wrap in if statement to reduce amount of data) and verify your assumption. Fix issue or make new assumption or put more debug output to bit problem.

Also for stack traces use:

console.trace();

as say Console

Happy hacking!


Start with Firebug and IE Debugger.

Be careful with debuggers in JavaScript though. Every once in a while they will affect the environment just enough to cause some of the errors you are trying to debug.

Examples:

For Internet Explorer, it's generally a gradual slowdown and is some kind of memory leak type deal. After a half hour or so I need to restart. It seems to be fairly regular.

For Firebug, it's probably been more than a year so it may have been an older version. As a result, I don't remember the specifics, but basically the code was not running correctly and after trying to debug it for a while I disabled Firebug and the code worked fine.


Although alert(msg); works in those "I just want to find out whats going on" scenarios... every developer has encountered that case where you end up in a (very large or endless) loop that you can't break out of.

I'd recommend that during development if you want a very in-your-face debug option, use a debug option that lets you break out. (PS Opera, Safari? and Chrome? all have this available in their native dialogs)

//global flag
_debug = true;
function debug(msg){
  if(_debug){
    if(!confirm(msg + '\n\nPress Cancel to stop debugging.')){
      _debug = false;
    }
  }
}

With the above you can get your self into a large loop of popup debugging, where pressing Enter/Ok lets you jump through each message, but pressing Escape/Cancel lets you break out nicely.


I use WebKit's developer menu/console (Safari 4). It is almost identical to Firebug.

console.log() is the new black -- far better than alert().


My first step is always to validate the HTML and to check syntax with JSLint. If you have clean markup and valid JavaScript code then it is time for Firebug or another debugger.


Visual Studio 2008 has some very good JavaScript debugging tools. You can drop a breakpoint in your client side JavaScript code and step through it using the exact same tools as you would the server side code. There is no need to attach to a process or do anything tricky to enable it.


I use a few tools: Fiddler, Firebug, and Visual Studio. I hear Internet Explorer 8 has a good built-in debugger.


I used to use Firebug, until Internet Explorer 8 came out. I'm not a huge fan of Internet Explorer, but after spending some time with the built-in developer tools, which includes a really nice debugger, it seems pointless to use anything else. I have to tip my hat to Microsoft they did a fantastic job on this tool.


You might also check out YUI Logger. All you have to do to use it is include a couple of tags in your HTML. It is a helpful addition to Firebug, which is more or less a must.


I found the new version of Internet Explorer 8 (press F12) is very good to debug JavaScript code.

Of course, Firebug is good if you use Firefox.


Besides using Visual Studio's JavaScript debugger, I wrote my own simple panel that I include to a page. It's simply like the Immediate window of Visual Studio. I can change my variables' values, call my functions, and see variables' values. It simply evaluates the code written in the text field.


I'm using Venkman, a JavaScript debugger for XUL applications.


In addition to Firebug and browser-native developer extensions JetBrains WebStorm IDE comes with remote debug support for Firefox and Chrome (Extension required) built in.

Also supports:

Options to test this for free are the 30 trial or using an Early Access Version.


If you are using Visual Studio, just put debugger; above the code you want to debug. During execution the control will pause at that place, and you can debug step by step from there on.


As with most answers, it really depends: What are you trying to achieve with your debugging? Basic development, fixing performance issues? For basic development, all the previous answers are more than adequate.

For performance testing specifically, I recommend Firebug. Being able to profile which methods are the most expensive in terms of time has been invaluable for a number of projects I have worked on. As client-side libraries become more and more robust, and more responsibility is placed client-side in general, this type of debugging and profiling will only become more useful.

Firebug Console API: http://getfirebug.com/console.html


By pressing F12 web developers can quickly debug JavaScript code without leaving the browser. It is built into every installation of Windows.

에서 인터넷 익스플로러 11 , F12 도구 등의 중단 점, 시계와 지역 변수보기, 메시지 및 즉시 코드 실행을위한 콘솔로 디버깅 도구를 제공합니다.

참고 URL : https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code

반응형