电子浏览器视图和预加载JavaScript问题

时间:2020-02-11 01:57:54

标签: electron

我已经通过Electron Fiddle尝试了多个版本,但无法使电子浏览器视图与预加载的javascript文件一起使用。我一直关注Electron BrowserView not capturing mouse eventsPreload script not loading in electron@5.0.0 browserview,以及我可以在浏览器视图和预加载的javascript上阅读的其他内容。我能够从浏览器窗口中运行预加载的javascript,但不能从browserview中运行。我尝试了所有的webpreferences选项,并确保路径正确。没有。我的问题是:任何人都可以提供一些已经可以使用的框架代码吗?或者甚至暗示我正在尝试做的事情。这是我使用的一些代码。就像我之前提到的,它可以从浏览器窗口运行,但不能从浏览器视图运行,任何内容都不会输出到控制台。谢谢。

我想让它适用于Electron v8.0.0

main.js

const path = require('path');
const { BrowserView, BrowserWindow, app } = require('electron')

app.on('ready', () => {
  let win = new BrowserWindow({ width: 800, height: 600 });
  win.on('closed', () => { win = null });

  const view = new BrowserView();
  win.setBrowserView(view);
  view.setBounds({ x: 0, y: 0, width: 800, height: 600, 
     webPreferences: { devTools: true, contextIsolation: true, preload: path.join(app.getAppPath(), 'preload.js') } });
  view.webContents.loadURL('https://electronjs.org');
  view.webContents.openDevTools({mode:'undocked'});
});

preload.js

const { webFrame } = require('electron');

webFrame.executeJavaScript('window.foo = "foo";');
window.bar = 'bar';

document.addEventListener('DOMContentLoaded', () => {
 // Will log out 'undefined' since window.foo is only available in the main
 // context
  console.log(window.foo);

  // Will log out 'bar' since window.bar is available in this context
  console.log(window.bar);
});

3 个答案:

答案 0 :(得分:0)

我也花点时间... 我正在使用electron-webpack,上面有以下配置设置(您可能可以使用裸露的webpack和Extraentries实现相同的设置):

"main": {
  "extraEntries": ["@/preload.js"]
}

,以及在创建浏览器视图时:

const view = new BrowserView({
  webPreferences: {
    preload: path.resolve(__dirname, 'preload.js'),
    #some other options
}})

preload脚本位于主流程的所有源代码中(无论您为它配置了什么)

答案 1 :(得分:0)

您必须将预加载文件放在静态文件夹中,然后这样调用 file:${require('path').resolve(__static, './preload.js')} 为我工作...。 但是预加载文件不会在多浏览器视图或 webview在第一帧仅运行一次,也许是一些错误.....非常可悲的行为

答案 2 :(得分:0)

const view = new BrowserView({
  webPreferences: { 
    devTools: true, 
    contextIsolation: true, 
    preload: path.join(app.getAppPath(), 'preload.js') 
  }
});
win.setBrowserView(view);
view.setBounds({ x: 0, y: 0, width: 800, height: 600 });

webPreferences应该在BrowserView的选择子中