"Never ask again" feature on Electron dialog.showMessageBox method - javascript

I have a dialog.showMessageBox that works well and do what I tell it to do.
electron.dialog.showMessageBox({
type: 'info',
buttons: ['Yes', 'No'],
message: 'Are you sure?',
}, resp => {
if (resp === 0) {
// User selected 'Yes'
foo.bar();
}
});
But it's annoying to answer each times this function is called, I'd like to insert a "Never ask me again" like this.
electron.dialog.showMessageBox({
type: 'info',
buttons: ['Yes', 'No'],
message: 'Are you sure?',
checkboxLabel: 'Never ask me again',
checkboxChecked: false
}, resp => {
if (resp === 0) {
// User selected 'Yes'
foo.bar();
}
});
The documentation says that the boolean checkboxChecked can be used in the callback function but I'd like to know how to make it global so that the question isn't ask anymore.

Ok so here's what I've done:
const settings = require('electron-settings');
settings.set('neverAskMeAgain', {
state: false
});
if (!settings.get('neverAskMeAgain.state')) {
electron.dialog.showMessageBox({
type: 'info',
buttons: ['Yes', 'No'],
message: 'Are you sure?',
checkboxLabel: 'Never ask me again',
checkboxChecked: false
}, (resp, checkboxChecked) => {
if (resp === 0) {
foo.bar();
settings.set('neverAskMeAgain.state', checkboxChecked);
}
});
} else if (settings.get('neverAskMeAgain.state')) {
foo.bar();
}
} else {
foo.bar();
}
It works like a charm within an instance of the app when running npm install && npm start but when I quit it and relaunch it, the dialog box is displayed again...

I would recommend using a lib named electron-settings. Link here.
That way, your code would look something like that:
const settings = require('electron-settings');
electron.dialog.showMessageBox({
type: 'info',
buttons: ['Yes', 'No'],
message: 'Are you sure?',
checkboxLabel: 'Never ask me again',
checkboxChecked: false
},
resp => {
if (resp === 0) {
// User selected 'Yes'
settings.set('never_ask_again_answer', true);
foo.bar();
}
});
// get the answer later
let answer = settings.get('never_ask_again_answer')
EDIT: I think it doesn't work when you restart because you're just setting it to false again right at the start. Little fix will do:
const settings = require('electron-settings');
if(!settings.has('neverAskMeAgain')){ // this if might do it
settings.set('neverAskMeAgain', {
state: false
});
}
if (!settings.get('neverAskMeAgain.state')) {
electron.dialog.showMessageBox({
type: 'info',
buttons: ['Yes', 'No'],
message: 'Are you sure?',
checkboxLabel: 'Never ask me again',
checkboxChecked: false
}, (resp, checkboxChecked) => {
if (resp === 0) {
foo.bar();
settings.set('neverAskMeAgain.state', checkboxChecked);
}
});
} else if (settings.get('neverAskMeAgain.state')) {
foo.bar();
}

Related

Primeng confirm dialog show when it shouldn't

I have a method that checks if any property of object in array is equal to 'not ready'. If it is it should inform user about that and ask if he still wishes to continue. If no, there is return that breaks the method and if yes, method continues and there is one more confirm dialog
createOrder() {
if(this.orders.filter(e => e.statusName === 'not ready').length > 0){
this.confirmationService.confirm({
message: 'There is already ongoing order. Do you want start another?',
header: 'Order',
icon: 'fa fa-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
key: 'ongoin',
accept: () => {
},
reject: () => {
return
}
})
}
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Order',
icon: 'fa fa-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
key: 'confirm',
accept: () => {
*//add object code*
}
});
This how it looks like in html:
<button pButton tooltipPosition="left" (click)="createOrder()" icon="fa fa-plus-square"
class="ui-button-warning">
</button>
<p-confirmDialog key='ongoin'></p-confirmDialog>
<p-confirmDialog key='confirm'></p-confirmDialog>
My problem is that both confirm dialogs shows up at the same time. I guess it is because of using twice in html. But if i change that to
<p-confirmDialog></p-confirmDialog>
Only the first one works ('There is already ongoin...') and second one('Are you sure') after clicking yes doesn't show up. How do I make it work?
You should be calling the second dialog after the confirmation happens. Which happens in accept or reject callbacks. But you are immediately calling this.confirmationService.confirm again and it is causing both dialogs to be shown.
You should be having something like below :
createOrder() {
if(this.orders.filter(e => e.statusName === 'not ready').length > 0){
this.confirmationService.confirm({
message: 'There is already ongoing order. Do you want start another?',
header: 'Order',
icon: 'fa fa-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
key: 'ongoin',
accept: () => {
// do something here
this.showAnotherDialog();
},
reject: () => {
// if you want to show another dialog on reject you should call it here
return
}
})
} else {
this.showAnotherDialog();
}
}
showAnotherDialog() {
this.confirmationService.confirm({
message: 'Are you sure?',
header: 'Order',
icon: 'fa fa-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
key: 'confirm',
accept: () => {
*//add object code*
}
});
}

