上下文隔離是什么?
上下文隔離功能將確保您的 預加載腳本 和 的內部邏輯 運行在所加載的 網頁 之外的另一個獨立的上下文環境里。 這對安全性很重要,因為它有助于阻止網站訪問 的內部組件 和 您的預加載腳本可訪問的高等級權限的API 。
這意味著圖片預加載程序的正確邏輯,實際上,您的預加載腳本訪問的 對象并不是網站所能訪問的對象。 例如,如果您在預加載腳本中設置 .hello = 'wave ' 并且啟用了上下文隔離,當網站嘗試訪問.hello對象時將返回未定義。
自 12 以來圖片預加載程序的正確邏輯,默認情況下已啟用上下文隔離,并且它是 所有應用程序推薦的安全設置。
遷移
, I used to APIs from my using .X = . Now what?
之前: 上下文隔離禁用
APIs from your to a in the is a use-case. With , your would share a with the . You could then to a :
.js
// 上下文隔離禁用的情況下使用預加載
window.myAPI = {
doAThing: () => {}
}
The () could then be used in the :
.js
// 在渲染器中使用開放的 API
window.myAPI.doAThing()
之后:啟用上下文隔離
There is a in to help you do this in a way. The can be used to APIs from your 's to the the is in. API 還可以像以前一樣,從 .myAPI 網站上訪問。
.js
// 在上下文隔離啟用的情況下使用預加載
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('myAPI', {
doAThing: () => {}
})
.js
// 在渲染器中使用開放的 API
window.myAPI.doAThing()
read the above to fully its . For , you can't send or over the .
安全事項
單單開啟和使用 并不直接意味著您所做的一切都是安全的。 例如,此代碼是 不安全的。
.js
// ? 錯誤使用
contextBridge.exposeInMainWorld('myAPI', {
send: ipcRenderer.send
})
它直接暴露了一個沒有任何參數過濾的高等級權限 API 。 這將允許任何網站發送任意的 IPC 消息,這不會是你希望發生的。 相反,暴露進程間通信相關 API 的正確方法是為每一種通信消息提供一種實現方法。
.js
// ? 正確使用
contextBridge.exposeInMainWorld('myAPI', {
loadPreferences: () => ipcRenderer.invoke('load-prefs')
})
與一同使用
If you're your app with , you'll want to add types to your APIs over the . The 's won't have the you the types with a file.
For , given this .ts :
.ts
contextBridge.exposeInMainWorld('electronAPI', {
loadPreferences: () => ipcRenderer.invoke('load-prefs')
})
You can a .d.ts file and the :
.d.ts
export interface IElectronAPI {
loadPreferences: () => Promise,
}
declare global {
interface Window {
electronAPI: IElectronAPI
}
}
Doing so will that the will know about the on your when in your :
.ts
window.electronAPI.loadPreferences()