gpt4 book ai didi

electron - 在 Electron 中给定上下文隔离的预加载和客户端之间的通信

转载 作者:行者123 更新时间:2023-12-04 20:27:33 27 4
gpt4 key购买 nike

我有一个 Electron 应用程序。我的客户端脚本(渲染器)需要访问 Electron API,但这给了我一个安全警告,所以我将它移到预加载脚本中并禁用了 nodeIntegration。然后我收到了关于 contextIsolation 的警告,所以我启用了它。我的预加载脚本之前将一个函数附加到客户端可以读取的窗口,如下所示:

window.readClipboard = function(){
return clipboard.readText()
}

不幸的是,上下文隔离意味着客户端无法再访问此功能。有没有办法使这个工作与上下文隔离或我应该禁用它?

额外详情

让我尝试打开上下文隔离的警告消息如下:

Electron Deprecation Warning (contextIsolation default change) This window has context isolation disabled by default. In Electron 5.0.0, context isolation will be enabled by default. To prepare for this change, set {contextIsolation: false} in the webPreferences for this window, or ensure that this window does not rely on context isolation being disabled, and set {contextIsolation: true}.



在 client.js 我尝试访问:
console.log("window.readClipboard", window.readClipboard)

有输出:

window.readClipboard undefined

最佳答案

据我所知,上下文隔离旨在防止您描述的情况。所以如果你想添加数据到window您能做的最好的事情就是禁用隔离。

不过,我查了一下Content Scripts BrowserWindow 中提到的文档文档位于 contextIsolation定义并找到使用方法 postMessage获取剪贴板文本。

主文件

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'))
})

预加载.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()
}

索引.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>

关于electron - 在 Electron 中给定上下文隔离的预加载和客户端之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com