electron#dialog JavaScript Examples
The following examples show how to use
electron#dialog.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: application.js From razer-macos with GNU General Public License v2.0 | 6 votes |
constructor(isDevelopment) {
this.isDevelopment = isDevelopment;
this.forceQuit = false;
this.tray = null;
this.browserWindow = null;
this.app = app;
this.dialog = dialog;
this.APP_VERSION = version;
this.initListeners();
// Init the main application
this.razerApplication = new RazerApplication();
}
Example #2
Source File: eve-dialog.js From EveReader with GNU Affero General Public License v3.0 | 6 votes |
askOpenFile() {
let win = this.eveApp.getFocusedWindow();
dialog
.showOpenDialog(win, {
properties: ["openFile"],
filters: [
{
name: "Epub",
extensions: ["epub"],
},
],
})
.then((result) => {
if (!result.canceled) {
let epubPath = result.filePaths[0];
win.openFileFromDialog(epubPath);
} else {
console.log("no file selected");
}
});
}
Example #3
Source File: updater.js From linked with GNU General Public License v3.0 | 6 votes |
autoUpdater.on('update-available', async (updateInfo) => {
const { response } = await dialog.showMessageBox({
title: 'Update available',
message: `Version ${updateInfo.version} is available, would you like to update now?`,
detail: 'The app will download the update and restart once finished.',
type: 'question',
buttons: ['Remind me later', 'Install'],
defaultId: 1,
noLink: true
})
if (response === 1) {
global.storage.set('updateInterval', DAILY)
await autoUpdater.downloadUpdate()
} else {
global.storage.set('updateInterval', WEEKLY)
}
})
Example #4
Source File: electron-main.js From follow with GNU General Public License v3.0 | 6 votes |
async function main() {
try {
await app.whenReady();
} catch (e) {
dialog.showErrorBox("Electron could not start", e.stack);
app.exit(1);
}
try {
// await setupAnalytics(ctx); // ctx.countlyDeviceId
await setupI18n(ctx);
await setupAppMenu(ctx);
// await setupWebUI(ctx) // ctx.webui, launchWebUI
await setupTray(ctx); // ctx.tray
await setupDaemon(ctx); // ctx.getIpfsd, startIpfs, stopIpfs, restartIpfs
// await setupAutoUpdater(ctx); // ctx.checkForUpdates
await Promise.all([
// setupArgvFilesHandler(ctx),
setupAutoLaunch(ctx),
setupAutoGc(ctx),
setupPubsub(ctx),
setupNamesysPubsub(ctx),
// Setup global shortcuts
setupDownloadCid(ctx),
// setupIpfsOnPath(ctx)
]);
// // Setup identity
await setupIdentity(ctx);
// open electron
await createWindow(ctx);
// // Setup pubsub
// await setupOrbit(ctx);
} catch (e) {
handleError(e);
}
}
Example #5
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
showUpdateDialog = version => {
info(`New version available: ${version}`);
const clickedButton = dialog.showMessageBoxSync(null, {
type: "warning",
buttons: ["View update", "Remind me later"],
defaultId: 0,
title: "VPN.ht - Update available",
message: `Do you want to install the new version ${version}?`
});
if (clickedButton === 0) {
shell.openExternal(
`https://github.com/${repository}/releases/tag/v${version}`
);
}
if (clickedButton === 1) {
// just ignore and continue
return;
}
}
Example #6
Source File: update-checker.js From desktop with GNU General Public License v3.0 | 6 votes |
urgentUpdateAvailable = (latestVersion) => {
const choice = dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {
title: APP_NAME,
type: 'warning',
buttons: [
getTranslation('updater.download'),
getTranslation('updater.later')
],
cancelId: 1,
message: getTranslation('updater.security.message').replace('{version}', latestVersion),
detail: getTranslation('updater.security.detail')
});
if (choice === 0) {
shell.openExternal(getUpdateURL(version, latestVersion));
}
}
Example #7
Source File: update-checker.js From desktop with GNU General Public License v3.0 | 6 votes |
updateAvailable = async (latestVersion) => {
const ignoredUpdate = get(IGNORE_UPDATE_KEY);
if (ignoredUpdate !== null && ignoredUpdate === latestVersion) {
log('not showing update message: ignored by user');
return;
}
const choice = await dialog.showMessageBox(BrowserWindow.getFocusedWindow(), {
title: APP_NAME,
type: 'info',
buttons: [
getTranslation('updater.download'),
getTranslation('updater.later')
],
cancelId: 1,
message: getTranslation('updater.message').replace('{version}', latestVersion),
detail: getTranslation('updater.detail'),
checkboxLabel: getTranslation('updater.ignore'),
checkboxChecked: false
});
if (choice.response === 0) {
shell.openExternal(getUpdateURL(version, latestVersion));
} else if (choice.checkboxChecked) {
set(IGNORE_UPDATE_KEY, latestVersion);
}
}
Example #8
Source File: permissions.js From desktop with GNU General Public License v3.0 | 6 votes |
showPermissionDeniedWarning = (window, mediaType) => {
const title = getTranslation(`permission.${mediaType}-denied`);
const description = getTranslation(`permission.${mediaType}-denied-description`);
// This prompt currently is only visible in macOS
const instructions = getTranslation('permission.macos-instructions');
dialog.showMessageBox(window, {
type: 'warning',
message: title,
detail: `${description}\n\n${instructions}`
});
}
Example #9
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
ipcMain.on('confirm', (event, message) => {
const result = dialog.showMessageBoxSync(BrowserWindow.fromWebContents(event.sender), {
title: APP_NAME,
message: '' + message,
buttons: [
getTranslation('prompt.ok'),
getTranslation('prompt.cancel')
],
defaultId: 0,
cancelId: 1,
noLink: true
}) === 0;
event.returnValue = result;
});
Example #10
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
ipcMain.on('alert', (event, message) => {
dialog.showMessageBoxSync(BrowserWindow.fromWebContents(event.sender), {
title: APP_NAME,
message: '' + message,
buttons: [
getTranslation('prompt.ok')
],
noLink: true
});
// set returnValue to something to reply so the renderer can resume
event.returnValue = 1;
});
Example #11
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
ipcMain.on('export-addon-settings', async (event, settings) => {
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), {
defaultPath: 'turbowarp-addon-setting.json',
filters: [
{
name: 'JSON',
extensions: ['json']
}
]
});
if (result.canceled) {
return;
}
const path = result.filePath;
await writeFile(path, JSON.stringify(settings));
});
Example #12
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
ipcMain.on('open-packager-legacy', async (e) => {
const window = BrowserWindow.fromWebContents(e.sender);
await dialog.showMessageBox(window, {
title: APP_NAME,
message: getTranslation('packager-moved.title'),
detail: getTranslation('packager-moved.details')
});
createPackagerWindow(e.sender);
});
Example #13
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
ipcMain.handle('show-open-dialog', async (event, options) => {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
filters: options.filters,
properties: ['openFile'],
defaultPath: getLastAccessedDirectory()
});
if (!result.canceled) {
const [filePath] = result.filePaths;
setLastAccessedFile(filePath);
allowedToAccessFiles.add(filePath);
}
return result;
});
Example #14
Source File: index.js From desktop with GNU General Public License v3.0 | 6 votes |
ipcMain.handle('show-save-dialog', async (event, options) => {
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), {
filters: options.filters,
defaultPath: pathUtil.join(getLastAccessedDirectory(), options.suggestedName)
});
if (!result.canceled) {
const {filePath} = result;
setLastAccessedFile(filePath);
allowedToAccessFiles.add(filePath);
}
return result;
});
Example #15
Source File: crash.js From desktop with GNU General Public License v3.0 | 6 votes |
showCrashMessage = (window, type, code, reason) => {
dialog.showMessageBoxSync(window, {
type: 'error',
title: APP_NAME,
message: getTranslation('crash.title'),
detail: getTranslation('crash.description')
.replace('{type}', type)
.replace('{code}', code)
.replace('{reason}', reason)
});
}
Example #16
Source File: index.js From clipcc-desktop with GNU Affero General Public License v3.0 | 6 votes |
ipcMain.on('open-extension-store', () => {
if (!net.isOnline()) {
return dialog.showMessageBoxSync(_windows.main, {
message: 'You need to be connected to the Internet to use the extension store.',
type: 'info'
});
}
_windows.extensionStore.loadURL('https://codingclip.com/extension/?desktop=1');
_windows.extensionStore.show();
});
Example #17
Source File: index.js From clipcc-desktop with GNU Affero General Public License v3.0 | 6 votes |
ipcMain.handle('write-file', async (event, file, content) => {
try {
await fs.writeFile(file, content);
} catch (e) {
await dialog.showMessageBox(_windows.main, {
type: 'error',
message: `Cannot write file:\n${file}`,
detail: e.message
});
}
});
Example #18
Source File: index.js From clipcc-desktop with GNU Affero General Public License v3.0 | 6 votes |
initialProjectDataPromise = (async () => {
if (argv._.length === 0) {
// no command line argument means no initial project data
return;
}
if (argv._.length > 1) {
log.warn(`Expected 1 command line argument but received ${argv._.length}.`);
}
const projectPath = argv._[argv._.length - 1];
try {
const projectData = await promisify(fs.readFile)(projectPath, null);
return projectData;
} catch (e) {
dialog.showMessageBox(_windows.main, {
type: 'error',
title: 'Failed to load project',
message: `Could not load project from file:\n${projectPath}`,
detail: e.message
});
}
// load failed: initial project data undefined
})()
Example #19
Source File: index.js From clipcc-desktop with GNU Affero General Public License v3.0 | 6 votes |
displayPermissionDeniedWarning = (browserWindow, permissionType) => {
let title;
let message;
switch (permissionType) {
case 'camera':
title = 'Camera Permission Denied';
message = 'Permission to use the camera has been denied. ' +
'Scratch will not be able to take a photo or use video sensing blocks.';
break;
case 'microphone':
title = 'Microphone Permission Denied';
message = 'Permission to use the microphone has been denied. ' +
'Scratch will not be able to record sounds or detect loudness.';
break;
default: // shouldn't ever happen...
title = 'Permission Denied';
message = 'A permission has been denied.';
}
let instructions;
switch (process.platform) {
case 'darwin':
instructions = 'To change Scratch permissions, please check "Security & Privacy" in System Preferences.';
break;
default:
instructions = 'To change Scratch permissions, please check your system settings and restart Scratch.';
break;
}
message = `${message}\n\n${instructions}`;
dialog.showMessageBox(browserWindow, {type: 'warning', title, message});
}
Example #20
Source File: fileHandler.js From melvor-mod-manager with MIT License | 6 votes |
handlers = {
[file.openScript]: async () => {
// Open .js or .json and parse manifest
const res = await dialog.showOpenDialog({
properties: ['openFile'],
filters: [
{ name: 'Userscript or extension manifest', extensions: ['js', 'json'] }
]
});
return res.canceled ? null : res.filePaths[0];
},
[file.openDir]: async () => {
// Prompt directory and return path
const res = await dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'] });
const dir = res.canceled ? null : res.filePaths[0];
return dir;
},
[file.validateMelvorDir]: async ({ dir }) => {
// Validate the executable exists in dir
const melvorPath = path.join(dir, getExecutableFilename(process.platform));
try {
await access(melvorPath);
return true;
} catch {
return false;
}
}
}
Example #21
Source File: settings.js From brisque-2.0-desktop with MIT License | 5 votes |
constructor(brisque, type, name = type.substring(0, 1).toUpperCase() + type.substring(1).toLowerCase()) {
super({
filename: path.resolve(app.getPath('userData'), 'Settings', type)
})
this.promised = promisify(Datastore.prototype)
this.brisque = brisque
this.type = type
this.name = name
super.loadDatabase(err => {
if (err) {
return dialog.showMessageBox(
{
type: 'error',
title: `${name} Load Failure`,
message: `There was a problem loading your ${type}. Try restarting Brisque, and contact us on Discord if the problem persists.${
err ? `\n\n${err}` : ''
}`,
buttons: ['Close Brisque']
},
() => app.quit()
)
}
this.persistence.setAutocompactionInterval(15000)
});
['find', 'findOne', 'count'].forEach(property =>
Object.defineProperty(this, property, {
value: (...args) => this.promised[property].apply(this, args)
})
);
['update', 'insert', 'remove'].forEach(property =>
Object.defineProperty(this, property, {
value: (...args) => this.promised[property].apply(this, args).then(doc => {
this.latestUpdate = Date.now()
return doc
})
})
)
ipc.on('store.subscribe', async (evt) => {
const { windowManager: { window } } = this.brisque
if (window.webContents.id !== evt.sender.id) {
return
}
const update = async () => {
if (!window) {
return
}
if (this.latestUpdate && (this.lastUpdate || 0) < this.latestUpdate && window) {
window.webContents.send('store.update', {
type,
data: type === 'account' ? await this.findOne({}) : await this.find({})
})
this.lastUpdate = Date.now()
}
if (timeoutId !== null) {
timeoutId = setTimeout(update, 50)
}
}
let timeoutId = setTimeout(update, 50)
evt.sender.once('closed', () => {
clearTimeout(timeoutId)
timeoutId = null
this.subscription = null
})
evt.sender.send('store.update', {
type,
data: type === 'account' ? await this.findOne({}) : await this.find({})
})
})
}
Example #22
Source File: index.js From desktop with GNU General Public License v3.0 | 5 votes |
createEditorWindow = () => {
// Note: the route for this must be `editor`, otherwise the dev tools keyboard shortcuts will not work.
let url = getURL('editor');
const fileToOpen = filesToOpen.shift();
if (typeof fileToOpen !== 'undefined') {
url += `&file=${encodeURIComponent(fileToOpen)}`;
allowedToAccessFiles.add(fileToOpen);
}
const window = createWindow(url, {
title: APP_NAME,
width: 1280,
height: 800
});
window.on('page-title-updated', (event, title, explicitSet) => {
event.preventDefault();
if (explicitSet && title) {
window.setTitle(`${title} - ${APP_NAME}`);
} else {
window.setTitle(APP_NAME);
}
});
window.on('closed', () => {
editorWindows.delete(window);
if (editorWindows.size === 0) {
closeAllNonEditorWindows();
}
});
window.webContents.on('will-prevent-unload', (e) => {
const choice = dialog.showMessageBoxSync(window, {
title: APP_NAME,
type: 'info',
buttons: [
getTranslation('unload.stay'),
getTranslation('unload.leave')
],
cancelId: 0,
defaultId: 0,
message: getTranslation('unload.message'),
detail: getTranslation('unload.detail')
});
if (choice === 1) {
e.preventDefault();
}
});
editorWindows.add(window);
return window;
}
Example #23
Source File: application.js From razer-macos with GNU General Public License v2.0 | 5 votes |
showConfirm(message) {
this.app.focus();
return this.dialog.showMessageBox({
buttons: ['Yes', 'No'], message: message,
});
}
Example #24
Source File: AlfwCommon.js From ntfstool with MIT License | 5 votes |
/**
* checkUpdate
*/
export function checkUpdate() {
var cur_version = process.env.NODE_ENV === 'development' ? process.env.npm_package_version : app.getVersion()
// console.warn(this.$http,"this.$http")
try {
get('https://ntfstool.com/version.json').asString(function (err, ret) {
if (err) {
saveLog.error("get api update version.json error",err);
return;
}
var data = {
"version": "",
"url": "https://ntfstool.com/",
"title": "New Version Found",
"detail": "update"
};
try {
var getData = JSON.parse(ret);
if (!getData || typeof getData.version == "undefined" || !getData.version) {
saveLog.error("not found version!")
return;
}
if (typeof getData.version != "undefined") {
data.version = getData.version;
}
if (typeof getData.url != "undefined") {
data.url = getData.url;
}
if (typeof getData.title != "undefined") {
data.title = getData.title;
}
if (typeof getData.detail != "undefined") {
data.detail = getData.detail;
}
} catch (e) {
saveLog.warn("check version format error!",e)
}
if (typeof data.version != "undefined" && data.version) {
saveLog.warn({
cur_version: cur_version,
check_version: data.version
})
if (cur_version != data.version && versionStringCompare(cur_version,data.version) < 0) {
const dialogOpts = {
type: 'info',
buttons: ['Cancel', "OK"],
title: 'Application Update',
message: data.title + "("+cur_version+"->"+data.version+")",
detail: data.detail
}
dialog.showMessageBox(dialogOpts).then((diaret) => {
if (typeof diaret.response != "undefined" && diaret.response == 1) {
shell.openExternal(data.url);
}
});
}
} else {
saveLog.warn("check version format error!")
}
});
} catch (e) {
saveLog.error("get update error!", e);
}
}
Example #25
Source File: AlfwCommon.js From ntfstool with MIT License | 5 votes |
/**
* notice the system error
* @param _error
* @param setOption
*/
export function noticeTheSystemError(_error, setOption) {
var errorMap = {
system: 10000,
dialog: 10010,
dialog_save_err: 10011,
savePassword: 10020,
savePassword2: 10021,
getSudoPwdError: 10031,
checkSudoPasswordError: 10041,
opendevmod: 10030,
FEEDBACK_ERROR: 10040,
UNCLEANERROR:10050
};
var error = (typeof _error != "undefined") ? _error : "system";
console.warn(error, "error")
var errorNo = (typeof errorMap[error] != "undefined") ? errorMap[error] : 1000;
var option = {
title: "System Error: " + errorNo,
body: "please contact official technical support",
href: 'https://www.ntfstool.com'
};
if (typeof setOption == "object") {
option = setOption;
}
if (typeof setOption == "string") {
option.body = setOption;
}
saveLog.error({name: _error, text: JSON.stringify(option)}, "noticeTheSystemError");
new window.Notification(option.title, option).onclick = function () {
shell.openExternal(option.href)
}
}
Example #26
Source File: index.js From NIM-Pools-Hub-Miner with GNU General Public License v3.0 | 5 votes |
function createWindow() {
/**
* Initial window options
*/
mainWindow = new BrowserWindow({
height: 560,
width: process.env.NODE_ENV === "development" ? 1090 : 660,
center: true,
resizable: false,
fullscreenable: false,
frame: false,
transparent: true,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
experimentalFeatures: true,
},
});
if (process.env.NODE_ENV !== "development") mainWindow.removeMenu();
log("Detecting UV_THREADPOOL_SIZE: " + process.env.UV_THREADPOOL_SIZE);
if (!process.env.UV_THREADPOOL_SIZE) {
process.env.UV_THREADPOOL_SIZE = 128;
if (process.platform === "win32") {
const Shell = require("node-powershell");
let ps = new Shell({
executionPolicy: "Bypass",
noProfile: true,
});
const command =
"[Environment]::SetEnvironmentVariable('UV_THREADPOOL_SIZE', 128, 'User')";
ps.addCommand(command);
ps.invoke()
.then((output) => {
dialog.showMessageBox({
type: "info",
message:
"First time setup completed. NIM Pools Hub Miner will now restart.",
});
app.relaunch();
app.quit();
})
.catch((err) => {
console.log(err);
ps.dispose();
});
}
} else {
log(`Detected ${process.env.UV_THREADPOOL_SIZE} threadpool size`);
}
log("Nimiq initialization");
Nimiq.GenesisConfig.main();
store.dispatch("setAppVersion", app.getVersion());
store.dispatch("setCpuHashrate", null);
store.dispatch("setGpuHashrate", null);
store.dispatch("setMiningCPU", false);
store.dispatch("setMiningGPU", false);
mainWindow.loadURL(winURL);
mainWindow.on("closed", () => {
mainWindow = null;
});
}
Example #27
Source File: background.js From linked with GNU General Public License v3.0 | 5 votes |
ipcMain.handle('SET_DATA_PATH', async () => {
const currentPath = global.storage.get('dataPath')
const result = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory']
})
if (result.canceled === true) {
new Notification({
title: 'Action aborted',
body: 'Your previous settings still apply.'
}).show()
return currentPath
}
const newPath = result.filePaths.length > 0
? result.filePaths[0]
: basePath
searchIndex = new Document({
document: {
id: 'date',
index: ['content'],
store: true
},
tokenize: global.storage.get('searchMode')
})
if ((await fs.promises.readdir(newPath)).length !== 0) {
await dialog.showMessageBox(win, {
message: 'Directory not empty!',
detail: `${newPath} is not empty, please choose another directory or add an empty directory at the desired location first.`,
type: 'error',
buttons: ['Close'],
defaultId: 1,
noLink: true
})
return global.storage.get('dataPath')
}
const fsEx = require('fs-extra')
try {
await fsEx.move(currentPath, newPath, { overwrite: true })
} catch (e) {
await dialog.showMessageBox(win, {
message: 'An error occured!',
detail: e.toString(),
type: 'error',
buttons: ['Close'],
defaultId: 1,
noLink: true
})
return global.storage.get('dataPath')
}
global.storage.set('dataPath', newPath)
await repairSearchDatabase()
new Notification({
title: 'Successfully set new path!',
body: `Your data now is being read from ${newPath}.`
}).show()
return global.storage.get('dataPath')
})
Example #28
Source File: http-bridge.js From loa-details with GNU General Public License v3.0 | 5 votes |
function spawnPacketCapturer(appSettings, serverPort) {
const args = ["--Port", serverPort];
if (appSettings?.general?.customLogPath !== null)
args.push("--CustomLogPath", appSettings?.general?.customLogPath);
if (appSettings?.general?.useWinpcap) args.push("--UseNpcap");
if (appSettings?.general?.server === "russia")
args.push("--Region", "Russia");
else if (appSettings?.general?.server === "korea")
args.push("--Region", "Korea");
try {
let binaryFolder;
if (process.env.DEBUGGING) {
binaryFolder = path.resolve(__dirname, "../../binary/");
} else {
binaryFolder = path.resolve("./binary/");
}
const binaryFiles = fs.readdirSync(binaryFolder);
for (const binaryFile of binaryFiles) {
if (binaryFile.endsWith(".exe")) {
packetCapturerProcess = spawn(
path.resolve(binaryFolder, binaryFile),
args
);
break;
}
}
log.info("Started Logger!");
} catch (e) {
log.error("Error while trying to open packet capturer: " + e);
dialog.showErrorBox(
"Error while trying to open packet capturer",
"Error: " + e.message
);
log.info("Exiting app...");
app.exit();
}
packetCapturerProcess.on("exit", function (code, signal) {
log.error(
`The connection to the Lost Ark Packet Capture was lost for some reason:\n
Code: ${code} and Signal: ${signal}`
);
dialog.showErrorBox(
"Error",
`The connection to the Lost Ark Packet Capture was lost for some reason:\n
Code: ${code} and Signal: ${signal}\n
Exiting app...`
);
log.info("Exiting app...");
app.exit();
});
}
Example #29
Source File: index.js From desktop with GNU General Public License v3.0 | 5 votes |
showUpdateDialogNoVersion = () => {
dialog.showMessageBoxSync(null, {
type: "warning",
buttons: ["Ok"],
title: "VPN.ht",
message: "No updates available."
});
}