如果你要在 VS Code 插件的 WebView 中調用插件中的方法,可以使用 vscode.postMessage API。具體步驟如下:
在插件中,在創建 WebView 時,指定一個 onDidReceiveMessage 回調方法,該方法會在 WebView 中調用 vscode.postMessage 時被觸發。
在 WebView 中,使用 window.acquireVsCodeApi() 獲取 vscode 對象,然后通過 vscode.postMessage 向插件發送消息。
在插件中,當收到 WebView 發送的消息時,可以調用需要的方法,處理消息內容。
下面是一個簡單的示例代碼:
在插件中:
let currentPanel = undefined;export function activate(context: vscode.ExtensionContext) {// 創建 WebViewvscode.commands.registerCommand('myCommand', () => {if (!currentPanel) {currentPanel = vscode.window.createWebviewPanel('myWebview', // 唯一標識'My WebView', // 標題vscode.ViewColumn.One,{enableScripts: true,});// 監聽 WebView 發來的消息currentPanel.webview.onDidReceiveMessage((message) => {// 處理消息if (message.command === 'myCommand') {myMethod(message.arg1);}},undefined,context.subscriptions);}// 發送消息給 WebViewcurrentPanel.webview.postMessage({ command: 'myCommand', arg1: 'hello' });});
}function myMethod(arg1: string) {// 處理消息
}
在 WebView 中:
const vscode = acquireVsCodeApi();// 發送消息給插件
vscode.postMessage({ command: 'myCommand', arg1: 'hello' });
注意,WebView 中的 JavaScript 代碼需要在 HTML 文件中引入,需要在 WebView 中使用 webview.asWebviewUri 方法將文件路徑轉換為 vscode-resource: 協議的 URI,以確保安全。例如:
<script src="${webview.asWebviewUri(vscode.Uri.file(path.join(context.extensionPath, 'media', 'script.js')
))}"></script>
如果你想在 WebView 中接收插件的消息,可以使用 window.addEventListener 監聽 message 事件。具體步驟如下:
在 WebView 中,使用 window.addEventListener(‘message’, callback) 監聽 message 事件,其中 callback 是收到消息時要執行的函數。
在插件中,使用 webview.postMessage 向 WebView 發送消息,消息可以是任意類型的數據,如字符串、對象等。
在 WebView 中,當收到插件發送的消息時,會觸發 message 事件,事件對象中包含了消息的具體內容,可以通過 event.data 獲取。
下面是一個示例代碼:
在插件中:
let currentPanel = undefined;export function activate(context: vscode.ExtensionContext) {// 創建 WebViewvscode.commands.registerCommand('myCommand', () => {if (!currentPanel) {currentPanel = vscode.window.createWebviewPanel('myWebview', // 唯一標識'My WebView', // 標題vscode.ViewColumn.One,{enableScripts: true,});}// 發送消息給 WebViewcurrentPanel.webview.postMessage({ command: 'myCommand', arg1: 'hello' });});
}
在 WebView 中:
// 監聽插件發送的消息
window.addEventListener('message', (event) => {// 處理消息if (event.data.command === 'myCommand') {myMethod(event.data.arg1);}
});function myMethod(arg1) {// 處理消息
}
注意,為了確保安全,Webview 中的 JavaScript 代碼需要在 HTML 文件中引入,需要使用 webview.asWebviewUri 方法將文件路徑轉換為 vscode-resource: 協議的 URI。例如:
<script src="${webview.asWebviewUri(vscode.Uri.file(path.join(context.extensionPath, 'media', 'script.js')
))}"></script>