如何在 vscode 中保存整个 Webview

How can I save the whole body of Webview in vscode

Webview Api Guide 的持久性部分,展示了如何持久化 JSON 可序列化状态对象。 但是我怎样才能使我的整个 html 代码保持不变,以防 webview 失去焦点?

在我的扩展程序中,我正在接收来自 vscode 扩展程序的消息并通过附加 <p>paragraph</p> 更新 Webview

当您创建 webview 时,您可以设置一个选项以在隐藏视图时保留内容,如下所示:

    let panel = window.createWebviewPanel(
        'antlr4-vscode-webview', options.title, ViewColumn.Two, {
            enableScripts: true,
            retainContextWhenHidden: true
        }
    );

如果你只想保留某个 DOM 节点(包括正文甚至整个文档)你可以向你的 webview 发送消息,处理此消息的函数获取外部 HTML 并将该文本发送回您的分机,它可以保存并在以后恢复。

在我的扩展 vscode-antlr4 中,我这样做是为了 export generated SVG content(使用 D3.js 创建):

function exportToSVG(type, name) {
    // Saving the SVG is delegated to the extension to allow asking the user for a target file.
    const svg = document.querySelectorAll('svg')[0];
    const args = {
        command: "saveSVG",
        name: name,
        type: type,
        svg: svg.outerHTML
    };

    vscode.postMessage(args);
}

处理此消息的代码在 WebviewProvider class 中。同一个文件还包含发送消息到webview内容的方法:

protected sendMessage(uri: Uri, args: any): boolean {
    if (this.webViewMap.has(uri.toString())) {
        let [panel, _] = this.webViewMap.get(uri.toString())!;
        panel.webview.postMessage(args);
        return true;
    }
    return false;
}