Vs code не открывается браузер

Обновлено: 30.06.2024

Hi
When i am running my html file on vs code through "open with live server option" vs code is not opening browser directly when live server gets on its says "server is started at 5500"
and then i have to go to my browser and type "localhost:5500" to get my folder and files .

The text was updated successfully, but these errors were encountered:

niharikaarora1997 commented Jan 18, 2018

I have tried many times. I even installed lite server. and same issue is there. it shows which server port gets on. and then i have to open my browser myself and type localhost:port to view my page

ritwickdey commented Jan 18, 2018

I mean by 2nd time -> Right Click on html file and click Open with Live Server and again repeat the step without stopping the server. If it's NOT works for you! I've another workaround for you.

Try this, if it not works, tell me about few things -

niharikaarora1997 commented Jan 18, 2018

tried this. not working.
Using Windows
and i want to start Chrome

ritwickdey commented Jan 18, 2018

Ok, Let me know, if you have a changed any setting, if not, try following.

Open your User Settings and setup the settings

For 64bit system.

For 32bit system.

niharikaarora1997 commented Jan 18, 2018

"git.path": null,
"workbench.iconTheme": "vscode-icons",
"liveServer.settings.CustomBrowser": "chrome",
"liveServer.settings.NoBrowser": true,
"liveServer.settings.ChromeDebuggingAttachment": true

These are my changes settings

niharikaarora1997 commented Jan 18, 2018

ritwickdey commented Jan 18, 2018

"liveServer.settings.NoBrowser": true, => means NO BROWSER.
make it false.

niharikaarora1997 commented Jan 18, 2018

Yes changed it
Still not working

MouniBoug commented Mar 2, 2018

The same issue, the browser won't open!!

gauravcap01 commented Apr 4, 2018

I am also facing same issue. Can someone help?

ghost commented Apr 8, 2018

Any progress on this issue of the browser not opening when o the source page right clicking and selecting, "Open With Live Server"?

  • Windows 10 Pro and latest VSCode.
  • All my install setting are defaults

Works on other like Windows 10 installs.

sambgordon commented Apr 9, 2018

I would also like to hear if anyone figures this out. On OSX and it does the same.

OstapHetman commented Apr 14, 2018

I have the same problem. My User settings:

My VS code version 1.22.2

Any new solutions ?

30ozSteak commented Apr 16, 2018

I have a DIFFERENT problem! It seems whenever I try to open a live server, it opens a completely . different HTML file. I've even closed all the other associated files and it still opens a completely unrelated one.

Azhorabai commented Apr 19, 2018

Same here, however i'm looking for help with firefox. I made no changes whatsoever to the settings file.
Here's my code:

C:\\Program Files\\Firefox Developer Edition\\firefox.exe --private-window "liveServer.settings.AdvanceCustomBrowserCmdLine": null,

Also note that the Go Live button is no longer there.
Right clicking the Html file brings up going live, however nothing happens.

mjyousse commented May 12, 2018

Anyone found a solution for this problem? It opens my code tree instead or the actual HTML code. Not sure what to do.

VSC Version: 1.23.1
OS: Windows 10 Pro

@mohammadsf i think there is no index.html that's why it opens your code tree when server started.

mjyousse commented May 18, 2018

@rjoydip Yea thanks for that.. I'm assuming that sometimes the HTML file doesn't have to necessarily be names"index.html", is there a work around that or not really?

If any html file opened in your vscode active window then it will open that otherwise it will open a file explore from the you can pick any html and live reload will works as well.

Cshivers1 commented Aug 18, 2018

∫ this is what I am getting when I try to use option b with mac. The html file won't open in browser. Uninstalled, disabled it and the opposite. Also deleted visual studios and reinstalled that as well still no avail.

Anyone else having this issue?

You have to open the project directory in vs code, and not the file itself

-Folder <—— open this in the terminal with code Folder
—index.html
—style.css
—index.js

Then you’ll be able to open in Live server

Cshivers1 commented Aug 18, 2018

I use to be able to just press option b and it would load directly from the html file

ODINAKACHUKWU commented Sep 4, 2018

Wow! I was having same issue of not being able to open my file in Live server. But now, I can after opening the project directory in VS Code and not the file itself.

Big thanks to you @30ozSteak

ehsanyousefi commented Sep 24, 2018

close all opened windows in VS and close the program then run as administrator.
now select the folder to open and go live.
it worked for me.

gladwinK commented Nov 9, 2020

