SymphonyElectron/js/rendererPreload.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2017-02-14 19:44:15 -06:00
'use strict';
2017-02-10 20:20:09 -06:00
// script run before others and still has access to node integration, even
2017-02-13 18:31:42 -06:00
// when turned off - allows us to leak only what want into window object.
2017-02-10 20:20:09 -06:00
// see: http://electron.atom.io/docs/api/browser-window/
//
// to leak some node module into:
// https://medium.com/@leonli/securing-embedded-external-content-in-electron-node-js-8b6ef665cd8e#.fex4e68p7
// https://slack.engineering/building-hybrid-applications-with-electron-dc67686de5fb#.tp6zz1nrk
//
// also to bring pieces of node.js:
// https://github.com/electron/electron/issues/2984
//
const { ipcRenderer } = require('electron');
// hold ref so doesn't get GC'ed
const local = {
ipcRenderer: ipcRenderer
2017-02-13 18:31:42 -06:00
};
2017-02-10 20:20:09 -06:00
2017-03-01 18:32:21 -06:00
const api = 'symphony-api';
2017-02-14 19:44:15 -06:00
// API exposed by Symphony to renderer processes:
// Note: certain cmds are only allowed on some windows, this is checked by
// main process.
2017-02-13 11:04:16 -06:00
window.SYM_API = {
2017-02-14 19:44:15 -06:00
version: '1.0.0', // api version
// only allowed by main window - enforced by main process.
2017-02-10 20:20:09 -06:00
openWindow: function(url) {
2017-03-01 18:32:21 -06:00
local.ipcRenderer.send(api, {
2017-02-10 20:20:09 -06:00
cmd: 'open',
url: url
});
2017-02-28 16:45:04 -06:00
},
2017-03-01 18:32:21 -06:00
/**
* allows JS to register a logger that can be used by electron main process.
* @param {Object} logger function that can be called accepting
* object: {
* logLevel: 'ERROR'|'CONFLICT'|'WARN'|'ACTION'|'INFO'|'DEBUG',
* logDetails: String
* }
*
* note: only main window is allowed to register a logger, others are
* ignored.
*/
registerLogger: function(logger) {
if (typeof logger === 'function') {
local.logger = logger;
// only main window can register
local.ipcRenderer.send(api, {
cmd: 'registerLogger'
});
}
2017-02-10 20:20:09 -06:00
}
};
2017-03-01 18:32:21 -06:00
// listen for log message from main process
local.ipcRenderer.on('log', (event, arg) => {
console.log('got msg:' + arg)
if (local.logger && arg && arg.level && arg.msg) {
local.logger({
logLevel: arg.level,
logDetails: arg.msg
});
}
});
2017-02-28 16:45:04 -06:00
function updateOnlineStatus() {
2017-03-01 18:32:21 -06:00
local.ipcRenderer.send(api, {
cmd: 'isOnline',
isOnline: navigator.onLine
});
2017-02-28 16:45:04 -06:00
}
window.addEventListener('offline', updateOnlineStatus, false);
window.addEventListener('online', updateOnlineStatus, false);
updateOnlineStatus();
2017-02-13 11:04:16 -06:00
Object.freeze(window.SYM_API);