Search code examples
google-chrome-devtoolsbreakpoints

Unable to set breakpoints in chrome developer tools


When I use chrome developer tools to set a breakpoint it wont set it exactly in the line that I wanted to be set. It changes it to another line. Why this happens? and what should I do if i want to set a breakpoint in the line i want?

here is the video : https://drive.google.com/file/d/0B7NuLgKMVzkgUHhaclM0YW1BSEU/view?usp=sharing


Solution

  • The debugger allows you to add breakpoints on statements. This is achieved by clicking on the line number where the statement begins. You can't add a breakpoint on an expression within.

    Example

    The following code is a mockup of the Angular code in your video:

    $stateProvider.state("key1", {
        url: "url1",
        controller: "controller1",
        templateUrl: "templateUrl1"
    }).state("key2", {
        url: "url2",
        controller: "controller2",
        templateUrl: "templateUrl2"
    });
    

    There is only one statement, beginning on line 1 and ending on line 9. You may be calling two functions that chain together, but they are one statement.

    Injecting debugger/trace statements

    You can work around this restriction by adding a debugger statement into the state function, so that it breaks for every chained function call. You can run something like into the Console/Snippet:

    var oldState = $stateProvider.state;
    
    $stateProvider.state = function() {
        debugger;
        return oldState.apply(this, arguments);
    }
    

    This saves a reference to the old function definition, and then overwrites the current with the debugger statement. If you didn't care about the real functionality, you could end it there. However, to continue normal execution, we can call the origin function using apply, which specifies the context and the arguments to be passed in. You can read a detailed explanation here.

    Now this will break for every state execution. What if you just wanted to break for a particular case? Well you could add a Conditional Breakpoint on the debugger statement as per below:

    Conditional Breakpoint

    Now the code will only break when the key is 'key2'.

    A debugger statement can be intrusive on your execution flow, so you could replace it with a console.log statement, or anything else. The conditional logic could be omitted in this case.