Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a browser window in a visual studio code extension?

Tags:

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?

like image 204
Mark M Avatar asked May 06 '16 16:05

Mark M


2 Answers

This was added recently (see microsoft/vscode#109276).

  1. Open the pallet (Ctrl + Shift + P)
  2. Select "Simple Browser: Preview"
  3. Enter web address
like image 148
John Henry Avatar answered Sep 27 '22 18:09

John Henry


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:

export function activate(context: vscode.ExtensionContext) {   context.subscriptions.push(     vscode.commands.registerCommand('catCoding.start', () => {       // Create and show panel       const panel = vscode.window.createWebviewPanel(         'catCoding',         'Cat Coding',         vscode.ViewColumn.One,         {}       );        // And set its HTML content       panel.webview.html = getWebviewContent();     })   ); }  function getWebviewContent() {   return `<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Cat Coding</title> </head> <body>     <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" /> </body> </html>`; } 

enter image description here

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):

vscode.env.openExternal(Uri.parse("https://www.stackoverflow.com/")); 
like image 29
Danny Tuppeny Avatar answered Sep 27 '22 16:09

Danny Tuppeny