Home

How to use preload script in electron

You can use preload.js which will be loaded before other scripts run in the page.

This script will always have access to both electron APIs and node APIs(and also the browser APIs) no matter whether node integration is turned on or off. Using preload.js, you can expose any functionality or APIs by setting an global on window

const path = require('path');

mainWindow = new BrowserWindow({
  width: 300,
  height: 455,
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
  },
});

Here are few examples:

const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
process.once('loaded', () => {
  global.setImmediate = _setImmediate;
  global.clearImmediate = _clearImmediate;
});
const {ipcRenderer, remote, clipboard} = require('electron');

// Expose a custom bridging API to by setting an global on `window`.
// you can also use ipcRenderer here
window.Bridge = {
  copyResult: copyResult,
};

function copyResult() {
  clipboard.writeText(document.querySelector('.result').textContent);
}
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener('DOMContentLoaded', () => {
  const element = document.getElementById('chrome-version');
  if (element) {
    element.innerText = process.versions['chrome'];
  }
});


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments