Define CSP HTTP Header in Electron App(在 Electron App 中定义 CSP HTTP Header)
问题描述
按照 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Electron App 中定义 CSP HTTP Header
基础教程推荐
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01