在VSCode扩展程序中使用“确定”按钮在窗口中显示HTML

时间:2019-03-19 10:54:14

标签: visual-studio-code vscode-extensions

如果用户同意,我需要在光标后插入文本。我找不到in the documentation的任务。

我的扩展程序的任务:

  1. 用户编写代码
  2. 然后他将其称为分机
  3. 它将所有代码发送到服务器
  4. 使用“确定”按钮返回并在其他窗口中显示一些代码
  5. 按下“确定”按钮会将服务器的响应插入到光标之后

我对第4点有疑问。找不到通过“确定”按钮显示其他窗口的方法。

extension.js中的所有代码:

function activate(context) {
  console.log('"showText" active');

  const commandId = 'extension.showText'
  let disposable = vscode.commands.registerCommand(commandId, function () {
    const text = editor.document.getText()

    let options = {
      method: 'GET',
      uri: 'http://example.com:8081/',
      body: {
        text: text
      },
      json: true
    }
    rp(options)
      .then(function (respString) {
        console.log(respString);
        // what should I call here?
        // vscode.window.showInformationMessage(respString);
      })
      .catch(function(err) {
        console.log(err);
      });
  });
  context.subscriptions.push(disposable);
}
exports.activate = activate;

function deactivate() {
  console.log('showText disactive');
}

module.exports = {
  activate,
  deactivate
}

1 个答案:

答案 0 :(得分:0)

它不是How to handle click event in Visual Studio Code message box?的重复项,因为我需要HTML页面。而这个决定只是显示带有confim按钮的短信。

我的决定是: webview-sample Webview API

My example:
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const workspace = vscode.workspace;
const window = vscode.window;
const rp = require("request-promise");

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */

function activate(context) {
  // Use the console to output diagnostic information (console.log) and errors (console.error)
  // This line of code will only be executed once when your extension is activated
  console.log('Extension activated');


  // The command has been defined in the package.json file
  // Now provide the implementation of the command with  registerCommand
  // The commandId parameter must match the command field in package.json
  const commandId = 'extension.showText'
  let disposable = vscode.commands.registerCommand(commandId, function () {
    const editor = window.activeTextEditor;
    const text = editor.document.getText();

    console.log('For editor "'+ editor._id +'"');

    let options = {
      method: 'POST',
      uri: URL,
      body: {
        text: text
      },
      json: true
    };

    rp(options)
      .then(function (res) { // res
        const panel = window.createWebviewPanel(
          'type_id', // Identifies the type of the webview. Used internally
          'Title', // Title of the panel displayed to the user
          vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
          {
            // Enable scripts in the webview
            enableScripts: true
          } // Webview options. More on these later.
        );
        panel.webview.html = res;


        // Handle messages from the webview
        // закрывать когда выбираешь другое окошко
        window.onDidChangeActiveTextEditor(
          ev => {
            // console.log(ev._id, editor._id, editor);
            ev && ev._id && ev._id != editor._id && panel.dispose();
          }
        )
        // закрывать когда закрываешь окно
        workspace.onDidCloseTextDocument(
          textDocument => {
            console.log("closed => " + textDocument.isClosed)
            panel.dispose();
          },
          null,
          context.subscriptions
        );
        // любая клавиша кроме enter - фильтр по префиксу
        // если enter - поиск подсказок
        workspace.onDidChangeTextDocument(
          ev => {
            console.log(ev);

            if (ev && ev.contentChanges && ev.contentChanges.length
                   && (ev.contentChanges[0].text || ev.contentChanges[0].rangeLength)) {
              // do smth
            } else {
              console.error('No changes detected. But it must be.', ev);
            }
          },
          null,
          context.subscriptions
        );

        panel.webview.onDidReceiveMessage(
          message => {
            switch (message.command) {
            case 'use':
              console.log('use');
              editor.edit(edit => {
                let pos = new vscode.Position(editor.selection.start.line,
                                              editor.selection.start.character)
                edit.insert(pos, message.text);
                panel.dispose()
              });
              return;
            case 'hide':
              panel.dispose()
              console.log('hide');
              return;
            }
          },
          undefined,
          context.subscriptions
        );

        panel.onDidDispose(
          () => {
            console.log('disposed');
          },
          null,
          context.subscriptions
        )
    })
    .catch(function(err) {
      console.log(err);
    });
  });
  context.subscriptions.push(disposable);
}
exports.activate = activate;

// this method is called when your extension is deactivated
function deactivate() {
  console.log('Extension disactivated');
}

module.exports = {
  activate,
  deactivate
}

res的示例:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  </head>
  <body>
    <p id="text">Text</p>
    <button onclick="useAdvise()">Use</button>
    <button onclick="hideAdvise()">Hide</button>
    <script>
      const vscode = acquireVsCodeApi();
      function useAdvise(){
        let text_ = $(document).find("#text").text();
        vscode.postMessage({command: 'use',text: text_})
      }
      function hideAdvise(){
        vscode.postMessage({command: 'hide'})
      }
    </script>
  </body>
</html>