visual-studio-code

Cannot debug in VS Code by attaching to Chrome


I have default config in launch.json. The site runs on port 8080.

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080",
            "webRoot": "${workspaceRoot}"
        },
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 9222,
            "webRoot": "${workspaceRoot}"
        }
    ]
}

enter image description here

However, when I click on the Debug button, I get this error:

Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9222

enter image description here

Question 1: Why does VS Code assign port 9222 when creating this json?

What is so special about this port that MS decided to put it in this launch.json?

Question 2: What do I need to change to make things work?

The Launch debug always launches a new window. I am asking specifically about Attach debug option, so that it will open in a new tab instead.


Solution

    1. You need to install Debugger for Chrome extension for this to work. Open extensions in VS Code and search for Debugger for Chrome

    2. You need to run a web server on the URL specified in the first configuration (default to http://localhost:8080). I use serve npm package that I installed globally. From my app folder I run serve -p 8080

    3. Select Launch Chrome against localhost option. It will launch the browser and you can set breakpoints in your code and the debugging should work.

    Regarding the second configuration (Attach to Chrome). There's nothing special about the port. In order to attach to Chrome you need to run Chrome with remote debugging enabled on port specified in the config. For example chrome.exe --remote-debugging-port=9222. I personally never use this options. Just follow the three steps above and you should be fine.