Tìm kiếm trang web

typescript - Gửi tin nhắn từ webview đến tiện ích mở rộng


Tôi có một webview (SidebarProvider) cho phép người dùng nhập dữ liệu và gửi nó. Tôi muốn gửi dữ liệu đó đến một mở rộng SearchedWordPanel.

Các bước :

  1. Trong Chế độ Xem Thanh Bên của tôi (html, js và css), người dùng nhập một từ và nhấn "tìm kiếm". (Hoạt động)
  2. Từ này được gửi đến SidebarProvider, nơi nhận tin nhắn sử dụng onDidReceiveMessage và thực hiện lệnh để hiển thị SearchedWordPanel. (Hoạt động)
  3. SearchedWordPanel mở ra và hiển thị từ mà người dùng đã nhập. (Câu hỏi)

Tôi có thể làm được điểm 1 và 2 nhưng không thể gửi từ đã tìm kiếm đến SearchedWordPanel.

extensions.ts

const sidebarProvider = new SidebarProvider(context.extensionUri);
  context.subscriptions.push(
    vscode.window.registerWebviewViewProvider(
      "vsmyapp-sidebar",
      sidebarProvider
    )
  );

context.subscriptions.push(
  vscode.commands.registerCommand('vsmyapp.showSearched', () => {
    SearchedWordPanel.kill();
    SearchedWordPanel.createOrShow(context.extensionUri);
  })
);

Chế độ xem thanh bên

<button on:click={() =>
  tsvscode.postMessage({
    type: 'onSearch',
    value: searchedText
  })
}>Search</button>

NhàCungCấpThanhBên

webviewView.webview.onDidReceiveMessage(async (data) => {
  switch (data.type) {
    case "onSearch" : {
      if (!data.value) {
        return;
      }
      vscode.window.showInformationMessage(data.value); <-- WORKS
      vscode.commands.executeCommand( <--WORKS, the command is run. BUT How do I send data.value to SearchedWordPanel?
        "vsmyapp.showSearched",
      );
      COMMAND_THAT_SENDS_(data.value)_TO_SearchedWordPanel // Pseudocode
      break;
    }

Câu hỏi: làm thế nào tôi có thể gửi data.value đến SearchedWordPanel khi tôi thực hiện vscode.commands.executeCommand("vsmyapp.showSearched"); trong SidebarProvider?

Câu trả lời #1

Webview có postMessage - https://code.visualstudio.com/api/extension-guides/webview#passing-messages-from-an-extension-to-a-webview.

Tôi không chắc SearchedWordPanel là gì (Nó không phải là WebviewPanel), có lẽ là một lớp bao bọc.

Giả sử SearchedWordPanel có WebviewPanel gốc làm prop panel. Để gửi một tin nhắn tới nó, bạn có thể làm như sau:

SearchedWordPanel.panel.postMessage()