showMessageBox promise is never called

The message box appears properly, but when I select one of the buttons, the closure doesn't trigger. Here is my code:
dialog.showMessageBox(options, (response, checkboxChecked) => {
/* More code like log statements, opening error boxes, etc*/
}
Options is defined as choices = ["Yes", "No"], message = "Confirm".
The code inside of the curly braces is never run.
Try:
const options = {
type: 'question',
buttons: ['Cancel', 'Yes, please', 'No, thanks'],
defaultId: 2,
title: 'Question',
message: 'Do you want to do this?',
detail: 'It does not really matter',
checkboxLabel: 'Remember my answer',
checkboxChecked: true,
};
dialog.showMessageBox(null, options, (response, checkboxChecked) => {
console.log(response);
console.log(checkboxChecked);
});

Zebra dialogue js - trying to return a value false or true

I'm trying to return a value from a Zebra_Dialog framework. I need a value like true or false in order to send it as an input so I can update my store card.
The problem is that I'm able to do it with confirm (which return always a value like true or false, but I've no idea about how to do with a javascript framework with that structure.
My code so far was the following:
confirm():
$('#removebuttonstyle i').click(function() {
console.log("you click!");
var c = confirm("Are you sure that you want to continue?");
return c;
});
zebra():
$('#removebuttonstyle i').on('click', function(e) {
console.log("you click!");
e.preventDefault();
var t = $.Zebra_Dialog('<strong>Zebra_Dialog</strong>, a small, compact and highly configurable dialog box plugin for jQuery', {
type: 'question',
title: 'Custom buttons',
buttons: ['Yes', 'No'],
onClose: function(buttons) {
if (buttons=='Yes') {
return true;
} else {
return false;
}
}
});
return buttons;
});
Like you can imagine, the zebra approach doesn't work. Any help? Someone who did that?
Update: I actually made some progress, so the last step is to reassign the value to true or false:
$('#removebuttonstyle i').on('click', function(e) {
console.log("you click!");
e.preventDefault();
var t = $.Zebra_Dialog('<strong>Zebra_Dialog</strong>, a small, compact and highly configurable dialog box plugin for jQuery', {
type: 'question',
title: 'Custom buttons',
buttons: [
{caption: 'Yes'},
{caption: 'No'}
],
onClose: function(caption) {
caption == 'Yes' ? true : false;
console.log(caption);
}
});
});
If I console.log caption I still obtain yes or not, but I need to reassign the value true or false to the variable.
This is my solution:
$('#removebuttonstyle i').on('click', function(e) {
e.preventDefault();
var t = $.Zebra_Dialog('<strong>Zebra_Dialog</strong>, a small, compact and highly configurable dialog box plugin for jQuery', {
type: 'question',
title: 'Custom buttons',
buttons: [
{caption: 'Yes'},
{caption: 'No'}
],
onClose: function(caption) {
if (caption == 'Yes') {
$("#removebuttonstyle i").unbind('click').click()
} else {
caption = false;
}
return caption;
}
});
});

Uncaught (in promise) cancel using SweetAlert2

how do I properly escape the cancel button without throwing an error when using promises? My code throws an alert confirmation with a required checkbox. the code executes as it should to the user, but it throws an error in the console window:
Uncaught (in promise) cancel
//validation logic all passes...Now proceed to...
else
{
//determine and parse Discounts
var myLookup = document.getElementsByName("myLookup")[0].value;
$.post( "findthem.php", {myLookup: myLookup })
.done(function(json_data){
var theResponse1 = $.parseJSON(json_data);
myDiscountRate = theResponse1['ourDiscountFound'];
}).then( function(callback){
priceRate = priceRate * (1 - (.01 * myDiscountRate));
newRate = priceRate.toFixed(2);
}
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to Your new Rate is :'+newRate,
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
return new Promise(function(resolve, reject) {
if (result) {
$.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
resolve();
} else {
reject('You must agree to our Terms & Conditions ');
}
});
},
allowOutsideClick: false
}).then(function(json_data) {
})
});
Update (Jan 2017): This issue has been fixed in v7: v7 upgrade guide ↗
You need to add a rejection handler to the Promise. Alternatively, you can use .catch(swal.noop) as a quick way to simply suppress the errors:
swal('...')
.catch(swal.noop);
PS. the package you're using is called SweetAlert2, not SweetAlert. In future questions please mention it so you can get more relevant answers.
SweetAlert2 rejects the result promise when the cancel button is pressed. You can handle that:
swal({
…
}).then(function(json_data) {
…
}, function(dismiss) {
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
If you don't need to do anything with the json_data, you might also use the catch method.
new Promise(function(resolve, reject) { is not necessary. $.post() returns a jQuery promise object.
Possible solution substitutes Promise.reject() for new Promise() constructor; removed .then() that was placed as an option to first swal() call; pattern appears to expect a Promise to be returned from preConfirm, though not certain what value is expected to be returned from .done() other than json_data.
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to ',
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
if (result) {
return $.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
} else {
return Promise.reject('You must agree to our Terms & Conditions ');
}
},
allowOutsideClick: false
});
you will need to catch the action for cancel
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function(json_data) {
//delete item
}, function(dismiss) {
if (dismiss === 'cancel' || dismiss === 'close') {
// ignore
}
})
Adding catch(swal.noop); at the end swal function will solve this problem
For example:
swal({
}).then(function() {
}).catch(swal.noop);

How do I return true or false using jQuery noty plugin?

I have the following jQuery using the noty plugin and plum shopping cart jQuery. The first block of code correctly alerts a yes / no and empties the cart correctly.
The second block of code shows the yes / no message correctly using noty BUT it does not return the true / false so the cart isnt emptied.
Im really new to jQuery so I'm probably missing something obvious ! Any help would be appreciated:
//This works..
emptycart: function () {
if (!confirm('Are you sure you want to empty your cart?')) {
return false;
}
},
//This doesnt work..
emptycart: function () {
confirm.call(this, noty({
text: 'Are you sure you want to empty the cart ?',
buttons: [
{type: 'button green', text: 'Ok', click: function() { return false; } },
{type: 'button pink', text: 'Cancel', click: function() { return true; } }
],
closable: false,
timeout: false
}),
true
);
return false;
},
Well, the plugin is receiving callbacks, so when you use callbacks you must think in a asynchronous way.
/**
* #param {function} onConfirm : Receives true or false as argument, depending on the user choice
*/
emptycart: function (onConfirm) {
confirm.call(this, noty({
text: 'Are you sure you want to empty the cart ?',
buttons: [
{
type: 'button green',
text: 'Ok',
click: function() {
//Do other stuff if you want...
onConfirm(true);
}
},
{
type: 'button pink',
text: 'Cancel',
click: function() {
//Do other stuff if you want...
onConfirm(false);
}
}
],
closable: false,
timeout: false
}), true);
}
Above, you will send a callbackfunction "onConfirm" which will be called when the user clicks on either buttons. The function will receive one boolean argument telling if was a click on Ok or Cancel.

Categories

Resources