我有一个电子应用程序。我的客户端脚本(渲染器)需要访问电子API,但这给了我一个安全警告,因此我将其移动到预加载脚本并禁用了nodeIntegration。然后我收到有关contextIsolation的警告,所以我启用了它。我的preload脚本以前将一个函数附加到窗口,客户端可以读取如下:
window.readClipboard = function(){
return clipboard.readText()
}
不幸的是,上下文隔离意味着客户端无法再访问此功能。有没有办法让这个工作与上下文隔离或我应该禁用它?
额外细节
使我尝试打开上下文隔离的警告消息如下:
Electron Deprecation Warning(contextIsolation默认更改)此窗口默认禁用上下文隔离。在Electron 5.0.0中,默认情况下将启用上下文隔离。要准备此更改,请在此窗口的webPreferences中设置{contextIsolation:false},或者确保此窗口不依赖于禁用上下文隔离,并设置{contextIsolation:true}。
在client.js中我尝试访问:
console.log("window.readClipboard", window.readClipboard)
随着输出:
window.readClipboard undefined
据我所知,上下文隔离旨在防止您描述的情况。因此,如果您想将数据添加到window
,您可以做的最好是禁用隔离。
但是,我在Content Scripts定义中查找了BrowserWindow文档中引用的contextIsolation
文档,并找到了使用postMessage
获取剪贴板文本的方法。
main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
app.once('ready', () => {
let win = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
win.loadURL(path.join(__dirname, 'index.html'))
})
preload.js
const { clipboard } = require('electron')
window.addEventListener("message", (event) => {
if (event.source != window) return
if (event.data.type && (event.data.type == "READCLIP_REQ")) {
window.postMessage({ type: "READCLIP_ANS", text: window.readClipboard() }, "*")
}
}, false)
window.readClipboard = function(){
return clipboard.readText()
}
的index.html
<html>
<body>
<p></p>
<p></p>
<script>
// Try window.readClipboard directly (works with no isolation)
document.getElementsByTagName("p")[0].innerText =
window.readClipboard && window.readClipboard()
// Try the same with postMessage
const readClipboardMessage = () => {
window.postMessage({ type: "READCLIP_REQ" }, "*")
}
window.addEventListener("message", (event) => {
if (event.source != window) return
if (event.data.type && (event.data.type == "READCLIP_ANS")) {
document.getElementsByTagName("p")[1].innerText = event.data.text
}
}, false)
readClipboardMessage()
</script>
</body>
</html>