I had a same problem and i solve it (I use Windovs 7, but it is same procedure as for Windovs 10). Just follow this steps:

Go to system variables, then go to enviroment variables, then go to system variables find Path and click edit.

After that add C:\Windows\System32.

Good luck!

How to do this on ubuntu

ArhamZaldin commented Nov 17, 2020

for anyone who still can't open browser automatically after turn on the live server, i have a solution for you. just change/delete the space on your name file. ex: your file name is "live server.html", just change it to "live_server.html" or "live-server.html" or "liveserver.html".
hope this works on you. sorry for my bad english.

BetaxxxCross commented Nov 30, 2020

You just need to set your environmental variable to the default one. Here's the better one:
C:\Windows\System32; C:\Program Files; C:\Program Files (x86);%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;
Just click on your path and edit paste this and voila you're good

aystic commented Dec 14, 2020

Hi
When i am running my html file on vs code through "open with live server option" vs code is not opening browser directly when live server gets on its says "server is started at 5500"
and then i have to go to my browser and type "localhost:5500" to get my folder and files .

Ok, Let me know, if you have a changed any setting, if not, try following.

Open your User Settings and setup the settings

For 64bit system.

For 32bit system.

razzlepazzle commented Dec 14, 2020

I selected "Go Live" from my html file under Open Editor. I'm not sure if it was just time that I needed to get the file to work and if the time had finally come for me or if that was the actual solution.

yustinayasin commented Jan 2, 2021

solution

The issue appeared after I stupidly deleted some environment variables.

Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.

See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

Thank you so much. It works!! :')

ngotaiduy commented Jan 11, 2021

solution

The issue appeared after I stupidly deleted some environment variables.

Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.

See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

thank you very much! It works :D

jyothisable commented Jan 20, 2021

solution

The issue appeared after I stupidly deleted some environment variables.

Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.

See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

finally it worked, thanks a lot.
issue was pressing the live button didn't directly redirect to chrome, but it was working fine if I manually go to localhost:5500 (auto refresh was also not working)

usmanklasan commented Feb 5, 2021

kavyachinnuu commented Feb 13, 2021

started at 5500"
and then i have to go to my browser and type "localhost:5500" to get my folder and files .

kavyachinnuu commented Feb 13, 2021

Even am facing d same issue ,plz help anyone! Thanks in advance

kavyachinnuu commented Feb 15, 2021

Hi
When i am running my html file on vs code through "open with live server option" vs code is not opening browser directly when live server gets on its says "server is started at 5500"
and then i have to go to my browser and type "localhost:5500" to get my folder and files .

Same issue am facing

kavyachinnuu commented Feb 15, 2021

Yes changed it
Still not working

Did ur issue solved ? Plz lemme knw wt changes u hav made even am facing same issue 😟 @niharikaarora1997

I have a problem with VsC, when i open my html with live server i can see my page with all my changes but when i try open with the visual estudios' path all the change that i made it's not there, i don't know what happens. Sorry if my English is not perfect.

LalitBoop commented Feb 21, 2021

I made a change as per your instruction. it does not work please help.

akhilreddy619 commented Mar 21, 2021

I have followed all of the above suggestions. But none of them are working for me. I re-installed the live server. Set the default browser to chrome. Added the above mentioned directories to the Path system variable. When I righ-click and select open with live server, it starts but the browser does not open. Please help me with this.

D-Hornsby commented Mar 22, 2021

solution

The issue appeared after I stupidly deleted some environment variables.
Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.
See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

Thank you so much my live server started working

How do i fix this with a mac?
I had to uninstall and reinstall so I could get my command palette as it was missing. To do this i really cleaned out all past vs hidden threw out my computer as the first attempts did not do the trick. I finally got enough for my other issue to be fixed but now Im pretty sure I may of not got it all back right because now my LS is not opening as it should. ..How can i restore the path on a mac?
I have already added the"liveServer.settings.NoBrowser": false as it was not in my json at all but it did have this."liveServer.settings.donotShowInfoMsg": true, not sure what that is. I have also changed my"liveServer.settings.CustomBrowser": "chrome", to point right at chrome and also made sure to change my user browser in my box to reflect the same. is someone able to help with this one?

You have to open the project directory in vs code, and not the file itself

-Folder <—— open this in the terminal with code Folder
—index.html
—style.css
—index.js

Then you’ll be able to open in Live server

This solved the problem for me! Thanks!

BhaskarSingh-DEV commented May 3, 2021

solution

The issue appeared after I stupidly deleted some environment variables.
Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.
See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

Thank you so much my live server started working

Thank you so much.

BhaskarSingh-DEV commented May 3, 2021

Thank you so much my live server started working

albiemk commented May 10, 2021

Solved issue of my windows 8 pro. just added C:\Windows\System32; to the environment path.
Thank you very much all of you

Driss-Tran commented Jun 13, 2021

solution

The issue appeared after I stupidly deleted some environment variables.
Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.
See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

thank you very much! It works :D

Yah It's really work , you save my life

Tanisha-creator commented Aug 19, 2021

solution

The issue appeared after I stupidly deleted some environment variables.
Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.
See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

You Saved My Life.

solution

The issue appeared after I stupidly deleted some environment variables.

Fixed by adding a missing variable "Path" pointing to "C:\Windows\System32" folder. This solution was mentioned previously in the thread, but without detailed info.

See screenshot of my Windows10 variable added that was missing.

On other versions of Windows path may be different.

Thanks, even I deleted this path for some reason and since then live server wasn't working. Searched this issue every where, in Google, YouTube and finally found the solution here scrolling these many solutions. 🙃

VSCode имеет множество отличных расширений, и Live Server - одно из лучших.

Всего за пару кликов Live Server позволяет увидеть вашу страницу в реальном времени в реальном браузере. Более того, он имеет функцию перезагрузки в реальном времени, поэтому, если вы обновите свой код, изменения также будут отражены в браузере.

Все, что вам нужно сделать, это щелкнуть правой кнопкой мыши HTML-файл, который вы хотите просмотреть, затем щелкнуть правой кнопкой мыши и выбрать «Открыть с помощью Live Server»:


Но что, если Live Server не открывает ваш браузер и не отображает вашу страницу так, как вы ожидаете? Если это происходит с вами, вот несколько вещей, которые вы можете попробовать.

Перезапустить VSCode

Иногда лучшее, что вы можете сделать, - это запустить VSCode с нуля.

Во-первых, сохраните всю свою работу. Затем закройте VSCode, который также остановит все установленные вами расширения.

Затем снова откройте VSCode и попробуйте еще раз - перейдите к HTML-файлу, который вы хотите просмотреть, щелкните правой кнопкой мыши и выберите «Открыть с помощью Live Server».

Установите браузер для Live Server

Возможно, расширение работает, но в вашей системе нет браузера по умолчанию.

Даже если вы установили браузер по умолчанию для своей системы, не помешало бы сообщить Live Server, какой браузер вы хотите использовать явно.

Сначала откройте Command Pallete с помощью F1, затем введите Preferences: Open Settings (JSON) и выберите эту опцию.

Это откроет ваш settings.json файл VSCode .

Прокрутите файл до конца и вставьте его "liveServer.settings.CustomBrowser": "chrome" .

Прокрутите файл до конца, добавьте запятую после последнего параметра и вставьте "liveServer.settings.CustomBrowser": "chrome" :


Обратите внимание, что вы также можете использовать "firefox" , "safari" или любой другой браузер в качестве значения "liveServer.settings.CustomBrowser" параметра.

Наконец, сохраните settings.json файл и попробуйте снова запустить Live Server.

Установите браузер по умолчанию для вашей операционной системы

Даже после того, как Live Server сообщил, какой браузер вы хотите использовать, возможно, что он по-прежнему неправильно открывает вашу страницу в этом браузере.

Следующее, что нужно попробовать, - это установить браузер по умолчанию для самой операционной системы.

Точный метод для этого может варьироваться в зависимости от вашей операционной системы, поэтому лучше поискать, как это сделать, если вы не уверены.

Вот как выглядит страница настроек в Windows:


Зайдите на живую страницу сами

Если по какой-то причине Live Server по-прежнему не открывает страницу в вашем браузере автоматически, не беспокойтесь. Вы всегда можете открыть любой браузер по вашему выбору и просмотреть страницу напрямую.

Просто откройте предпочтительный браузер и перейдите в //127.0.0.1:5500/ .

Например, если ваш файл называется index.html , просто перейдите по ссылке //127.0.0.1:5500/index.html .

Пока работает Live Server, вы должны видеть свою страницу.

В заключение

Это несколько распространенных исправлений, которые вы можете попробовать, если Live Server не работает так, как вы ожидаете.

По умолчанию это мое сафари, но я хотел бы изменить его на хром. Я посмотрел в настройках, но, похоже, нет возможности для этого. Любые идеи?

Перейти к Файлы> Настройки> Настройки

Из настроек пользователя по умолчанию выберите LiveServer Config

Внутри нажмите на значок пера слева на liveServer.settings.CustomBrowser выберите chrome .

Вы можете сделать это в 2 этапа:
1) В package.json в разделе scripts создайте значение ключа как "devserver": "live-server --browser=Chrome" .
2) В терминале запустить npm run devserver

Это откроет приложение в Chrome.

Если вы установили ваш live-сервер глобально при использовании пакета npm, вы можете легко запустить ваш live-сервер в браузере по вашему выбору, передав опцию browser в вашей команде запуска:

На вашем терминале введите: live-server --browser=BROWSER_NAME Например: live-server --browser=firefox, live-server --browser=safari

и некоторые MacBooks принимает live-server --browser='Google Chrome' для Google chrome в то время как другие live-server --browser=google-chrome NB: для Mac live-server --browser=chrome выдаст ошибку

  1. Откройте файл settings.json
  2. Введите или скопируйте и вставьте следующую строку в следующую строку: "liveServer.settings.CustomBrowser": "chrome"
  3. Убедитесь, что после кода в предыдущей строке есть запятая.

liveServer.settings.CustomBrowser:

Чтобы изменить браузер вашей системы по умолчанию. Значением по умолчанию является "Нуль" [Строка, а не ноль]. (Откроется браузер по умолчанию для вашей системы.) Доступные параметры: chrome chrome: PrivateMode firefox firefox: PrivateMode Microsoft-Edge

Как настроить свой нетрадиционный браузер в "liveServer"?

    Перейдите на Files > Preferences > Settings , Найдите .json И нажмите на файл settings.json

или нажмите SHIFT + CTRL + P и вкладку Preferences: Open Settings (JSON)

Написать в файл JSON

