programing

WebKit, FireBug 또는 IE8 Developer Tool과 같은 일부 디버거에서 동적 로딩 JavaScript를 디버깅 할 수 있습니까?

nasanasas 2020. 9. 9. 08:06
반응형

WebKit, FireBug 또는 IE8 Developer Tool과 같은 일부 디버거에서 동적 로딩 JavaScript를 디버깅 할 수 있습니까?


에서 내 최근 질문 , 난 이미 동적 로딩 부분보기위한 몇 가지 자바 스크립트 함수를 만들었습니다. 따라서 동적 로딩 JavaScript를 디버깅 할 수 없습니다. 로드 된 모든 JavaScript는 "eval"함수에 의해 평가되기 때문입니다.

그러나 다음 스크립트를 사용하여 현재 문서의 헤더에 스크립트를 동적으로 생성하여 새 JavaScript를 만드는 방법을 찾았습니다. 로드 된 모든 스크립트는 HTML DOM에 표시됩니다 (디버거를 사용하여 찾을 수 있음).

var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.text = "alert('Test!');";

document.getElementsByTagName('head')[0].appendChild(script);

그런데 대부분의 디버거 (IE8 개발자 도구 모음, Firebug 및 Google Chrome)는 동적 스크립트에 중단 점을 설정할 수 없습니다. 디버깅 가능한 스크립트는 페이지가로드 된 후 처음으로로드되어야하기 때문입니다.

동적 스크립트 내용이나 파일에서 디버깅 할 아이디어가 있습니까?

업데이트 1-테스트를위한 소스 코드 추가

someVariable 값을 디버그하기 위해 다음 xhtml 파일을 사용할 수 있습니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>    
    <title>Dynamic Loading Script Testing</title>
    <script type="text/javascript">
    function page_load()
    {       
        var script = document.createElement('script')
        script.setAttribute("id", "dynamicLoadingScript");
        script.setAttribute("type","text/javascript");
        script.text =   "var someVariable = 0;\n" +
                        "someVariable = window.outerWidth;\n" +
                        "alert(someVariable);";

        document.getElementsByTagName('head')[0].appendChild(script);
    }
    </script>
</head>
<body onload="page_load();">
</body>
</html>

대답에서 FireBug에서 테스트합니다. 결과는 아래 이미지와 같이 표시되어야합니다.

대체 텍스트 http://d7cgnq.bay.livefilestore.com/y1pJGV27qEARXzZhsMMhPD5z0OxAtnkQK8eKeEXMAxuHjsuWeAq1aGl7sTISRNqVv3lw8ghyxE_GorlwSJDvTql0m0ugSGXPaY-PNGugSGXPaY-PNGugSGXPaY-

페이지로드 후 추가되는 "dynamicLoadingScript"스크립트를 참조하십시오.

대체 텍스트 http://d7cgnq.bay.livefilestore.com/y1pz_RwqjgeVqe2mAlUZha0PalpPdP0X5AiwJcQhYahERlnbPDdZpb-_d1e96Q-14raSDMJOBsdcV9jsi4B5yCUDqm41Wc3h0yk/undebugable-firebug-script.PNGbugable-firebug-script.PNGbugable

하지만 FireBug의 스크립트 탭에서는 찾을 수 없습니다.

업데이트 2-동적 로딩 스크립트에서 디버그 중단 점 생성

대체 텍스트 http://d7cgnq.bay.livefilestore.com/y1peKdIMOztXss-pc8PlJEmaGov_0ShYnLsuDdK5OLETbCG0UpkX6Te29w0YW2pNKaD_0ANAiizh2GdGPAAp_1q0JWAETo4Qoiw/Debugger-VS2010.png

대체 텍스트 http://d7cgnq.bay.livefilestore.com/y1pUeHaHoTXj0WBl74fnTrXwdr_y7s7h8jNKfslSONgshzZBpUddGHNBWA9cXRabo3HAl3QazeozrCABo7pNVQc1Acl-UXXbHFE/Debugger-GoogleChrome.png

위의 이미지는 모두 "debugger;"삽입을 보여줍니다. 스크립트의 일부 줄에있는 문은 동적 로딩 스크립트에서 중단 점을 발생시킬 수 있습니다. 그러나 두 디버거 모두 중단 점에서 코드를 표시하지 않습니다. 따라서이를 수행하는 데는 쓸모가 없습니다.

감사,


동일한 용도로 크롬을 사용할 수도 있습니다. Chrome에는 파서 속성을 지정하고 동적 JS 조각을 파일로 표시하여 찾아보고 중단 점을 설정할 수있는 기능이 있습니다.

설정해야하는 속성은 다음과 같습니다.

//# sourceURL=dynamicScript.js

여기서 dynamicScript.js는 스크립트 파일 브라우저에 표시되어야하는 파일의 이름입니다.

여기에 더 많은 정보

Paul Irish는 Tooling & The Webapp Development Stack 에 대한 훌륭한 강연에서도 이에 대해 간략하게 설명합니다.


"디버거"를 추가해보십시오. 동적으로 추가하는 자바 스크립트의 문. 이로 인해 중단 점 설정에 관계없이 해당 줄에서 중지됩니다.


예, Google 크롬을 사용하여 동적으로로드 된 JavaScript를 디버깅 할 수 있습니다.

debugger;동적으로로드 된 JS 파일에 대해 추가 또는 기타 속성 을 추가 할 필요가 없습니다 . 디버그하려면 아래 단계를 따르십시오.

방법 1 :

제 기술 책임자는 동적으로로드 된 Javascript 메서드를 디버그하는 매우 쉬운 방법을 보여주었습니다.

  1. 크롬 콘솔을 열고 메소드 이름을 쓰고 Enter 키를 누르십시오.
    제 경우 GetAdvancedSearchConditonRowNew
    에는 JS 메서드가로드 된 경우 메서드의 정의가 표시됩니다.

