Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

Electron: 怎样在BrowserWindow直接加载一个JS文件呢

我想直接用BrowserWindow加载一个js文件(这是一个隐藏窗口,不用开启UI界面),而不是先加载html文件然后在其中声明<script>标记来运行一段脚本,可以实现吗?

BrowserWindow里面有个相关属性preload,就是预加载脚本,但好像不调用window.loadURLwindow.loadFile就不能直接使用:

new BrowserWindow({
      width,
      height,
      show: false,
      center: true,
      minWidth: 800,
      minHeight: 600,
      title: 'electronux',
      autoHideMenuBar: true,
      icon: path.join(app.getAppPath(), 'resources/icon.png'),
      webPreferences: {
        nodeIntegration: true,
        enableRemoteModule: true,
        webviewTag: true,
        preload: 'path/to/my/preload.js'
      },
    }); 

也尝试过直接window.loadURL(dataURL)这种方式实现,但是,以dataURL的方式生成的脚本文件里加载其它外部脚本会出现路径问题:

/**
  * loadView 
  * @param  {[String]} title [标题]
  * @param  {[String]} script [脚本内容]
  * @return {[String]}
  */
 exports.loadView = ({ title, script, childId="" }) => {
  const htmlContent = (`
    <!DOCTYPE html>
    <html>
      <head>
        <title>${title}</title>
        <meta charset="UTF-8">
      </head>
      <script>
        window.childId=${childId}
      </script>
      <body>
        <div id="view"></div>
        <script>
        ${script}
        </script>
      </body>
    </html>
  `);
  
  return 'data:text/html;charset=UTF-8,' + encodeURIComponent(htmlContent);
};

window.loadURL(loadView({...}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

问题解决方法:BrowserService.class

没有使用preload脚本方案,因为感觉不太灵活,不能调试脚本,且创建BrowserWindow时必须覆盖默认preload属性。继承重写了BrowserWindow的部分实例方法和构造函数逻辑,使用了dataURL 脚本注入来加载js文件。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...