[英]Load external js in external html file in Webview [vscode-extensions]
我正在尝试使用外部 HTML 文件在我的扩展中创建一个 webview 并在脚本标记中加载一个外部 js 文件。
HTML 文件已正确加载,但 HTML 文件无法打开 js 文件。 我尝试从两种方式加载 - Option A
和Option B
但他们都没有工作。 我在 SO 上提到了与此相关的其他类似问题,但没有太大帮助。
在检查调试器控制台Ctrl+Shift+P
时,我收到此错误:
无法加载资源:.net::ERR_ACCESS_DENIED
这是代码片段
扩展.ts
let htmlContent = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf8')
export async function activate(context: vscode.ExtensionContext) {
...
...
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, 'out', 'index.js')
);
// const jsFileSrc = panel.webview.asWebviewUri(onDiskPath); //Option A
const jsFileSrc = onDiskPath.with({ scheme: 'vscode-resource' }); //Option B
console.log(jsFileSrc);
panel.webview.html = getWebviewContent(jsFileSrc);
...
...
}
export function getWebviewContent(jsFileSrc:vscode.Uri){
return `${htmlContent}`
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Coding</title>
</head>
<body>
<div id="content"></div>
<script src="{{jsFileSrc}}"><script>
</body>
</html>
首先,您需要使用元标记定义内容安全策略。 这对我行得通
<meta http-equiv="Content-Security-Policy" content="default-src self; img-src vscode-resource:; script-src vscode-resource: 'self' 'unsafe-inline'; style-src vscode-resource: 'self' 'unsafe-inline'; "/>
并允许在 webview 配置中使用脚本。
其次,您需要路径 HTML。我使用的是 xmldom。
const XML = require('xmldom');
const PATH = require('path');
//base_path = context.extensionPath
function pathHTML(html, base_path){
const doc = new XML.DOMParser().parseFromString(
html,
'text/html' //It is important, html may be not valid XML document
);
for (let script of doc.getElementsByTagName('script')){
let path = PATH.parse(script.getAttribute('src')); //use relative path
path = `vscode-resource: ${PATH.resolve(base_path, path)}`;
//The documentation says use vscode.Uri.file, but my varinat works too.
script.setAttribute('src', path);
}
return new XML.XMLSerializer().serializeToString(doc);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.