[html] How to view an HTML file in the browser with Visual Studio Code

How can I view my HTML code in a browser with the new Microsoft Visual Studio Code?

With Notepad++ you have the option to Run in a browser. How can I do the same thing with Visual Studio Code?

This question is related to html visual-studio-code preview

The answer is


Here is the version 2.0.0 for Mac OSx:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "echo",
      "type": "shell",
      "command": "echo Hello"
    },
    {
      "label":"chrome",
      "type":"process",
      "command":"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
      "args": [
        "${file}"
      ]
    }
  ]
}

Following worked in version 1.53.2 on windows 10 ->

  • choose run active file in terminal menu
  • It executed the html file in default edge browser

Open custom Chrome with URL from prompt

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Open Chrome",
      "type": "process",
      "windows": {
        "command": "${config:chrome.executable}"
      },
      "args": ["--user-data-dir=${config:chrome.profileDir}", "${input:url}"],
      "problemMatcher": []
    }
  ],
  "inputs": [
    {
      "id": "url",
      "description": "Which URL?",
      "default": "http://localhost:8080",
      "type": "promptString"
    }
  ]
}

Open custom Chrome with active file

{
  "label": "Open active file in Chrome",
  "type": "process",
  "command": "chrome.exe",
  "windows": {
    "command": "${config:chrome.executable}"
  },
  "args": ["--user-data-dir=${config:chrome.profileDir}", "${file}"],
  "problemMatcher": []
},

Notes

  • if necessary, replace windows property by other OS
  • replace ${config:chrome.executable} with your custom chrome location, e.g. "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
  • replace ${config:chrome.profileDir} with your custome chrome profile directory, e.g. "C:/My/Data/chrome/profile" or leave it out
  • You can keep the variables like above if you want. To do so, add following entries in settings.json - user or workspace - , adjust paths to your needs:
"chrome.executable": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
"chrome.profileDir": "C:/My/Data/chrome/profile"
  • You could re-use these variables e.g. in launch.json for debugging purposes: "runtimeExecutable": "${config:chrome.executable}"

VSCode Task - Open by App bundle identifier (macOS only).

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Open In: Firefox DE",
      "type": "process",
      "command": "open",
      "args": ["-b", "org.mozilla.firefoxdeveloperedition", "${file}"],
      "group": "build",
      "problemMatcher": [],
      "presentation": {
        "panel": "shared",
        "focus": false,
        "clear": true,
        "reveal": "never",
      }
    }
  ]
}

In linux, you can use the xdg-open command to open the file with the default browser:

{
    "version": "0.1.0",
    "linux": {
        "command": "xdg-open"
    },
    "isShellCommand": true,
    "showOutput": "never",
    "args": ["${file}"]
}

VS Code has a Live Server Extention that support one click launch from status bar.

Some of the features:

  • One Click Launch from Status Bar
  • Live Reload
  • Support for Chrome Debugging Attachment

enter image description here


You can now install an extension View In Browser. I tested it on windows with chrome and it is working.

vscode version: 1.10.2

enter image description here


If you would like to have live reload you can use gulp-webserver, which will watch for your file changes and reload page, this way you don't have to press F5 every time on your page:

Here is how to do it:

  • Open command prompt (cmd) and type

    npm install --save-dev gulp-webserver

  • Enter Ctrl+Shift+P in VS Code and type Configure Task Runner. Select it and press enter. It will open tasks.json file for you. Remove everything from it end enter just following code

tasks.json

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "args": [
        "--no-color"
    ],
    "tasks": [
        {
            "taskName": "webserver",
            "isBuildCommand": true,
            "showOutput": "always"
        }
    ]
}
  • In the root directory of your project add gulpfile.js and enter following code:

gulpfile.js

var gulp = require('gulp'),
    webserver = require('gulp-webserver');

gulp.task('webserver', function () {
    gulp.src('app')
        .pipe(webserver({
            livereload: true,
            open: true
        }));
});
  • Now in VS Code enter Ctrl+Shift+P and type "Run Task" when you enter it you will see your task "webserver" selected and press enter.

Your webserver now will open your page in your default browser. Now any changes that you will do to your HTML or CSS pages will be automatically reloaded.

Here is an information on how to configure 'gulp-webserver' for instance port, and what page to load, ...

You can also run your task just by entering Ctrl+P and type task webserver