여기에 이미지 설명 입력


  1. 메서드의 정의를 클릭하면 디버깅을 위해 전체 JS 파일이 열립니다. :)

여기에 이미지 설명 입력


방법 2 :

예를 들어 ajax호출 을 사용하여 버튼을 클릭하면 JS 파일을로드합니다 .

  1. networkGoogle 크롬 개발 도구에서 탭 열기
  2. 일부 자바 스크립트 파일을로드하고 일부 자바 스크립트 함수를 호출하는 컨트롤 (예 : 버튼)을 클릭합니다.
  3. 네트워크 탭을 관찰하고 JS 기능을 찾으십시오 (내 경우에는 RetrieveAllTags?_=1451974716935)
  4. 그 위로 마우스를 가져 initiater가면 동적으로로드 된 JS 파일 (접두사 포함 VM*)을 찾을 수 있습니다 .

크롬 -1에서 동적 로딩 JavaScript 디버그


  1. 해당 VM*파일을 클릭 하여 엽니 다.
  2. 해당 파일에서 원하는 곳에 디버거를 넣으십시오.

크롬 -1에서 동적 로딩 JavaScript 디버그



그 목적으로 Google 크롬을 사용하고 있습니다.

스크립트 탭의 크롬에서 '모든 예외에서 일시 중지'를 활성화 할 수 있습니다.

여기에 이미지 설명 입력

그런 다음 코드 라인 어딘가에 넣으십시오 try{throw ''} catch(e){}. Chrome은이 줄에 도달하면 실행을 중지합니다.

편집 : 수정 된 이미지이므로 내가 말하는 것이 더 명확해질 것입니다.


평가 코드에 다음과 같은 "이름"을 지정해야 할 수도 있습니다.

http://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/

그렇다면 debugger"업데이트 2" 접근 방식이 작동 할 것 같습니다.


UPDATE : 지원되지 않는 브라우저 (읽기 : IE)에서 오류 를 방지하기 위해 sourceUrl 구문이 변경되었습니다 (@이 #로 대체 됨 ). 세부


제공 한 코드와 다음과 같은 디버거 문으로 Chrome (12.0.742.112) 사용

    script.text =   "debugger;var someVariable = 0;\n" +
    "someVariable = window.outerWidth;\n" +
    "alert(someVariable);";

chrome_debugger

나를 위해 작동합니다.

실행하기 전에 일부 JavaScript (모든 jQuery 선택기의 범위를 현재 부분> 뷰 div로 제한)를 수정해야합니다.

html 본문에 스크립트 요소를 만드는 대신 선택기 변경 사항을 부분보기의 이벤트에 바인딩하면 더 분명해질 수 있습니다 (옳지 않은 느낌).

이런 식으로 할 수 있습니다.

   (function(j)(
      var limiting_selector = '';
      j(".partial_views").bind('focusin over',function(e){
         limiting_selector = j(this).attr('someattr') // or j(this).data('limiting-selector')
      }).bind('focusout out',function(e){
         limiting_selector = '';
      });
      // And then go on with
      // j(limiting_selector+' .someclass')
   ))(jQuery)

이 코드는 HTML이 엉망이되지 않는 특정 요소에 마우스가있는 동안 수행되는 모든 jQuery 선택 작업에 ​​항상 제한 선택기를 추가합니다.

(여전히 해커처럼 보이지만 누군가가 더 나은 해결책을 가지고있을 수 있습니다)

건배


In Firebug, you should be able to see that script after the page is loaded and the script is injected. When you do, you can set a breakpoint in the appropriate place, and it'll be preserved when you refresh the page.


Dynamicly loaded Javascript still has to be parsed by the browser this is where WebKit, or FireBug debugger is sat so it's subject to the debugger no matter what, i think this is the same for the developer tools in IE8,

So your code is subject is to the debugger so where your getting a problem will not be in that file or text if it does not error

The other thing is script.text = "alert('Test!');"; is not valid so it wont work in all browsers what you want is script.innerHTML = "alert('Test!');";

even though its innerHTML it means code inside the HTML Tags not the HTML inside just the most use people use it for this so it gets explained wrong

EDITED FOR UPDATE TWO

And on Second update using Chrome i did this

go to about:blank Open the console up and past in

var script = document.createElement('script')
script.setAttribute("type","text/javascript")
script.innerHTML = "alert('Test!');debugger;";

document.getElementsByTagName('head')[0].appendChild(script);

then it will break and open the script tab with about:blank shown (nothing to see)

Then on the right hand side show the call stack list, then click on the second (anonymous function) and it will show you.

So on your file you will have a (anonymous function) that is the code your running and you will see the break point in there. so you know your in the right one.


Using Google Chrome (or Safari) Developers Tool, you can run JavaScript line by line.

Developer Tool > Scripts > Choose which script you want to debug > pause sign on the right side Or set breakpoints by click the line number


One option I like to use it adding a console.log('') statement in my code. Once this statement appears in the console a line number is associated with it. You can click that number to go to the location in the source and set a breakpoint. The drawback to this approach is that breakpoints are not preserved across page reloads and you have to run through the code before you can add a debugger.


For current Google Chrome browser or other modern browsers, you can easily search for any evaluated code with developer tool like the following images.

  1. Simulate some dynamic loading file.

여기에 이미지 설명 입력

  1. Press Ctrl+Shift+F in source tab and search for the above function.

여기에 이미지 설명 입력

Create some breakpoint and execute function to test it.

여기에 이미지 설명 입력

참고 URL : https://stackoverflow.com/questions/1705952/is-possible-to-debug-dynamic-loading-javascript-by-some-debugger-like-webkit-fi

반응형