[英]Why does localhost not work inside my VS Code's webviews when connected to remote workspaces?
我有一個簡單的擴展,它使用VS Code 的 webview api從我的擴展生成的服務器加載內容。 它使用指向localhost
的 iframe 執行此操作:
import * as vscode from 'vscode';
import * as express from 'express';
const PORT = 3000;
export function activate(context: vscode.ExtensionContext) {
// Spawn simple server
const app = express();
app.get('/', (_req, res) => res.send('Hello VS Code!'));
app.listen(PORT)
context.subscriptions.push(
vscode.commands.registerCommand('myExtension.startPreview', () => {
const panel = vscode.window.createWebviewPanel('myExtension.preview', 'Preview', vscode.ViewColumn.One,
{
enableScripts: true
});
panel.webview.html = `<!DOCTYPE html>
<html lang="en"">
<head>
<meta charset="UTF-8">
<title>Preview</title>
<style>
html { width: 100%; height: 100%; min-height: 100%; display: flex; }
body { flex: 1; display: flex; }
iframe { flex: 1; border: none; background: white; }
</style>
</head>
<body>
<iframe src="http://localhost:${PORT}"></iframe>
</body>
</html>`
}));
}
當擴展在本地運行時,這工作正常,但是當我嘗試在遠程工作區中運行我的擴展時,iframe 為空:
為什么會發生這種情況,我該如何解決?
在遠程工作空間中的webview中使用localhost時,這是預期的。 根本原因是webview加載在用戶的本地計算機上,而您的擴展在遠程計算機上運行:
有兩種可能的解決方法:
如果不需要從工作區讀取文件或使用僅與工作區一起安裝的腳本/工具,則可以將擴展作為UI擴展。 UI擴展在用戶的本地計算機上運行,因此可以使用localhost訪問它生成的服務器
只需在您的擴展程序的package.json
添加"extensionKind": "ui"
即可。
VS Code端口映射API允許您將webview中使用的localhost端口映射到運行擴展的計算機上的任意端口。 如果您的擴展程序遠程運行,這甚至可以工作
VS Code 1.34中添加了端口映射API。 要使用它,請在創建webview面板時傳入portMapping
對象:
const panel = vscode.window.createWebviewPanel('myExtension.preview', 'Preview', vscode.ViewColumn.One,
{
enableScripts: true,
// This maps localhost:3000 in the webview to the express server port on the remote host.
portMapping: [
{ webviewPort: PORT, extensionHostPort: PORT}
]
});
如果您的webview出於任何原因使用localhost,最好設置portMapping
以便它可以在任何地方正常運行。 實際上,您還應該考慮隨機化運行服務器的端口。 使用端口映射,您沒有為此更改webview的html:
{ webviewPort: 3000, extensionHostPort: RANDOM_PORT_SERVER_WAS_STARTED_ON }
作為這個問題的參考,我認為我們應該使用這里提到的api- vscode.env.asExternalUri
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.