Насколько я вижу, контекстная изоляция предназначена для предотвращения самого описанного вами случая.Поэтому, если вы хотите добавить данные в window
, лучшее, что вы можете сделать, это отключить изоляцию.
Однако я посмотрел документы Сценарии содержимого , указанные в 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'))
})
предварительная загрузка.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>