electron 无法在子窗口中启用远程

fjnneemd  于 2023-02-27  发布在  Electron
关注(0)|答案(1)|浏览(208)

无法在子窗口中启用远程,throws @electron/remote对于此WebContents错误被禁用。调用require(“@electron/remote/main”).enable(webContents)以启用它。代码:main.js:

const {app, BrowserWindow, ipcMain} = require('electron')
const window = require("electron").BrowserWindow;
require('@electron/remote/main').initialize()
.......

renderer.js:

const { ipcRenderer, BrowserWindow} = require('electron');
const remote = require("@electron/remote");
var windows = remote.getCurrentWindow();
btn.onclick = () => {
   const con = new remote.BrowserWindow({
    width: 429,
    height: 781,
    parent: windows,
    autoHideMenuBar: true,
    transparent: true,
    frame: false,
    resizable: false,
    webPreferences: {
        contextIsolation: false,
        nodeIntegration: true,
        enableRemoteModule: true,
        webviewTag: true,
    }
})
require("@electron/remote/main").enable(con.webContents)
con.loadFile("emulator.exe/emulator.html")
}

emulator.exe/emulator.html:

<!DOCTYPE html>
 <html>
   <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
    <link rel="stylesheet" href="mobile.css">
    <title>Emulator</title>
   </head>
   <body>
     <button>collapse window</button>
     <script src="./mobile.js"></script>
   </body>
 </html>

mobile.js:

const { ipcRenderer, BrowserWindow} = require('electron');
const remote = require("@electron/remote");
var windows = remote.getCurrentWindow();
alert(windows)

它会在子窗口中导致此错误

bwitn5fc

bwitn5fc1#

我看了看github,也有同样的错误,原来是有必要通过远程启用:在renderer.js中:

const { ipcRenderer, BrowserWindow} = require('electron');
const remote = require("@electron/remote");
var windows = remote.getCurrentWindow();
btn.onclick = () => {
   const con = new remote.BrowserWindow({
    width: 429,
    height: 781,
    parent: windows,
    autoHideMenuBar: true,
    transparent: true,
    frame: false,
    resizable: false,
    webPreferences: {
        contextIsolation: false,
        nodeIntegration: true,
        enableRemoteModule: true,
        webviewTag: true,
    }
})
//NOT SO:
//require("@electron/remote/main").enable(con.webContents)
//BUT SO:
remote.require("@electron/remote/main").enable(con.webContents)
con.loadFile("emulator.exe/emulator.html")
}

相关问题