electron/spec/fixtures/api/singleton-data/main.js
Raymond Zhao 746927c972
feat: Add first-instance-ack event to the app.requestSingleInstanceLock() flow (#31460)
* feat: Add onFirstInstanceAck event for requestSingleInstanceLock

* Add tests

* Apply patch fix

* Add back missing docs

* Rebase

* Listen for exit earlier in test

* Rebase
2022-01-10 11:54:46 -05:00

68 lines
1.7 KiB
JavaScript

const { app } = require('electron');
app.whenReady().then(() => {
console.log('started'); // ping parent
});
// Send data from the second instance to the first instance.
const sendAdditionalData = app.commandLine.hasSwitch('send-data');
// Prevent the default behaviour of second-instance, which sends back an empty ack.
const preventDefault = app.commandLine.hasSwitch('prevent-default');
// Send an object back for the ack rather than undefined.
const sendAck = app.commandLine.hasSwitch('send-ack');
let obj = {
level: 1,
testkey: 'testvalue1',
inner: {
level: 2,
testkey: 'testvalue2'
}
};
let ackObj = {
level: 1,
testkey: 'acktestvalue1',
inner: {
level: 2,
testkey: 'acktestvalue2'
}
};
if (app.commandLine.hasSwitch('data-content')) {
obj = JSON.parse(app.commandLine.getSwitchValue('data-content'));
if (obj === 'undefined') {
obj = undefined;
}
}
if (app.commandLine.hasSwitch('ack-content')) {
ackObj = JSON.parse(app.commandLine.getSwitchValue('ack-content'));
if (ackObj === 'undefined') {
ackObj = undefined;
}
}
app.on('first-instance-ack', (event, additionalData) => {
console.log(JSON.stringify(additionalData));
});
const gotTheLock = sendAdditionalData
? app.requestSingleInstanceLock(obj) : app.requestSingleInstanceLock();
app.on('second-instance', (event, args, workingDirectory, data, ackCallback) => {
if (preventDefault) {
event.preventDefault();
}
setImmediate(() => {
console.log([JSON.stringify(args), JSON.stringify(data)].join('||'));
sendAck ? ackCallback(ackObj) : ackCallback();
setImmediate(() => {
app.exit(0);
});
});
});
if (!gotTheLock) {
app.exit(1);
}