@InvisibleDev - to get this working on a mac trying using this:

{
    "version": "0.1.0",
    "command": "Chrome",
    "osx": {
        "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    },
    "args": [
        "${file}"
    ]
}

If you have chrome already open, it will launch your html file in a new tab.


I am just re-posting the steps I used from msdn blog. It may help the community.

This will help you to setup a local web server known as lite-server with VS Code, and also guides you to host your static html files in localhost and debug your Javascript code.

1. Install Node.js

If not already installed, get it here

It comes with npm (the package manager for acquiring and managing your development libraries)

2. Create a new folder for your project

Somewhere in your drive, create a new folder for your web app.

3. Add a package.json file to the project folder

Then copy/paste the following text:

{
   "name": "Demo",
   "version": "1.0.0",
   "description": "demo project.",
   "scripts": {
     "lite": "lite-server --port 10001",
     "start": "npm run lite"
   },
   "author": "",
   "license": "ISC",
   "devDependencies": {
     "lite-server": "^2.5.4"
   }
}

4. Install the web server

In a terminal window (command prompt in Windows) opened on your project folder, run this command:

npm install

This will install lite-server (defined in package.json), a static server that loads index.html in your default browser and auto refreshes it when application files change.

5. Start the local web server!

(Assuming you have an index.html file in your project folder).

In the same terminal window (command prompt in Windows) run this command:

npm start

Wait a second and index.html is loaded and displayed in your default browser served by your local web server!

lite-server is watching your files and refreshes the page as soon as you make changes to any html, js or css files.

And if you have VS Code configured to auto save (menu File / Auto Save), you see changes in the browser as you type!

Notes:

  • Do not close the command line prompt until you’re done coding in your app for the day
  • It opens on http://localhost:10001 but you can change the port by editing the package.json file.

That’s it. Now before any coding session just type npm start and you are good to go!

Originally posted here in msdn blog. Credits goes to Author : @Laurent Duveau


  1. Open Extensions Sidebar (Ctrl + Shift + X)

  2. Search for open in browser and install it

    Ext > Open in Browser

  3. Right click on your html file, and select "Open in Browser" (Alt + B)

    Context Menu> Open in Browser


Here is a 2.0.0 version for the current document in Chrome w/ keyboard shortcut:

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Chrome",
            "type": "process",
            "command": "chrome.exe",
            "windows": {
                "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            },
            "args": [
                "${file}"
            ],
            "problemMatcher": []
        }
    ]
}

keybindings.json :

{
    "key": "ctrl+g",
    "command": "workbench.action.tasks.runTask",
    "args": "Chrome"
}

For running on a webserver:

https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer


For Mac, set your tasks.json (in the .vscode folder) file contents to the following and use SHFT+COMMAND+B to open.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Chrome Preview",
            "type": "shell",
            "command": "open -a /Applications/Google\\ Chrome.app test.html",
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

probably most will be able to find a solution from the above answers but seeing as how none worked for me (vscode v1.34) i thought i'd share my experience. if at least one person finds it helpful then, cool not a wasted post, amiirte?


anyway, my solution (windows) is built a-top of @noontz's. his configuration may have been sufficient for older versions of vscode but not with 1.34 (at least, i couldn't get it working ..).

our configs are nearly identical save a single property -- that property being, the group property. i'm not sure why but without this, my task would not even appear in the command palette.

so. a working tasks.json for windows users running vscode 1.34:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Chrome",
            "type": "process",
            "command": "chrome.exe",
            "windows": {
                "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            },
            "args": [
                "${file}"
            ],
            "group": "build",
            "problemMatcher": []
        }
    ]
}

note that the problemMatcher property is not required for this to work but without it an extra manual step is imposed on you. tried to read the docs on this property but i'm too thick to understand. hopefully someone will come about and school me but yeah, thanks in advance for that. all i know is -- include this property and ctrl+shift+b opens the current html file in a new chrome tab, hassle free.


easy.


Updated Answer in 18 April, 2020

enter image description here

Click on this Left-Bottom Manage Icon. Click Extensions or Short Cut Ctrl+Shift+X

Then Search in Extension with this key sentence Open In Default Browser. You will find this Extension. It is better to me.

Now right click on the html file and you will see Open in Default Browser or Short Cut Ctrl+1 to see the html file in browser.


If you're just on Mac this tasks.json file:

{
    "version": "0.1.0",
    "command": "open",
    "args": ["${file}"],
}

...is all you need to open the current file in Safari, assuming its extension is ".html".

Create tasks.json as described above and invoke it with ?+shift+b.

If you want it to open in Chrome then:

{
    "version": "0.1.0",
    "command": "open",
    "args": ["-a", "Chrome.app", "${file}"],
}

This will do what you want, as in opening in a new tab if the app is already open.


Openning files in Opera browser (on Windows 64 bits). Just add this lines:

{
"version": "0.1.0",
"command": "opera",
"windows": {
    "command": "///Program Files (x86)/Opera/launcher.exe"
},
"args": ["${file}"] }

Pay attention to the path format on "command": line. Don't use the "C:\path_to_exe\runme.exe" format.

To run this task, open the html file you want to view, press F1, type task opera and press enter


CTRL+SHIFT+P will bring up the command palette.
Depending on what you're running of course. Example in an ASP.net app you can type in:
>kestrel and then open up your web browser and type in localhost:(your port here).

If you type in > it will show you the show and run commands

Or in your case with HTML, I think F5 after opening the command palette should open the debugger.

Source: link


here is how you can run it in multiple browsers for windows

{
 "version": "0.1.0",
 "command": "cmd",
 "args": ["/C"],
 "isShellCommand": true,
 "showOutput": "always",
 "suppressTaskName": true,
 "tasks": [
     {   
         "taskName": "Chrome",
         "args": ["start chrome -incognito \"${file}\""]
     },
     {   
         "taskName": "Firefox",
         "args": ["start firefox -private-window \"${file}\""]
     },
     {   
         "taskName": "Edge",
         "args": ["${file}"]
     }   
    ]
}

notice that I didn't type anything in args for edge because Edge is my default browser just gave it the name of the file.

EDIT: also you don't need -incognito nor -private-window...it's just me I like to view it in a private window


my runner script looks like :

{
    "version": "0.1.0",

    "command": "explorer",

    "windows": {
        "command": "explorer.exe"
    },

    "args": ["{$file}"]
}

and it's just open my explorer when I press ctrl shift b in my index.html file


Ctrl + F1 will open the default browser. alternatively you can hit Ctrl + shift + P to open command window and select "View in Browser". The html code must be saved in a file (unsaved code on the editor - without extension, doesn't work)


For Mac - Opens in Chrome - Tested on VS Code v 1.9.0

  1. Use Command + shift + p to open the Command Palette.

enter image description here

  1. Type in Configure Task Runner, the first time you do this, VS Code will give you the scroll down menu, if it does select "Other." If you have done this before, VS Code will just send you directly to tasks.json.

  2. Once in the tasks.json file. Delete the script displayed and replace it by the following:

{
    "version": "0.1.0",
    "command": "Chrome",
    "osx": {
        "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    },
    "args": ["${file}"]
}
  1. Switch back to your html file and press Command + Shift + b to view your page in Chrome.

Recently came across this feature in one of the visual studio code tutorial in www.lynda.com

Press Ctrl + K followed by M, it will open the "Select Language Mode" ( or click on the right hand bottom corner that says HTML before that smiley ), type markdown and press enter

Now Press Ctrl + K followed by V, it will open your html in a near by tab.

Tadaaa !!!

Now emmet commands were not working in this mode in my html file, so I went back to the original state ( note - html tag tellisense were working perfectly )

To go to original state - Press Ctrl + K followed by M, select auto-detect. emmet commands started to work. If you are happy with html only viewer, then there is no need for you to come back to the original state.

Wonder why vscode is not having html viewer option by default, when it is able to dispaly the html file in the markdown mode.

Anyway it is cool. Happy vscoding :)


One click solution simply install open-in-browser Extensions from the Visual Studio marketplace.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to visual-studio-code

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error Cannot edit in read-only editor VS Code How to setup virtual environment for Python in VS Code? Pylint "unresolved import" error in Visual Studio Code Why do I keep getting Delete 'cr' [prettier/prettier]? How to set up devices for VS Code for a Flutter emulator VSCode single to double quote automatic replace js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check How can I clear the terminal in Visual Studio Code?

Examples related to preview

Unsupported major.minor version 52.0 when rendering in Android Studio How to view an HTML file in the browser with Visual Studio Code Android Camera Preview Stretched How can I set a website image that will show as preview on Facebook?