Как в vs code открыть страницу в браузере
Как просмотреть мой HTML-код в браузере с новым кодом Microsoft Visual Studio?
В Notepad ++ у вас есть возможность запускать в браузере. Как я могу сделать то же самое с кодом Visual Studio?
Для Windows – Откройте браузер по умолчанию – Протестировано на VS Code v 1.1.0
Ответьте на оба вопроса, чтобы открыть определенный файл (имя жестко запрограммировано) ИЛИ открыть ЛЮБОЙ другой файл.
шаги:
Используйте ctrl + shift + p (или F1 ), чтобы открыть палитру команд.
Введите ” Tasks: Configure Task или в более старых версиях ” Configure Task Runner . Выбор этого файла откроет файл tasks.json. Удалите отображаемый скрипт и замените его следующим:
Не забудьте изменить раздел “args” файла tasks.json на имя вашего файла. Это всегда откроет этот конкретный файл, когда вы нажмете F5.
Вы также можете установить this для открытия любого файла, который вы открыли в данный момент, используя ["$"] в качестве значения для “args”. Обратите внимание, что $ выходит за пределы <. >, поэтому [""] неверно.
Вернитесь к html файлу (в данном примере это “text.html”) и нажмите ctrl + shift + b , чтобы просмотреть свою страницу в веб-браузере.
VS Code имеет расширение Live Server, которое поддерживает запуск в один клик из строки состояния.
Некоторые из особенностей:
- Запуск одним кликом из строки состояния
- Live Обновить
- Поддержка Chrome Debugging Attachment
@InvisibleDev – чтобы заставить это работать на mac, пытаясь использовать это:
Если у вас уже открыт хром, он запустит ваш html файл на новой вкладке.
Если вы хотите иметь живую перезагрузку, вы можете использовать gulp -webserver, который будет следить за вашими файлами и перезагружать страницу, так что вам не нужно нажимать F5 каждый раз на вашей странице:
Вот как это сделать:
Откройте командную строку (cmd) и введите
npm install –save-dev gulp -webserver
Введите Ctrl + Shift + P в коде VS и введите Настроить запуск задачи. Выберите его и нажмите клавишу ввода. Он откроет для вас файл tasks.json. Удалите все, начиная с конца, введите только следующий код
tasks.json
- В корневой каталог вашего проекта добавьте gulpfile.js и введите следующий код:
gulpfile.js
- Теперь в VS Code введите Ctrl + Shift + P и введите “Запустить задачу”, когда вы входите в нее, вы увидите свою задачу “веб-сервер” и нажмите клавишу ввода.
Теперь ваш веб-сервер откроет вашу страницу в браузере по умолчанию. Теперь любые изменения, которые вы будете делать с вашими страницами HTML или CSS, будут автоматически перезагружены.
Ниже приведена информация о том, как настроить ‘gulp -webserver’ порт, и какую страницу загрузить,…
Вы также можете запустить свою задачу, просто введя Ctrl + P и введите веб-сервер задач
Теперь вы можете установить расширение Просмотреть в браузере. Я тестировал его на окнах с хромом, и он работает.
версия vscode: 1.10.2
В linux вы можете использовать команду xdg-open , чтобы открыть файл с браузером по умолчанию:
Вот версия 2.0.0 для текущего документа в Chrome с сочетанием клавиш:
Для работы на веб-сервере:
Я просто повторяю шаги, которые я использовал из блога 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 : @Laurent Duveau
Если вы только на Mac, это tasks.json файл:
… все, что вам нужно, чтобы открыть текущий файл в Safari, если его расширение является “.html”.
Создайте tasks.json , как описано выше, и вызовите его с помощью ⌘ + shift + b .
Если вы хотите, чтобы он открывался в Chrome, тогда:
Это будет делать то, что вы хотите, как при открытии новой вкладки, если приложение уже открыто.
Решение одним кликом просто установите open-in-browser Расширения с рынка Visual Studio.
Если вы наберете > , он покажет вам команды show и run
Или в вашем случае с HTML, я думаю, F5 после открытия палитры команд должен открыть отладчик.
Открытие файлов в браузере Opera (в Windows 64 бит). Просто добавьте следующие строки:
Обратите внимание на формат пути в строке “команда”:. Не используйте формат “C:\path_to_exe\runme.exe”.
Чтобы запустить эту задачу, откройте файл html, который хотите просмотреть, нажмите F1, введите task opera и нажмите enter
мой бегун script выглядит следующим образом:
и он просто открывает мой проводник, когда я нажимаю ctrl shift b в файле index.html
вот как вы можете запускать его в нескольких браузерах для Windows
Заметьте, что я не вводил ничего в args для edge, потому что Edge – мой браузер по умолчанию, просто дал ему имя файла.
EDIT: вам также не нужно -incognito или -private-window… это просто мне нравится просматривать его в частном окне
Для Mac – открывается в Chrome – проверено на VS Code v 1.9.0
- Используйте Command + shift + p , чтобы открыть палитру команд.
Введите Configure Task Runner, в первый раз, когда вы это сделаете, код VS даст вам меню прокрутки вниз, если оно выберет “Другое”. Если вы это сделали раньше, VS Code просто отправит вас непосредственно на tasks.json.
Один раз в файле tasks.json. Удалите отображаемый script и замените его на:
- Вернитесь в свой html файл и нажмите Command + shift + b , чтобы просмотреть свою страницу в Chrome.
Нажмите Ctrl + K, а затем M, откроется “Выбор режима языка” (или щелкните в правом нижнем углу с надписью HTML перед этим смайликом), введите разметку и нажмите Enter
Теперь нажмите Ctrl + K, а затем V, он откроет ваш HTML в ближайшей вкладке.
Теперь команды emmet не работали в этом режиме в моем html файле, поэтому я вернулся в исходное состояние (примечание – html tag tellisense работали отлично)
Чтобы перейти в исходное состояние – нажмите Ctrl + K, затем M, выберите автоопределение. Команды emmet начали работать. Если вас устраивает просмотрщик html файлов, вам не нужно возвращаться в исходное состояние.
Вам интересно, почему vscode не имеет опции просмотра html по умолчанию, когда он может отображать html файл в режиме уценки?
Во всяком случае, это круто. Счастливого vscoding 🙂
Вот версия 2.0.0 для Mac OSx:
Ctrl + F1 откроет браузер по умолчанию. альтернативно, вы можете нажать Ctrl + shift + P, чтобы открыть командное окно и выбрать “Просмотреть в браузере”. Код html должен быть сохранен в файле (несохраненный код в редакторе – без расширения, не работает)
Для будущих разработчиков, которые придут сюда в поисках решения. Это удивительное расширение, которое довольно недавно называется Browser Preview от Кеннета Аухенберга, вы можете получить расширение с рынка. Как начать, вы можете проверить это репо, как начать с предварительного просмотра браузера
Во всяком случае, мое решение ( windows ) построено на вершине @noontz’s. его конфигурации, возможно, было достаточно для более старых версий vscode но не с 1.34 (по крайней мере, я не мог заставить его работать..).
наши конфиги почти идентичны, за исключением одного свойства – это свойство является свойством group . Я не уверен, почему, но без этого моя задача даже не появилась бы в палитре команд.
так. рабочий tasks.json для пользователей windows использующий vscode 1.34 :
обратите внимание, что свойство problemMatcher не требуется для того, чтобы это работало, но без него вам навязывают дополнительный ручной шаг. пытался прочитать документы по этому свойству, но я слишком толстый, чтобы понять. надеюсь, кто-нибудь придет и обучит меня, но да, заранее спасибо за это. все, что я знаю, – включите это свойство, и ctrl+shift+b открывает текущий html файл в новой вкладке chrome , без проблем.
-
Откройте код Visual Studio, затем перейдите к расширениям.
Ищите “открыть в браузере”.
3. Установите его.
4.Нажмите правой кнопкой мыши свой HTML файл, вы найдете опцию “Открыть в браузере”.
Откройте пользовательский Chrome с URL-адресом из приглашения
Открыть пользовательский Chrome с активным файлом
Notes
- при необходимости замените свойство windows на другую ОС
- замените $ вашим собственным местоположением Chrome, например, "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
- замените $ вашим обычным каталогом Chrome, например,
"C:/My/Data/chrome/profile" или не указывать - Вы можете сохранить переменные, как указано выше, если хотите. Для этого добавьте следующие записи в settings.json – пользователь или рабочее пространство – и настройте пути в соответствии с вашими потребностями:
- Вы можете повторно использовать эти переменные, например, в launch.json для целей отладки: "runtimeExecutable": "$"
Вы не можете. Visual Studio не предназначалась для веб-дизайна или разработки. Вы должны закодировать некоторые строки, чтобы заставить его работать.
Как просмотреть мой HTML-код в браузере с новым кодом Microsoft Visual Studio?
с Notepad++ у вас есть возможность запускать в браузере. Как я могу сделать то же самое с кодом Visual Studio?
использовать ctrl + shift + p (или F1 ), чтобы открыть палитру команд.
тип Настройка Task Runner. Выбрав его откроется элемент задач.json. Удалите отображаемый скрипт и замените его следующим:
Не забудьте изменить раздел" args " задач.json-файл с именем вашего файла. Это всегда будет открывать этот конкретный файл, когда вы нажмете F5.
вы также можете установить это, чтобы открыть любой файл, который вы открыли в то время с помощью ["$"] как значение для "args". Обратите внимание, что $ выходит за пределы <. >, Так что [""] is неправильный.
сохраните файл.
вернитесь к своему html-файлу (в этом примере это "текст.html"), и нажмите ctrl + shift + b для просмотра страницы в веб-браузере.
@InvisibleDev-чтобы получить эту работу на mac пытается использовать это:
Если у вас уже открыт chrome, он запустит ваш html-файл на новой вкладке.
открыть командную строку (cmd) и введите
npm install --save-dev gulp-webserver
введите Ctrl + Shift+P в VS код и тип Настройка Task Runner. Выбрать ее и нажмите enter. Это откроет задачи.файл JSON для вас. Удалить все из него конец введите только следующий код
- в корневой каталог вашего проекта добавьте gulpfile.JS и введите следующий код:
- теперь в VS код введите Ctrl + Shift+P и введите "выполнить задачу" , когда вы введете его, вы увидите свою задачу "webserver" выбран и нажмите enter.
- запуск одним щелчком мыши из строки состояния
- Live Reload
- поддержка приложения отладки Chrome
теперь вы можете установить расширение Просмотр В Браузере. Я тестировал его на windows с chrome, и он работает.
версия vscode: 1.10.2
в Linux, вы можете использовать xdg-open команда для открытия файла в браузере по умолчанию:
вот версия 2.0.0 для текущего документа в Chrome с сочетанием клавиш:
tasks.json
keybindings.json :
если вы просто на Mac это tasks.json file:
. это все, что вам нужно, чтобы открыть текущий файл в Safari, предполагая, что его расширение ".формат HTML."
создать tasks.json как описано выше, и запустите его с ⌘ + shift + b .
если вы хотите, чтобы он открылся в Chrome, то:
это будет делать то, что вы хотите, как при открытии в новой вкладке, если приложение уже открыто.
открытие файлов в браузере Opera (на 64 битах Windows). Просто добавьте эти строки:
обратите внимание на формат пути на "команды": линии. Не используйте "C:\path_to_exe\runme.формат exe".
чтобы запустить эту задачу, откройте html-файл, который вы хотите просмотреть, нажмите F1, введите task opera и нажмите enter
мой скрипт бегуна выглядит так:
и это просто открыть мой проводник, когда я нажимаю ctrl shift b в моем индексе.html файл
вот как вы можете запустить его в нескольких браузерах для Windows
обратите внимание, что я ничего не набирал в args для edge, потому что Edge-это мой браузер по умолчанию, просто дал ему имя файла.
EDIT: также вам не нужно-инкогнито и -private-window. it ' это только мне нравится, чтобы посмотреть его в частном окне
- использовать команда + shift + p чтобы открыть палитру команд.
введите Configure Task Runner, в первый раз, когда вы это сделаете, VS Code даст вам меню прокрутки вниз, если он выберет "другое."Если вы делали это раньше, VS Code просто отправит вас прямо в задачи.формат JSON.
один раз в задачах.файл json. Удалите отображаемый скрипт и замените его следующим:
- вернитесь к html-файлу и нажмите команда + Shift + b для просмотра страницы в Chrome.
один клик решение просто установить открыть в браузере расширения из Visual Studio marketplace.
Ctrl + F1 откроет браузер по умолчанию. кроме того, вы можете нажать Ctrl + shift + P, чтобы открыть командное окно и выбрать "просмотр в браузере". Html код должен быть сохранен в файл (несохраненный код в редакторе - без расширения, не работает)
недавно наткнулся на эту функцию в одном из учебников кода visual studio в www.lynda.com
нажмите Ctrl + K, а затем M, он откроет "выберите режим языка" (или нажмите на правый нижний угол, который говорит HTML перед этим смайликом), введите markdown и нажмите enter
Теперь нажмите Ctrl + K, а затем V, он откроет ваш html в соседней вкладке.
Tadaaa .
теперь команды emmet не работали в этом режим в моем html-файле, поэтому я вернулся в исходное состояние (Примечание - html-тег tellisense работал отлично )
чтобы перейти в исходное состояние-нажмите Ctrl + K, затем M, выберите автоопределение. команды Эммета начали работать. Если вы довольны только HTML viewer, то вам не нужно возвращаться в исходное состояние.
интересно, почему vscode не имеет опции просмотра html по умолчанию, когда он может отображать html-файл в markdown режим.
в любом случае это круто. Счастливый vscoding :)
вы не можете. Visual Studio не предназначалась для веб-дизайна или разработки. Вы должны закодировать некоторые строки, чтобы заставить его работать.
VS Code for the Web has many of the features of VS Code desktop that you love, including search and syntax highlighting while browsing and editing, along with extension support to work on your codebase and make simpler edits. In addition to opening repositories, forks, and pull requests from source control providers like GitHub and Azure Repos (in preview), you can also work with code that is stored on your local machine.
VS Code for the Web runs entirely in your web browser, so there are certain limitations compared to the desktop experience, which you can read more about below.
Relationship to VS Code desktop
VS Code for the Web provides a browser-based experience for navigating files and repositories and committing lightweight code changes. However, if you need access to a runtime to run, build, or debug your code, or you want to use platform features such as a terminal, we recommend moving your work to the desktop application or GitHub Codespaces for the full capabilities of VS Code. In addition, VS Code desktop lets you run extensions that aren't supported in the web version, and use a full set of keyboard shortcuts not limited by your browser.
When you're ready to switch, you'll be able to "upgrade" to the full VS Code desktop experience with a few clicks.
Opening a project
To work with both GitHub and Azure Repos, VS Code for the Web supports two routes, vscode.dev/github and vscode.dev/azurerepos :
GitHub Repositories is the core component that provides the ability to remotely browse and edit a repository from within the editor.
Rather than cloning your work, GitHub Repositories creates a virtual file system to access repositories and pull requests, allowing you to become productive quickly without needing to pull code onto your local machine. You can learn more about the extension in our GitHub Repositories guide.
Note: The GitHub Repositories extension works in VS Code desktop as well to provide fast repository browsing and editing.
You can create a new file in the web just as you would in a desktop VS Code environment, using File > New File from the Command Palette ( F1 ).
Azure Repos (preview)
Support for Azure Repos (part of Azure DevOps) in Visual Studio Code for the Web is in preview, and the experience will continue to grow and evolve over time.
You can open any repository, branch, or tag from Azure Repos in VS Code for the Web by prefixing vscode.dev to the Azure Repos URL.
Current limitations
Azure Repos support is currently read-only. Commit, branch, fork, and PR actions are disabled in the Source Control view and Command Palette.
More custom URLs
Like in the desktop, you can customize VS Code for the Web through a rich ecosystem of extensions that support just about every back end, language, and service. Unlike in the desktop, it's easy for us to deliver customized experiences with pre-installed extensions through unique vscode.dev URLs (like vscode.dev/github and vscode.dev/azurerepos described above).
Themes
Note: The color theme URL scheme works for themes that are fully declarative (no code).
An extension can define multiple themes. You can use the schema /theme/extensionId/themeName . If no themeName is specified, VS Code for the Web will take the first theme.
As a theme author, you can add the following badge to your extension readme to allow users to easily try out your theme in VS Code for the Web (replacing with your theme extension's unique identifier):
Visual Studio Live Share
Continue working in a different environment
In some cases, you will want to access a different environment that has the ability to run code. You can switch to working on a repository in a development environment that has support for a local file system and full language and development tooling.
The GitHub Repositories extension makes it easy for you to clone the repository locally with the GitHub Repositories: Continue Working on. command available from the Command Palette ( F1 ) or by clicking on the Remote indicator in the Status bar.
Safe exploration
VS Code for the Web runs entirely in your web browser's sandbox and offers a very limited execution environment.
When accessing code from remote repositories, the web editor doesn't "clone" the repo, but instead loads the code by invoking the services' APIs directly from your browser; this further reduces the attack surface when cloning untrusted repositories.
When working with local files, VS Code for the Web loads them through your browser's file system access APIs, which limit the scope of what the browser can access.
Saving and sharing work
When working on a local file in the web, your work is saved automatically if you have Auto Save enabled. You can also save manually as you do when working in desktop VS Code (for example File > Save).
When working on a remote repository, your work is saved in the browser's local storage until you commit it. If you open a repo or pull request using GitHub Repositories, you can push your changes in the Source Control view to persist any new work.
Run anywhere
Similar to GitHub Codespaces, VS Code for the Web can run on tablets, like iPads.
Language support
Language support is a bit more nuanced on the web, including code editing, navigation, and browsing. The desktop experiences are typically powered by language services and compilers that expect a file system, runtime, and compute environment. In the browser, these experiences are powered by language services running in the browser that provide source code tokenization and syntax colorization, completions, and many single-file operations.
Generally, experiences fall into the following categories:
You can determine the level of language support in your current file through the Language Status Indicator in the Status bar:
Limitations
Since VS Code for the Web runs completely within the browser, some experiences will naturally be more constrained when compared to what you can do in the desktop app. For example, the terminal and debugger are not available, which makes sense since you can't compile, run, and debug a Rust or Go application within the browser sandbox.
Extensions
Only a subset of extensions can run in the browser. You can use the Extensions view to install extensions in the web, and extensions that cannot be installed will have a warning icon and Learn Why link. We expect more extensions to become enabled over time.
When you install an extension, it is saved in the browser's local storage. You can ensure your extensions are synced across VS Code instances, including different browsers and even the desktop, by enabling Settings Sync.
When an Extension Pack contains extensions that do not run in the browser sandbox, you will get an informational message with the option to see the extensions included in the pack.
When extensions are executed in the browser sandbox, they are more restricted. Extensions that are purely declarative, such as most themes, snippets, or grammars, can run unmodified and are available in VS Code for the Web without any modification from the extension authors. Extensions that are running code need to be updated to support running in the browser sandbox. You can read more about what is involved to support extensions in the browser in the web extension authors guide.
There are also extensions that run in the browser with partial support only. A good example is a language extension that restricts its support to single files or the currently opened files.
File system API
Edge and Chrome today support the File System API, allowing web pages to access the local file system. If your browser does not support the File System API, you cannot open a folder locally, but you can open files instead.
Browser support
You can use VS Code for the Web in Chrome, Edge, Firefox, and Safari.
Webviews might appear differently or have some unexpected behavior in Firefox and Safari. You can view issue queries in the VS Code GitHub repo to track issues related to specific browsers, such as with the Safari label and Firefox label.
There are additional steps you can take to improve your browser experience using VS Code for the Web. Review the Additional browser setup section for more information.
Mobile support
You can use VS Code for the Web on mobile devices, but smaller screens may have certain limitations.
Keybindings
Certain keybindings may also work differently in the web.
Issue | Reason |
---|---|
⇧⌘P (Windows, Linux Ctrl+Shift+P ) won't launch the Command Palette in Firefox. | ⇧⌘P (Windows, Linux Ctrl+Shift+P ) is reserved in Firefox. As a workaround, use F1 to launch the Command Palette. |
⌘N (Windows, Linux Ctrl+N ) for new file doesn't work in web. | ⌘N (Windows, Linux Ctrl+N ) opens a new window instead. As a workaround, you can use Ctrl+Alt+N ( Cmd+Alt+N on macOS). |
⌘W (Windows, Linux Ctrl+W ) for closing an editor doesn't work in web. | ⌘W (Windows, Linux Ctrl+W ) closes the current tab in browsers. As a workaround, you can use Ctrl+Shift+Alt+N ( Cmd+Shift+Alt+N on macOS). |
⇧⌘B (Windows, Linux Ctrl+Shift+B ) will not toggle the favorites bar in the browser. | VS Code for the Web overrides this and redirects to the "Build" menu in the Command Palette. |
Additional browser setup
There are additional browser configuration steps you can take when working with VS Code in a browser.
Opening new tabs and windows
In certain cases, you may need to open a new tab or window while working in VS Code for the Web. VS Code might ask you for permission to access the clipboard when reading from it. Depending on your browser, you may grant access to the clipboard or otherwise allow for pop-up windows in different ways:
Visual Studio Code includes a built-in debugger for Edge and Chrome. There are a couple ways to get started with it.
- Use the Open Link command to debug a URL.
- Clicking a link in the JavaScript debug terminal.
- Use a launch config to launch a browser with your app.
We also have more detailed walkthroughs to get started with React, Angular, Vue, and Ember, as well as other debugging recipes.
Open Link command
The simplest way to debug a webpage is through the Debug: Open Link command found in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). When you run this command, you'll be prompted for a URL to open, and the debugger will be attached.
If your default browser is Edge, VS Code will use it to open the page. Otherwise, it will try to find an installation of Chrome on your system instead.
Launch configuration
Launch configs are the traditional way to set up debugging in VS Code, and provide you the most flexibility for running complex applications.
In this section, we'll go into more detail about configurations and features for more advanced debugging scenarios. Instructions for Node.js debugging with source maps and stepping over external code also apply to browser-based debugging.
Note: If you are just getting started with VS Code, you can learn about general debugging features and creating launch.json configuration files in the Debugging topic.
Launching browsers
In most cases, you'll want to start a new instance of the browser to debug your webpage or file. To do this, you can create a file named .vscode/launch.json that looks like this:
You can also debug a single file without running a server, for example:
Attaching to browsers
To attach to a running browser, it needs to be launched in a special debug mode. You can do this using the following command, replacing edge.exe with the path to your Edge or Chrome binary:
Setting the --remote-debugging-port tells the browser to listen on that port for a debug connection. Setting a separate --user-data-dir forces a new instance of the browser to be opened; if this flag isn't given, then the command will open a new window of any running browser and not enter debug mode.
Next, add a new section to the vscode/launch.json file as below:
Now, you can press F5 or the Start button in the Debug view to attach to the running browser. You can even add a host property to debug a browser running on a different machine.
Launch configuration attributes
Debugging configurations are stored in a launch.json file located in your workspace's .vscode folder. An introduction into the creation and use of debugging configuration files is in the general Debugging article. You can either "launch" a browser with your application, or "attach" to an existing browser that you started in debug mode.
Below is a reference of common launch.json attributes specific to browser debugging. You can view the complete set of options in the vscode-js-debug options documentation.
- webRoot - The root directory for your source code. Most often, and by default, the webRoot is your workspace folder. This option is used for sourcemap resolution.
- outFiles - An array of glob patterns for locating generated JavaScript files. See the section on Source maps.
- smartStep - Try to automatically step over source code that doesn't map to source files. See the section on Smart stepping.
- skipFiles - Automatically skip files covered by these glob patterns. See the section on Skipping uninteresting code.
- trace - Enable diagnostic output.
These attributes are only available for launch configurations of request type launch :
- url - The URL to automatically open when the browser is launched.
- runtimeExecutable - Either an absolute path to the browser executable to use, or the version of the browser to use. Valid versions include stable (default), canary , beta , and dev .
- runtimeArgs - Optional arguments passed when launching the browser.
These attributes are only available for launch configurations of request type attach :
I am writing a visual studio code extension and I'd like to be able to open a browser window with a specific url in response to a command. I know that Electron has a BrowserWindow class but it appears that the Electron API is not accessible from a vscode extension.
I'd prefer the browser window to open within the tool but I'd be ok with opening the web page in my default browser if it is not possible.
How does one open a web page from an extension?
Yes, the answer referenced by @Steffen will open a browser outside of VS Code. This is my backup plan. However, it would be slightly better for my extension if the browser window was in VS Code. Is it possible to open a browser within the tool itself?
@MattBierner Your first suggested duplicate covers what Mark addresses, above: He wants to open in VS Code, not an external browser like that question details. The second would likely more rightfully be marked as a duplicate of this question, since Mark's predates it by over a year.
3 Answers 3
- Open the pallet (Ctrl + Shift + P)
- Select "Simple Browser: Preview"
- Enter web address
wow! this combined with live server extension (@^0^@)/ is the only side-by-side HTML preview solution that actually works.
This worked for me, once, and then afterwards I only see a white screen. Tried reloading/restarting Code, doesn't resolve :( Code's Developer Console shows a warning: main.js [Violation] Avoid using document.write(). Then I tried again with a simple site (e.g. milosophical.me) which works, but a site with frames (e.g. stackoverflow.com) does not. Error: Refused to frame 'stackoverflow.com' because an ancestor violates the Content Security Policy "frame-ancestors 'self'"
To open a browser window inside VS Code you can use the WebView API, though you need to supply HTML content rather than a URL:
Depending on your specific use case, there's also the Browser Preview extension which registers a command browser-preview.openPreview that you could use (you'd probably want to list browser-preview as a dependency to ensure it's installed).
And finally, if you just want to open in a normal browser window you can use the env.openExternal API. When running in remote environments this will also take care of exposing ports and mapping to the exposed hostname (if it's a localhost-served service):
Читайте также: