问题描述
按照 API 文档,我不明白如何为我的 Electron 应用程序的渲染器定义一个 Content-Security-Policy HTTP Header.我总是在 DevTools 中收到警告.
Following the API documentation, I don't understand how to define a Content-Security-Policy HTTP Header for the renderer of my Electron application. I always get a warning in the DevTools.
我试过了:
1) 盲目复制/粘贴API Doc中的代码:
1) Copy/Paste the code in the API Doc, blindly:
app.on('ready', () => {
const {session} = require('electron')
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({responseHeaders: `default-src 'self'`})
})
win = new BrowserWindow(...)
win.loadUrl(...)
}
(顺便说一句,我不明白为什么字符串中缺少Content-Security-Policy:".但是添加它不会改变任何东西)
(By the way, I don't get why "Content-Security-Policy:" is missing in the string. But adding it don't change anything)
2) 用同样的代码修改渲染器的会话:
2) Modifying the session of the renderer with the same code:
win = new BrowserWindow(...)
win.loadUrl(...)
const ses = win.webContents.session;
ses.webRequest.onHeadersReceived((details, callback) => {
callback({responseHeaders: `default-src 'self'`})
})
3) 向渲染器添加额外的标头:
3) Add an extra header to ther renderer:
win = new BrowserWindow(...)
win.loadURL(`file://${__dirname}/renderer.html`,{
extraHeaders: `Content-Security-Policy: default-src 'self'`
});
...
唯一有效的是在渲染器 HTML 文件中使用元标记:
The only thing that works is using a meta tag in the renderer HTML file:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'>
推荐答案
不知道为什么文档包含这个损坏的代码.它把我弄糊涂了,但我通过反复试验找到了一个可行的解决方案:
Not sure why the documentation contains this broken code. It confused the hell out of me but I found a working solution by trial and error:
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
callback({ responseHeaders: Object.assign({
"Content-Security-Policy": [ "default-src 'self'" ]
}, details.responseHeaders)});
});
所以 headers 参数必须是一个与 details.responseHeaders
中接收到的原始 headers 具有相同结构的对象.并且原始标头也必须包含在传递的对象中,因为该对象似乎完全替换了原始响应标头.
So the headers argument must be an object with the same structure as the original headers received in details.responseHeaders
. And the original headers must be included in the passed object as well because this object seems to completely replace the original response headers.
extraHeaders
选项不适用于响应标头.它用于发送到服务器的请求标头.
The extraHeaders
option isn't for response headers. It is for request headers sent to the server.
这篇关于在 Electron App 中定义 CSP HTTP Header的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!