"liveServer.settings.AdvanceCustomBrowserCmdLine": Для установки любого вашего любимого браузера (например, Chrome Canary, Firefox Nightly), используя расширенную командную строку. (Вы можете указать полный путь к вашему любимому настраиваемому браузеру).

  • Этот параметр переопределяет настройки "CustomBrowser" И "ChromeDebuggingAttachment" .
  • Значение по умолчанию равно нулю
  • Примеры:
    • chrome --incognito - без головы --remote-debugging-port = 9222
    • C:\Program Files\Firefox Developer Edition\firefox.exe --private-window

    Проверьте мой фото или посмотрите это ссылка на GitHub для более подробной информации.

    Примечание. Либо используйте "AdvanceCustomBrowserCmdLine" , Либо "CustomBrowser" . Если вы используете оба, "AdvanceCustomBrowserCmdLine" Имеет более высокий приоритет.

    Вот как я это сделал на MacOS (нужно включить передачу, затем выбрать "Настроить параметры расширения")

    Как просмотреть мой HTML-код в браузере с помощью нового кода Microsoft Visual Studio?

    С Notepad ++ у вас есть возможность запустить в браузере. Как я могу сделать то же самое с кодом Visual Studio?

    Для Windows - откройте браузер по умолчанию - протестировано на VS Code v 1.1.0

    Ответьте на оба вопроса, чтобы открыть определенный файл (имя жестко запрограммировано) OR открыть ЛЮБОЙ другой файл.

    шаги:

    Использование ctrl + shift + p (или же F1 ), чтобы открыть командную палитру.

    Введите Tasks: Configure Task или в более старых версиях Configure Task Runner . При его выборе откроется файл tasks.json. Удалите отображаемый скрипт и замените его следующим:

    Не забудьте изменить раздел "args" файла tasks.json на имя вашего файла. Это всегда откроет этот конкретный файл, когда вы нажмете F5.

    Вы также можете установить this для открытия любого файла, который вы открыли в данный момент, используя ["$"] в качестве значения для "args". Обратите внимание, что $ выходит за пределы <. >, поэтому [""] неверен.

    Вернитесь к html-файлу (в данном примере это "text.html") и нажмите ctrl + shift + b чтобы просмотреть свою страницу в веб-браузере.

    enter image description here

    @InvisibleDev - чтобы заставить это работать на Mac, пытающемся использовать это:

    Если у вас уже открыт Chrome, он запустит ваш HTML-файл на новой вкладке.

    VS Code имеет Live Server Extention , который поддерживает запуск в один клик из строки состояния.

    Некоторые из особенностей:

    • Запуск одним кликом из строки состояния
    • Live Обновление
    • Поддержка Chrome Debugging Attachment

    Если вы хотите выполнить перезагрузку в режиме реального времени, вы можете использовать gulp-webserver, который будет следить за изменениями ваших файлов и перезагружать страницу, так что вам не нужно каждый раз нажимать клавишу F5 на вашей странице:

    Вот как это сделать:

    Откройте командную строку (cmd) и введите

    установка npm --save-dev gulp-webserver

    Введите Ctrl + Shift + P в VS Code и введите Configure Task Runner. Выберите его и нажмите Enter. Он откроет для вас файл tasks.json. Удалить все с конца и ввести только следующий код

    tasks.json

    • В корневой каталог вашего проекта добавьте gulpfile.js и введите следующий код:

    gulpfile.js

    • Теперь в VS Code введите Ctrl + Shift + P и введите «Run Task», когда вы введете его, вы увидите выбранную задачу «веб-сервер» и нажмите Enter.

    Теперь ваш веб-сервер откроет вашу страницу в браузере по умолчанию. Теперь любые изменения, которые вы внесете в свои страницы HTML или CSS, будут автоматически перезагружены.

    Вот информация о том, как настроить 'gulp-webserver' например, порт и какую страницу загрузить, .

    Вы также можете запустить вашу задачу, просто набрав Ctrl + P и набрав task webserver

    Теперь вы можете установить расширение Просмотр в браузере . Я проверял это на окнах с хромом, и это работает.

    vscode версия: 1.10.2

    enter image description here

    В linux вы можете использовать команду xdg-open , чтобы открыть файл в браузере по умолчанию:

    Вот версия 2.0.0 для текущего документа в Chrome с сочетанием клавиш:

    Нажмите CTRL + C в терминале, чтобы выключить сервер

    Я только что опубликовал шаги, которые я использовал в блоге msdn . Это может помочь сообществу.

    Это поможет вам Настроить локальный веб-сервер, известный как lite-server с VS Code , а также поможет разместить ваши статические файлы html в localhost и debug ваш код Javascript .

    1. Установите Node.js

    Если он еще не установлен, получите его здесь

    Он поставляется с npm (менеджер пакетов для приобретения и управления вашими библиотеками разработки)

    2. Создайте новую папку для вашего проекта

    Где-нибудь на вашем диске создайте новую папку для вашего веб-приложения.

    3. Добавьте файл package.json в папку проекта

    Затем скопируйте/вставьте следующий текст:

    4. Установите веб-сервер

    В окне терминала (командная строка в Windows), открытом в папке вашего проекта, выполните эту команду:

    Это установит lite-сервер (определенный в package.json), статический сервер, который загружает index.html в ваш браузер по умолчанию и автоматически обновляет его при изменении файлов приложения.

    5. Запустите локальный веб-сервер!

    (Предполагая, что у вас есть файл index.html в папке вашего проекта).

    В том же окне терминала (командная строка в Windows) запустите эту команду:

    Подождите секунду, и index.html загрузится и отобразится в вашем браузере по умолчанию, обслуживаемом вашим локальным веб-сервером!

    lite-сервер следит за вашими файлами и обновляет страницу, как только вы вносите изменения в любые html, js или css файлы.

    И если у вас VS Code настроен на автоматическое сохранение (меню Файл/Автосохранение), вы увидите изменения в браузере по мере ввода!

    Заметки:

    Это оно. Теперь перед любой сессией кодирования просто наберите npm start и все готово!

    Первоначально опубликовано здесь в msdn блог . Кредиты переходит к автору: @Laurent Duveau

    Если вы только на Mac, это tasks.json файл:

    . это все, что вам нужно, чтобы открыть текущий файл в Safari, при условии, что его расширение ".html".

    Создайте tasks.json , как описано выше, и вызовите его с ⌘ + shift + b ,.

    Если вы хотите открыть его в Chrome, то:

    Это будет делать то, что вы хотите, как при открытии в новой вкладке, если приложение уже открыто.

    мой скрипт бегуна выглядит так:

    и он просто открывает мой проводник, когда я нажимаю ctrl shift b в моем файле index.html

    Открытие файлов в браузере Opera (в Windows 64 бит). Просто добавьте эти строки:

    Обратите внимание на формат пути в"command":line. Не используйте формат «C:\path_to_exe\runme.exe».

    Чтобы запустить эту задачу, откройте HTML-файл, который вы хотите просмотреть, нажмите F1, введите Task Opera и нажмите Enter

    Если вы введете > , он покажет вам команды show и run

    Или в вашем случае с HTML, я думаю, F5 после открытия палитры команд должен открыть отладчик.

    Читайте также: