問題描述
按照 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!