Answer a question

I'm building a VSCode extension which uses webview to display dynamic data using javascript and innerHTML. I found that the code is working properly in Chrome, but the innerHTML section does not work in VS Code webview.

HTML code

<!DOCTYPE html>
<html>

<body>
    <div id="root">
        Root
    </div>
    <script>
        document.getElementById('root').innerHTML += '<div>Inner HTML Success</div>'
    </script>
</body>

</html>

Here is the extension code:

    vscode.commands.registerCommand('my-extension.openFileInWebview', async (url: string) => {
        const panel = vscode.window.createWebviewPanel(
            'catCoding',
            'Cat Coding',
            vscode.ViewColumn.One,
            {}
        );

        const filePath = path.join(context.extensionPath, 'src', 'webviews', 'innerHtml.html');
        const fileContents = await readFile(filePath);
        const html = fileContents.toString();
        panel.webview.html = html;
    });

In VS Code

innerHTML not loading in VS Code

In Chrome

innerHTML is working in Chrome

Answers

innerHTML is supported. Just that Javascript is disabled in webview by default, and needs to be enabled using enableScripts: true option.

        const panel = vscode.window.createWebviewPanel(
            'catCoding',
            'Cat Coding',
            vscode.ViewColumn.One,
            {
                enableScripts: true
            }
        );
Logo

开发云社区提供前沿行业资讯和优质的学习知识,同时提供优质稳定、价格优惠的云主机、数据库、网络、云储存等云服务产品

更多推荐