Skip to content

Instantly share code, notes, and snippets.

@wearhere
Last active January 13, 2018 22:09
Show Gist options
  • Save wearhere/39995af125bdcd0f50ba to your computer and use it in GitHub Desktop.
Save wearhere/39995af125bdcd0f50ba to your computer and use it in GitHub Desktop.
Using a preload script to safely expose select Node APIs to remote web content. See https://mixmax.com/blog/turnkey-electron-apps-with-meteor#safe-native-bridge for more information.
// Local variables will not escape the preload script.
var shell = require('electron').shell;
// Global variables _will_ escape the preload script, except for globals injected by Node,
// like `require`—-those will be deleted after the script is done executing.
Electron = {
openExternal: function(url) {
shell.openExternal(url);
}
// Notice we don’t save `shell` as a property of `Electron`! Then it’d be available
// to the webpage.
};
<script>
// Successfully uses the `shell` module as prescribed by the preload script.
Electron.openExternal('https://mixmax.com/download');
// Logs "Uncaught ReferenceError: shell is not defined(…)"
shell.moveItemToTrash('~/Documents');
// (Ignoring previous line) Logs "Uncaught ReferenceError: require is not defined(…)"
require('electron').shell.moveItemToTrash('~/Documents');
</script>
@jlukic
Copy link

jlukic commented Jan 12, 2016

nice

@skeggse
Copy link

skeggse commented Jun 28, 2016

// Global variables _will_ escape the preload script, except for globals injected by Node,
// like `require`—-those will be deleted after the script is done executing.

Note that require is actually a local in Node, though it does have globals like process.

@CodingCentral
Copy link

skeggse: By global, do you mean an equivalent that works in browsers?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment