contextBridge 中的方法在子窗口中不起作用

问题描述 投票:0回答:1

我使用quasar框架进行开发。 在子窗口中,我无法调用 myWindowAPI 的代码,你知道为什么吗?

在 electro-preload.ts 中我有这个

function createWindow() {
  let x, y;
  const currentWindow = BrowserWindow.getFocusedWindow();
  if (currentWindow) {
    const [currentWindowX, currentWindowY] = currentWindow.getPosition();
    x = currentWindowX + 24;
    y = currentWindowY + 24;
  }
  let newWindow: Electron.CrossProcessExports.BrowserWindow | undefined;
  newWindow = new BrowserWindow({
    show: false,
    width: 1000,
    height: 600,
    x,
    y,
    frame: false,
    webPreferences: {
      //nodeIntegration: true,
      contextIsolation: true,
    }
  });
  //newWindow.loadURL(`file://${__dirname}/app.html`);
  newWindow.loadURL(process.env.APP_URL);
  newWindow.webContents.openDevTools();
  newWindow.webContents.on('did-finish-load', () => {
    if (!newWindow) {
      throw new Error('"newWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      newWindow.minimize();
    } else {
      newWindow.show();
      newWindow.focus();
    }
  });
  newWindow.on('closed', () => {
    //windows.delete(newWindow);
    newWindow = undefined;
  });
  /*newWindow.on('focus', () => {
    const menuBuilder = new MenuBuilder(newWindow);
    menuBuilder.buildMenu();
  });*/
  //windows.add(newWindow);
  return newWindow;
}

contextBridge.exposeInMainWorld('myWindowAPI', {

  
  ajouterFenetre () {
    createWindow()
  },

  envoi (data: unknown) {
    //BrowserWindow.getFocusedWindow()?.webContents.send('ping', data)
    console.log('envoi', data)
    ipcRenderer.send('ping', data)
  },

  on: () => {
        // Deliberately strip event as it includes `sender`
        ipcRenderer.on('ping2', (event, data) => {
            console.log('recoi 1', data)
        })
  },

  recoi: (func:(data: unknown) => void) => {
    //if (validChannels.includes(channel)) {
    // Deliberately strip event as it includes `sender`
    return ipcRenderer.on('ping2', (event, data) => {
        console.log('recoi 1', data)
    })
    //ipcRenderer.on('ping', (event, data) => func(data))
    //}
  },

  /*recoi: () => new Promise((res) => {
    ipcRenderer.on('ping', (ev, data) => {
        console.log('recoi 1', data)
      res(data);
    });
  }),*/

  minimize () {
    console.log('minimize2')
    //BrowserWindow.getFocusedWindow()?.minimize()
  },

  toggleMaximize () {
    const win = BrowserWindow.getFocusedWindow()

    if (win?.isMaximized()) {
      win.unmaximize()
    } else {
      win?.maximize()
    }
  },

  close () {
    BrowserWindow.getFocusedWindow()?.close()
  }
})

在主窗口中,方法 myWindowAPI 可以工作,但不能在方法 createWindow 创建的另一个窗口中工作。 我在我的 vue 组件中调用该方法

window.myWindowAPI?.ajouterFenetre()

为什么只能在主窗口中工作?

vue.js electron
1个回答
0
投票

预加载脚本必须附加到窗口才能访问:

new BrowserWindow({
  ...
  webPreferences: {
    preload: path.join(__dirname, 'preload.js')
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.