How to open browser from Visual Studio Code API

岁酱吖の 提交于 2019-12-09 16:34:03

问题


I am just exploring a way in order to open the default browser from Visual Studio Code API used for developing extensions.

Following is my code :

var disposable = vscode.commands.registerCommand('extension.browser', () => {
  // The code you place here will be executed every time your command is executed
  vscode.Uri.call("http://facebook.com");
});

How to open Browser URL from API using vscode class.


回答1:


There is no need for node or external libraries.

If you are using VS Code 1.31+, use the vscode.env.open function:

import * as vscode from 'vscode';

vscode.env.openExternal(vscode.Uri.parse('https://example.com'));

For older VS Code versions, use the vscode.open command:

vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://example.com'))

Both of these will open the page in the user's default browser




回答2:


I had to use npm open url in order to open in browser.

var openurl = require('openurl').open;
    openurl("http://google.com");



回答3:


You don't need to install an external dependency. Opening an URL can be simply done with just the Node.js libraries and system commands. For e.g. use the child_process.exec to open an URL.

Declare a function like so:

const exec = require('child_process').exec;

function openURL(url) {
  let opener;

  switch (process.platform) {
    case 'darwin':
      opener = 'open';
      break;
    case 'win32':
      opener = 'start';
      break;
    default:
      opener = 'xdg-open';
      break;
  }

  return exec(`${opener} "${url.replace(/"/g, '\\\"')}"`);
}

and then call it from your code

openURL('http://stackoverflow.com');


来源:https://stackoverflow.com/questions/34205481/how-to-open-browser-from-visual-studio-code-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!