Safari JavaScript prompt() cancel

The method to detect when a user click on cancel in a prompt window doesn't work in safari (and only safari). It returns an empty string instead of null.


The following code works but it won't make the difference between a user who cancel and a user who send an empty string !

Code:

var text = prompt('message','')

if (text != null && text.trim() != '') { // ?

console.log(text)

} else {

console.log('No text')

}


Do you know a simple method to detect when a user click on cancel ?


P.S: I'm french so please don't use complicate word

Safari-OTHER, OS X El Capitan (10.11.5), null

Posted on Jun 16, 2016 5:31 AM

Reply
3 replies

Jun 16, 2016 8:56 AM in response to ETN's

If the user clicks on cancel, the returned value will be Null, if they submit an empty string it will be empty.


So basically, instead of checking for both things at the same time, check for one first and then the other.


Si l'utilisateur clique sur annuler, la valeur retournée sera Null, si elles présentent une chaîne vide, il sera vide.

Donc, fondamentalement, au lieu de vérifier pour les deux choses en même temps, vérifier l'un d'entre eux d'abord, puis l'autre.



if(text==null)

{

console.log('User clicked on Cancel');

}

else if(text==''){

console.log("User did not type anything, but clicked on o.k.");

}

else{

console.log("User typed: " + text);

}

Jun 16, 2016 12:15 PM in response to ETN's

Safari on iOS works as expected.


Safari on Mac does in fact return an empty string if you click on cancel, regardless of what may be in the textbox.


So the only way I can think of to determine this, is to have a default piece of text in the prompt before hand to check against. Clicking on Cancel will not return that text, clicking on o.k. without altering it will.


Unfortunately, there is not much to be done, since the return value has been changed at the Browser level.


You can send Apple feedback about this:

http://www.apple.com/feedback/safari.html


.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Safari JavaScript prompt() cancel

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.