Show messages based on Severity in two p:growl - primefaces

I'm using PrimeFaces p:growl.
<p:growl id="msgsInfo"
rendered="true"
showDetail="true" />
<p:growl id="msgsError"
globalOnly="true"
showDetail="true"
sticky="true" />
I need to show in the first growl only Info messages while in the second I need to show Error messages.
Using globalOnly when I add error message this is show 2 times.
Any idea?

It would in theory be possible if it supported infoClass, errorClass, etc attributes like as h:messages. You could then just specify a CSS class which does a display: none.
But the p:growl doesn't support those attributes. On the severity level all you can do is changing the icon by infoIcon, errorIcon, etc. So you're pretty lost here.
It might be worth a feature request.
Note that the globalOnly="true" only displays messages which have a null client ID, regardless of their severity.

Please see my answer
PrimeFaces growl change color dynamically (Multiple messages)
You can also find the source code of the project which produces the page below:

I was looking for the same functionality (to set the growl to sticky from a specific message severity). PrimeFaces (6.1) doesn't offer this functionality, but it is quite easy to hack the growl JavaScript. More specifically, in the bindEvents function they check if sticky was configured and based on that:
//hide the message after given time if not sticky
if(!sticky) {
this.setRemovalTimeout(message);
}
So, you could prototype (override) the bindEvents function and set sticky based on the message severity.
PrimeFaces.widget.Growl.prototype.bindEvents = function(message) {
var _self = this,
sticky = this.cfg.sticky;
// Start hack
if (!sticky) {
// Your rule
}
...
You could also prototype renderMessage and add severity as a parameter to bindEvents. I chose to used a quick hack and read it from the className.
I've added these utility functions:
var SEVERITIES = [ "info", "warn", "error", "fatal" ];
function getSeverity(domNode) {
// HACK Severity can be found in the className after the last - character.
var severity = domNode.className;
return severity.substring(severity.lastIndexOf("-") + 1);
}
function getSeverityIndex(severityString) {
return SEVERITIES.indexOf(severityString);
}
Now you can use the following check:
if (!sticky) {
sticky = getSeverityIndex(getSeverity(message[0])) >= getSeverityIndex("error");
}
I might create a pull request at GitHub where you can set the minimum severity to stick massages using the stickSeverity attribute on the p:growl component.
Here is the full JavaScript hack (PrimeFaces 6.1):
var SEVERITIES = [ "info", "warn", "error", "fatal" ];
function getSeverity(domNode) {
// HACK Severity can be found in the className after the last - character.
var severity = domNode.className;
return severity.substring(severity.lastIndexOf("-") + 1);
}
function getSeverityIndex(severityString) {
return SEVERITIES.indexOf(severityString);
}
PrimeFaces.widget.Growl.prototype.bindEvents = function(message) {
var _self = this,
sticky = this.cfg.sticky;
// Start customization
if (!sticky) {
sticky = getSeverityIndex(getSeverity(message[0])) >= getSeverityIndex("error");
}
// End customization
message.mouseover(function() {
var msg = $(this);
//visuals
if(!msg.is(':animated')) {
msg.find('div.ui-growl-icon-close:first').show();
}
})
.mouseout(function() {
//visuals
$(this).find('div.ui-growl-icon-close:first').hide();
});
//remove message on click of close icon
message.find('div.ui-growl-icon-close').click(function() {
_self.removeMessage(message);
//clear timeout if removed manually
if(!sticky) {
clearTimeout(message.data('timeout'));
}
});
//hide the message after given time if not sticky
if(!sticky) {
this.setRemovalTimeout(message);
}
}

Related

Adding properties for a Polymer element to observe based on content or a better way to handle forms

I need to create a form using the Polymer Paper-Input elements, and I need a way to know when all required content has been filled out.
I looked for a built in element, but didn't see one. So I wanted to create a polymer form element that would wrap all of the input tags. The resulting element would have an Invalid attribute which lets you know if any of the input tags are invalid.
The use of the tag would look like this:
<test-form id="testform">
<paper-input label="test" required error="This field is required"></paper-input>
</test-form>
Invalid: {{ $.testform.invalid }}
However, it appears that by the time in the elements lifecycle that I can loop over all the elements inside of the content tag, that anything added to the observe object is ignored.
Here is the code I was working on below:
<polymer-element name="test-form" attributes="invalid">
<template>
<content id="content">
</content>
</template>
<script>
Polymer('test-form', {
domReady: function () {
this.observe = {};
for (var i = 0; i < this.children.length; i++) {
this.observe["this.children[" + i + "].invalid"] = "valChanged";
}
},
invalid: false,
valChanged: function (oldValue, newValue) {
// TODO: If newValue is true set invalid to true
// If newValue is false, loop over all elements to see if all are now valid and invalid can be set to false.
alert("VALUE CHANGED" + oldValue + newValue);
}
});
</script>
Is there a better way to handle this or does anyone know how to make changes to what polymer is observing at this point in the lifecycle?
As far as checking the form's validity, you could simply check each form element's invalid property:
validate: function() {
var invalid = false;
Array.prototype.forEach.call(this.children, function(child) {
if (child.invalid === true) {
invalid = true;
}
});
this.invalid = invalid;
}
Then you could add an input event listener and run this method each time a form element's input changes.
Here's a working jsbin.
If I understand your question, your high level goal is form validation?
As has been detailed in polycasts and other places, I have used iron-form which has some very powerful validate() functionality, including what you mention above and much more.
It does sometimes require some odd usages of hidden <input> fields to get all of the work done, but this is easy to learn in the polycasts, such as polycast 55 and 56
If you stumbled upon this question in 2017, you would definitely now want to use more primitive tech, after you've seen what this has to offer.

Prevent chrome.notifications API from hiding my notification after a few seconds

I'm doing around 1-2 notifications a day and it's important the user doesn't miss it. Is there a way of removing the auto close and only allowing the user to manually close the notification?
I don's see any option for this in the Notification Options:
http://developer.chrome.com/extensions/notifications.html#type-NotificationOptions
Notification now has (since Chrome 50) a requireInteraction property to force the notification to stay on screen:
var notification = new Notification("TITLE", {
icon: 'assets/res/icon.png',
body: "MESSAGE",
requireInteraction: true
});
In onclick you have to close the notification:
notification.onclick = function()
{
this.close();
}
UPDATE (2016-05-24):
Xan commented:
Fun fact: all this arcane hacking is no longer needed; see the new requireInteraction flag
It is availalbe since Chrome 50. More info.
Thanks to root's comment, this answer is revised to account for the fact that the onClosed event is not fired when the notification disappears (into the notigications area) after a few seconds. This is still kind of a hacky solution.
Background
You can take advantage of the fact that a notification's life-cycle ends with one of the following events:
onClosed: When the user clicks on the small 'x' in the top-right corner.
onClicked: When the user clicks on the message body (not the 'x', not some button).
onButtonClicked: When the user clicks on one of the buttons (if any).
The solution
The proposed solution consists of the following steps:
Register listeners for all the events mentioned above.
Register a timeout after a few seconds (e.g. 30) -after the notification is hidden- that will delete and re-create the notification (so it effectively stays visible on the screen.
If any of the listeners set on step 1 fires, it means the user interracted with the notification, so cancel the timeout (you don't need to re-create the notification).
Writing about it is simple, coding takes some more effort :)
Here is the sample code I used to achieve what is described above:
In manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
// We need this for the `Timeout` - see notes below
"persistent": true,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Test Extension"
"default_icon": {
"19": "img/icon19.png",
"38": "img/icon38.png"
},
},
"permissions": ["notifications"]
}
In background.js:
var pendingNotifications = {};
/* For demonstration purposes, the notification creation
* is attached to the browser-action's `onClicked` event.
* Change according to your needs. */
chrome.browserAction.onClicked.addListener(function() {
var dateStr = new Date().toUTCString();
var details = {
type: "basic",
iconUrl: "/img/notifIcon.png",
title: "REMINDER",
message: dateStr + "\n\n"
+ "There is one very important matter to attend to !\n"
+ "Deal with it now ?",
contextMessage: "Very important stuff...",
buttons: [
{ title: "Yes" },
{ title: "No" }
]
};
var listeners = {
onButtonClicked: function(btnIdx) {
if (btnIdx === 0) {
console.log(dateStr + ' - Clicked: "yes"');
} else if (btnIdx === 1) {
console.log(dateStr + ' - Clicked: "no"');
}
},
onClicked: function() {
console.log(dateStr + ' - Clicked: "message-body"');
},
onClosed: function(byUser) {
console.log(dateStr + ' - Closed: '
+ (byUser ? 'by user' : 'automagically (!?)'));
}
};
/* Create the notification */
createNotification(details, listeners);
});
/* Create a notification and store references
* of its "re-spawn" timer and event-listeners */
function createNotification(details, listeners, notifId) {
(notifId !== undefined) || (notifId = "");
chrome.notifications.create(notifId, details, function(id) {
console.log('Created notification "' + id + '" !');
if (pendingNotifications[id] !== undefined) {
clearTimeout(pendingNotifications[id].timer);
}
pendingNotifications[id] = {
listeners: listeners,
timer: setTimeout(function() {
console.log('Re-spawning notification "' + id + '"...');
destroyNotification(id, function(wasCleared) {
if (wasCleared) {
createNotification(details, listeners, id);
}
});
}, 10000)
};
});
}
/* Completely remove a notification, cancelling its "re-spawn" timer (if any)
* Optionally, supply it with a callback to execute upon successful removal */
function destroyNotification(notifId, callback) {
/* Cancel the "re-spawn" timer (if any) */
if (pendingNotifications[notifId] !== undefined) {
clearTimeout(pendingNotifications[notifId].timer);
delete(pendingNotifications[notifId]);
}
/* Remove the notification itself */
chrome.notifications.clear(notifId, function(wasCleared) {
console.log('Destroyed notification "' + notifId + '" !');
/* Execute the callback (if any) */
callback && callback(wasCleared);
});
}
/* Respond to the user's clicking one of the buttons */
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (pendingNotifications[notifId] !== undefined) {
var handler = pendingNotifications[notifId].listeners.onButtonClicked;
destroyNotification(notifId, handler(btnIdx));
}
});
/* Respond to the user's clicking on the notification message-body */
chrome.notifications.onClicked.addListener(function(notifId) {
if (pendingNotifications[notifId] !== undefined) {
var handler = pendingNotifications[notifId].listeners.onClicked;
destroyNotification(notifId, handler());
}
});
/* Respond to the user's clicking on the small 'x' in the top right corner */
chrome.notifications.onClosed.addListener(function(notifId, byUser) {
if (pendingNotifications[notifId] !== undefined) {
var handler = pendingNotifications[notifId].listeners.onClosed;
destroyNotification(notifId, handler(byUser));
}
});
Final notes:
If your notifications are extremely important, you should implement a "recovery" mechanism, for case such as browser os OS crashes or abrupt termination. E.g. relying on a more persistent storage (localStorage, chrome.storage API etc), resuming pending notifications on extension/browser start-up etc.
It might be a good idea to put a limit on the total number of pending notifications, for "user-friendliness" reasons. If your pending notifications exceed, say, 3 at any given moment, you could replace them with one that informs there are pending notifications and direct the user to a page where you list all of them. (The code will be considerably more complex, but hey anything for the user, right ? ;)
Instead of trying to keep the notifications visible on screen until the user decides to deal with them, it could be better using a Badge (wich can have a color and a small text - indicating the number of pending notifications.
I haven't looked into it, but it might be possible (in which case it is advisable as well) to replace the Timeout's with the chrome.alarms API and then convert the background-page to non-persistent (a.k.a. event-page) which will make it more resource-friendly.
This answer is obsolete; see this answer for an up to date solution involving requireInteraction flag (Chrome 50+).
There is a slightly better (but again, hacky) solution.
When you call update on a notification that changes its priority, and the priority is 0 or above, the notification will be re-shown and the timer for hiding it reset.
So, you can show a notification with a high priority, (say, 2) and then repeat this on an interval shorter than time to hide the notification:
chrome.notifications.update(id, {priority : 1}, function(wasUpdated) {
if(wasUpdated) {
chrome.notifications.update(id, {priority : 2}, function() {});
} else {
// Notification was fully closed; either stop updating or create a new one
}
});
UPDATE answar: after Chrome 50, please add new attribute: [requireInteraction: true]!
don't use chrome.notifications.create
try to use var notification= new Notification("New mail from John Doe", { tag: 'msg1', requireInteraction: true});
will not to close.
if want to close=> notification.close();
ref: http://www.w3.org/TR/notifications/
https://developer.mozilla.org/en-US/docs/Web/API/notification/requireInteraction
webkit notifications seem to be more persistent on the screen, althouth they have the opposite problem - how to hide them to sys tray.
http://developer.chrome.com/extensions/desktop_notifications.html

Accessing DOM object properties from Chrome's content script

I ran into a strange problem with a content script. The content script is defined as "run_at" : "document_end" in the manifest. After a page is loaded the script inserts an object tag into the page (if the tag with predefined id does not exist yet), and sets some properties in it, such as type, width, height, innerHTML, and title. All works fine here.
function checkForObject()
{
var obj = document.getElementById("unique_id");
if(obj == null)
{
var d = document.createElement("object");
d.id = "unique_id";
d.width = "1";
d.height = "1";
d.type = "application/x-y-z";
d.title = "1000";
d.style.position = "absolute";
d.style.left = "0px";
d.style.top = "0px";
d.style.zIndex = "1";
document.getElementsByTagName("body")[0].appendChild(d);
}
}
checkForObject();
I see the new object in the page html-code with proper values in its properties.
Some time later I need to read the title property of the object in the same content script. The code is simple:
function ReadTitle()
{
var obj = document.getElementById("unique_id");
var value = obj.title; // breakpoint
console.log(value);
// TODO: want to use proper title value here
}
The function is called from background.html page:
chrome.tabs.onActivated.addListener(
function(info)
{
chrome.tabs.executeScript(info.tabId, {code: 'setTimeout(ReadTitle, 250);'});
});
Unfortunately, in ReadTitle I'm getting not what I expect. Instead of current value of the title I see the logged value is:
function title() { [native code] }
If I set a breakpoint at the line marked by // breakpoint comment, I see in the watcher that all object properties including the title are correct. Nevertheless, the variable value gets the abovementioned descriptive string.
Apparently, I have missed something simple, but I can't figure it out.
The answer. It was a bug in the npapi plugin, which hosts the object of used type. My apologies for all who have read the question with intention to help.
The NPAPI plugin used in the object erroneously reported title as supported method.

Lifehacker implemention of url change with Ajax

I see that Lifehacker is able to change the url while using AJAX to update part of the page. I guess that can be implemented using HTML5 or history.js plugin, but I guess lifehacker is using neither.
Does any one has a clue on how they do it?
I am new to AJAX and just managed to update part of the page using Ajax.
Thank you #Robin Anderson for a detailed step by step algo. I tried it and it is working fine. However, before I can test it on production, I would like to run by you the code that I have. Did I do everything right?
<script type="text/javascript">
var httpRequest;
var globalurl;
function makeRequest(url) {
globalurl = url;
/* my custom script that retrieves original page without formatting (just data, no templates) */
finalurl = '/content.php?fname=' + url ;
if(window.XMLHttpRequest){httpRequest=new XMLHttpRequest}else if(window.ActiveXObject){try{httpRequest=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{httpRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}
/* if no html5 support, just load the page without ajax*/
if (!(httpRequest && window.history && window.history.pushState)) {
document.href = url;
return false;
}
httpRequest.onreadystatechange = alertContents;
alert(finalurl); /* to make sure, content is being retrieved from ajax */
httpRequest.open('GET', finalurl);
httpRequest.send();
}
/* for support to back button and forward button in browser */
window.onpopstate = function(event) {
if (event.state !== null) {
document.getElementById("ajright").innerHTML = event.state.data;
} else {
document.location.href = globalurl;
return false;
};
};
/* display content in div */
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var stateObj = { data: httpRequest.responseText};
history.pushState(stateObj, "", globalurl);
document.getElementById("ajright").innerHTML = httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
PS: I do not know how to paste code in comment, so I added it here.
It is not an requirement to have the markup as HTML5 in order to use the history API in the browser even if it is an HTML5 feature.
One really quick and simple implementation of making all page transistions load with AJAX is:
Hook up all links except where rel="external" exist to the function "ChangePage"
When ChangePage is triggered, check if history API is supported in the browser.
If history API isn't supported, do either push a hashtag or make a normal full page load as fallback.
If history API is supported:
Prevent the normal link behaviour.
Push the new URL to the browser history.
Make a AJAX request to the new URL and fetch its content.
Look for your content div (or similar element) in the response, take the HTML from that and replace the HTML of the corresponding element on the current page with the new one.
This will be easy to implement, easy to manage caches and work well with Google's robots, the downside is that is isn't that "optimized" and it will be some overhead on the responses (compared to a more complex solution) when you change pages.
Will also have backward compatibility, so old browsers or "non javascript visitors" will just get normal page loads.
Interesting links on the subject
History API Compatibility in different browsers
Mozillas documentation of the History API
Edit:
Another thing worth mentioning is that you shouldn't use this together with ASP .Net Web Forms applications, will probably screw up the postback handling.
Code addition:
I have put together a small demo of this functionality which you can find here.
It simply uses HTML, Javascript (jQuery) and a tiny bit of CSS, I would probably recommend you to test it before using it. But I have checked it some in Chrome and it seems to work decent.
Some testing I would recommend is:
Test in the good browsers, Chrome and Firefox.
Test it in a legacy browser such as IE7
Test it without Javascript enabled (just install Noscript or similar to Chrome/Firefox)
Here is the javascript I used to achieve this, you can find the full source in the demo above.
/*
The arguments are:
url: The url to pull new content from
doPushState: If a new state should be pushed to the browser, true on links and false on normal state changes such as forward and back.
*/
function changePage(url, doPushState, defaultEvent)
{
if (!history.pushState) { //Compatability check
return true; //pushState isn't supported, fallback to normal page load
}
if (defaultEvent != null) {
defaultEvent.preventDefault(); //Someone passed in a default event, stop it from executing
}
if (doPushState) { //If we are supposed to push the state or not
var stateObj = { type: "custom" };
history.pushState(stateObj, "Title", url); //Push the new state to the browser
}
//Make a GET request to the url which was passed in
$.get(url, function(response) {
var newContent = $(response).find(".content"); //Find the content section of the response
var contentWrapper = $("#content-wrapper"); //Find the content-wrapper where we are supposed to change the content.
var oldContent = contentWrapper.find(".content"); //Find the old content which we should replace.
oldContent.fadeOut(300, function() { //Make a pretty fade out of the old content
oldContent.remove(); //Remove it once it is done
contentWrapper.append(newContent.hide()); //Add our new content, hidden
newContent.fadeIn(300); //Fade it in!
});
});
}
//We hook up our events in here
$(function() {
$(".generated").html(new Date().getTime()); //This is just to present that it's actually working.
//Bind all links to use our changePage function except rel="external"
$("a[rel!='external']").live("click", function (e) {
changePage($(this).attr("href"), true, e);
});
//Bind "popstate", it is the browsers back and forward
window.onpopstate = function (e) {
if (e.state != null) {
changePage(document.location, false, null);
}
}
});
The DOCTYPE has no effect on which features the page can use.
They probably use the HTML5 History API directly.

How to detect when cancel is clicked on file input?

How can I detect when the user cancels a file input using an html file input?
onChange lets me detect when they choose a file, but I would also like to know when they cancel (close the file choose dialog without selecting anything).
While not a direct solution, and also bad in that it only (as far as I've tested) works with onfocus (requiring a pretty limiting event blocking) you can achieve it with the following:
document.body.onfocus = function(){ /*rock it*/ }
What's nice about this, is that you can attach/detach it in time with the file event, and it also seems to work fine with hidden inputs (a definite perk if you're using a visual workaround for the crappy default input type='file'). After that, you just need to figure out if the input value changed.
An example:
var godzilla = document.getElementById('godzilla')
godzilla.onclick = charge
function charge()
{
document.body.onfocus = roar
console.log('chargin')
}
function roar()
{
if(godzilla.value.length) alert('ROAR! FILES!')
else alert('*empty wheeze*')
document.body.onfocus = null
console.log('depleted')
}
See it in action: http://jsfiddle.net/Shiboe/yuK3r/6/
Sadly, it only seems to work on webkit browsers. Maybe someone else can figure out the firefox/IE solution
So I'll throw my hat into this question since I came up with a novel solution. I have a Progressive Web App which allows users to capture photos and videos and upload them. We use WebRTC when possible, but fall back to HTML5 file pickers for devices with less support *cough Safari cough*. If you're working specifically on an Android/iOS mobile web application which uses the native camera to capture photos/videos directly, then this is the best solution I have come across.
The crux of this problem is that when the page loads, the file is null, but then when the user opens the dialog and presses "Cancel", the file is still null, hence it did not "change", so no "change" event is triggered. For desktops, this isn't too bad because most desktop UI's aren't dependent on knowing when a cancel is invoked, but mobile UI's which bring up the camera to capture a photo/video are very dependent on knowing when a cancel is pressed.
I originally used the document.body.onfocus event to detect when the user returned from the file picker, and this worked for most devices, but iOS 11.3 broke it as that event is not triggered.
Concept
My solution to this is *shudder* to measure CPU timing to determine if the page is currently in the foreground or the background. On mobile devices, processing time is given to the app currently in the foreground. When a camera is visible it will steal CPU time and deprioritize the browser. All we need to do is measure how much processing time our page is given, when camera launches our available time will drop drastically. When the camera is dismissed (either cancelled or otherwise), our available time spike back up.
Implementation
We can measure CPU timing by using setTimeout() to invoke a callback in X milliseconds, and then measure how long it took to actually invoke it. The browser will never invoke it exactly after X milliseconds, but if it is reasonable close then we must be in the foreground. If the browser is very far away (over 10x slower than requested) then we must be in the background. A basic implementation of this is like so:
function waitForCameraDismiss() {
const REQUESTED_DELAY_MS = 25;
const ALLOWED_MARGIN_OF_ERROR_MS = 25;
const MAX_REASONABLE_DELAY_MS =
REQUESTED_DELAY_MS + ALLOWED_MARGIN_OF_ERROR_MS;
const MAX_TRIALS_TO_RECORD = 10;
const triggerDelays = [];
let lastTriggerTime = Date.now();
return new Promise((resolve) => {
const evtTimer = () => {
// Add the time since the last run
const now = Date.now();
triggerDelays.push(now - lastTriggerTime);
lastTriggerTime = now;
// Wait until we have enough trials before interpreting them.
if (triggerDelays.length < MAX_TRIALS_TO_RECORD) {
window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
return;
}
// Only maintain the last few event delays as trials so as not
// to penalize a long time in the camera and to avoid exploding
// memory.
if (triggerDelays.length > MAX_TRIALS_TO_RECORD) {
triggerDelays.shift();
}
// Compute the average of all trials. If it is outside the
// acceptable margin of error, then the user must have the
// camera open. If it is within the margin of error, then the
// user must have dismissed the camera and returned to the page.
const averageDelay =
triggerDelays.reduce((l, r) => l + r) / triggerDelays.length
if (averageDelay < MAX_REASONABLE_DELAY_MS) {
// Beyond any reasonable doubt, the user has returned from the
// camera
resolve();
} else {
// Probably not returned from camera, run another trial.
window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
}
};
window.setTimeout(evtTimer, REQUESTED_DELAY_MS);
});
}
I tested this on recent version of iOS and Android, bringing up the native camera by setting the attributes on the <input /> element.
<input type="file" accept="image/*" capture="camera" />
<input type="file" accept="video/*" capture="camcorder" />
This works out actually a lot better than I expected. It runs 10 trials by requesting a timer to be invoked in 25 milliseconds. It then measures how long it actually took to invoke, and if the average of 10 trials is less than 50 milliseconds, we assume that we must be in the foreground and the camera is gone. If it is greater than 50 milliseconds, then we must still be in the background and should continue to wait.
Some additional details
I used setTimeout() rather than setInterval() because the latter can queue multiple invocations which execute immediately after each other. This could drastically increase the noise in our data, so I stuck with setTimeout() even though it is a little more complicated to do so.
These particular numbers worked well for me, though I have see at least once instance where the camera dismiss was detected prematurely. I believe this is because the camera may be slow to open, and the device may run 10 trials before it actually becomes backgrounded. Adding more trials or waiting some 25-50 milliseconds before starting this function may be a workaround for that.
Desktop
Unfortuantely, this doesn't really work for desktop browsers. In theory the same trick is possible as they do prioritize the current page over backgrounded pages. However many desktops have enough resources to keep the page running at full speed even when backgrounded, so this strategy doesn't really work in practice.
Alternative solutions
One alternative solution not many people mention that I did explore was mocking a FileList. We start with null in the <input /> and then if the user opens the camera and cancels they come back to null, which is not a change and no event will trigger. One solution would be to assign a dummy file to the <input /> at page start, therefore setting to null would be a change which would trigger the appropriate event.
Unfortunately, there's no way official way to create a FileList, and the <input /> element requires a FileList in particular and will not accept any other value besides null. Naturally, FileList objects cannot be directly constructed, do to some old security issue which isn't even relevant anymore apparently. The only way to get ahold of one outside of an <input /> element is to utilize a hack which copy-pastes data to fake a clipboard event which can contain a FileList object (you're basically faking a drag-and-drop-a-file-on-your-website event). This is possible in Firefox, but not for iOS Safari, so it was not viable for my particular use case.
Browsers, please...
Needless to say this is patently ridiculous. The fact that web pages are given zero notification that a critical UI element has changed is simply laughable. This is really a bug in the spec, as it was never intended for a full-screen media capture UI, and not triggering the "change" event is technically to spec.
However, can browser vendors please recognize the reality of this? This could be solved with either a new "done" event which is triggered even when no change occurs, or you could just trigger "change" anyways. Yeah, that would be against spec, but it is trivial for me to dedup a change event on the JavaScript side, yet fundamentally impossible to invent my own "done" event. Even my solution is really just heuristics, if offer no guarantees on the state of the browser.
As it stands, this API is fundamentally unusable for mobile devices, and I think a relatively simple browser change could make this infinitely easier for web developers *steps off soap box*.
You can't.
The result of the file dialog is not exposed to the browser.
When you select a file and click open/cancel, the input element should lose focus aka blur. Assuming the initial value of the input is empty, any non empty value in your blur handler would indicate an OK, and an empty value would mean a Cancel.
UPDATE: The blur is not triggered when the input is hidden. So can't use this trick with IFRAME-based uploads, unless you want to temporarily display the input.
Most of these solutions don't work for me.
The problem is that you never know which event will be triggered fist,
is it click or is it change? You can't assume any order, because it probably depends on the browser's implementation.
At least in Opera and Chrome (late 2015) click is triggered just before 'filling' input with files, so you will never know the length of files.length != 0 until you delay click to be triggered after change.
Here is code:
var inputfile = $("#yourid");
inputfile.on("change click", function(ev){
if (ev.originalEvent != null){
console.log("OK clicked");
}
document.body.onfocus = function(){
document.body.onfocus = null;
setTimeout(function(){
if (inputfile.val().length === 0) console.log("Cancel clicked");
}, 1000);
};
});
/* Tested on Google Chrome */
$("input[type=file]").bind("change", function() {
var selected_file_name = $(this).val();
if ( selected_file_name.length > 0 ) {
/* Some file selected */
}
else {
/* No file selected or cancel/close
dialog button clicked */
/* If user has select a file before,
when they submit, it will treated as
no file selected */
}
});
The new File System Access API will make our life easy again :)
try {
const [fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
// ...
}
catch (e) {
console.log('Cancelled, no file selected');
}
Browser support is very limited (Jan, 2021). The example code works well in Chrome Desktop 86.
Just listen to the click event as well.
Following from Shiboe's example, here's a jQuery example:
var godzilla = $('#godzilla');
var godzillaBtn = $('#godzilla-btn');
godzillaBtn.on('click', function(){
godzilla.trigger('click');
});
godzilla.on('change click', function(){
if (godzilla.val() != '') {
$('#state').html('You have chosen a Mech!');
} else {
$('#state').html('Choose your Mech!');
}
});
You can see it in action here: http://jsfiddle.net/T3Vwz
You can catch the cancel if you choose the same file as previously and you click cancel: in this case.
You can do it like this:
<input type="file" id="myinputfile"/>
<script>
document.getElementById('myinputfile').addEventListener('change', myMethod, false);
function myMethod(evt) {
var files = evt.target.files;
f= files[0];
if (f==undefined) {
// the user has clicked on cancel
}
else if (f.name.match(".*\.jpg")|| f.name.match(".*\.png")) {
//.... the user has choosen an image file
var reader = new FileReader();
reader.onload = function(evt) {
try {
myimage.src=evt.target.result;
...
} catch (err) {
...
}
};
}
reader.readAsDataURL(f);
</script>
The easiest way is to check if there are any files in temporary memory. If you want to get the change event every time user clicks the file input you can trigger it.
var yourFileInput = $("#yourFileInput");
yourFileInput.on('mouseup', function() {
$(this).trigger("change");
}).on('change', function() {
if (this.files.length) {
//User chose a picture
} else {
//User clicked cancel
}
});
In my case i had to hide submit button while users were selecting images.
This is what i come up:
$(document).on('click', '#image-field', function(e) {
$('.submit-button').prop('disabled', true)
})
$(document).on('focus', '#image-field'), function(e) {
$('.submit-button').prop('disabled', false)
})
#image-field is my file selector. When somenone clicks on it, i disable the form submit button. The point is, when the file dialog closed - doesn't matter they select a file or cancel - #image-field got the focus back, so i listen on that event.
UPDATE
I found that, this does not work in safari and poltergeist/phantomjs. Take this info into account if you would like to implement it.
Shiboe's solution would be a good one if it worked on mobile webkit, but it doesn't. What I can come up with is to add a mousemove event listener to some dom object at the time that the file input window is opened, like so:
$('.upload-progress').mousemove(function() {
checkForFiles(this);
});
checkForFiles = function(me) {
var filefield = $('#myfileinput');
var files = filefield.get(0).files;
if (files == undefined || files[0] == undefined) $(me).remove(); // user cancelled the upload
};
The mousemove event is blocked from the page while the file dialog is open, and when its closed one checks to see if there are any files in the file input. In my case I want an activity indicator blocking things till the file is uploaded, so I only want to remove my indicator on cancel.
However this doesn't solve for mobile, since there is no mouse to move. My solution there is less than perfect, but I think its good enough.
$('.upload-progress').bind('touchstart', function() {
checkForFiles(this);
});
Now we're listening for a touch on the screen to do the same files check. I'm pretty confident that the user's finger will be put on the screen pretty quickly after cancel and dismiss this activity indicator.
One could also just add the activity indicator on the file input change event, but on mobile there is often a few seconds lag between selecting the image and the change event firing, so its just much better UX for the activity indicator to be displayed at the start of the process.
I found this atribute, its most simple yet.
if ($('#selectedFile')[0].files.length > 1)
{
// Clicked on 'open' with file
} else {
// Clicked on 'cancel'
}
Here, selectedFile is an input type=file.
I know this is a very old question but just in case it helps someone, I found when using the onmousemove event to detect the cancel, that it was necessary to test for two or more such events in a short space of time.
This was because single onmousemove events are generated by the browser (Chrome 65) each time the cursor is moved out of the select file dialog window and each time it is moved out of the main window and back in.
A simple counter of mouse movement events coupled with a short duration timeout to reset the counter back to zero worked a treat.
Combining Shiboe's and alx's solutions, i've got the most reliable code:
var selector = $('<input/>')
.attr({ /* just for example, use your own attributes */
"id": "FilesSelector",
"name": "File",
"type": "file",
"contentEditable": "false" /* if you "click" on input via label, this prevents IE7-8 from just setting caret into file input's text filed*/
})
.on("click.filesSelector", function () {
/* do some magic here, e.g. invoke callback for selection begin */
var cancelled = false; /* need this because .one calls handler once for each event type */
setTimeout(function () {
$(document).one("mousemove.filesSelector focusin.filesSelector", function () {
/* namespace is optional */
if (selector.val().length === 0 && !cancelled) {
cancelled = true; /* prevent double cancel */
/* that's the point of cancel, */
}
});
}, 1); /* 1 is enough as we just need to delay until first available tick */
})
.on("change.filesSelector", function () {
/* do some magic here, e.g. invoke callback for successful selection */
})
.appendTo(yourHolder).end(); /* just for example */
Generally, mousemove event does the trick, but in case user made a click and than:
cancelled file open dialog by escape key (without moving a mouse), made another accurate click to open file dialog again...
switched focus to any other application, than came back to browser's file open dialog and closed it, than opened again via enter or space key...
... we won't get mousemove event hence no cancel callback. Moreover, if user cancels second dialog and makes a mouse move, we'll get 2 cancel callbacks.
Fortunately, special jQuery focusIn event bubbles up to the document in both cases, helping us to avoid such situations. The only limitation is if one blocks focusIn event either.
I see that my response would be quite outdated, but never the less.
I faced with the same problem. So here's my solution.
The most useful code snipped was KGA's one. But it isn't totally working and is a bit complicated. But I simplified it.
Also, the main trouble maker was that fact, that 'change' event doesn't come instantly after focus, so we have to wait for some time.
"#appendfile" - which user clicks on to append a new file.
Hrefs get focus events.
$("#appendfile").one("focusin", function () {
// no matter - user uploaded file or canceled,
// appendfile gets focus
// change doesn't come instantly after focus, so we have to wait for some time
// wrapper represents an element where a new file input is placed into
setTimeout(function(){
if (wrapper.find("input.fileinput").val() != "") {
// user has uploaded some file
// add your logic for new file here
}
else {
// user canceled file upload
// you have to remove a fileinput element from DOM
}
}, 900);
});
You can detect this only in limited circumstances. Specifically, in chrome if a file was selected earlier and then the file dialog is clicked and cancel clicked, Chrome clears the file and fires the onChange event.
https://code.google.com/p/chromium/issues/detail?id=2508
In this scenario, you can detect this by handling the onChange event and checking the files property.
This is hacky at best, but here is a working example of my solution to detect whether or not a user has uploaded a file, and only allowing them to proceed if they have uploaded a file.
Basically hide the Continue, Save, Proceed or whatever your button is. Then in the JavaScript you grab the file name. If the file name does not have a value, then do not show the Continue button. If it does have a value, then show the button. This also works if they at first upload a file and then they try to upload a different file and click cancel.
Here is the code.
HTML:
<div class="container">
<div class="row">
<input class="file-input" type="file" accept="image/*" name="fileUpload" id="fileUpload" capture="camera">
<label for="fileUpload" id="file-upload-btn">Capture or Upload Photo</label>
</div>
<div class="row padding-top-two-em">
<input class="btn btn-success hidden" id="accept-btn" type="submit" value="Accept & Continue"/>
<button class="btn btn-danger">Back</button>
</div></div>
JavaScript:
$('#fileUpload').change(function () {
var fileName = $('#fileUpload').val();
if (fileName != "") {
$('#file-upload-btn').html(fileName);
$('#accept-btn').removeClass('hidden').addClass('show');
} else {
$('#file-upload-btn').html("Upload File");
$('#accept-btn').addClass('hidden');
}
});
CSS:
.file-input {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.file-input + label {
font-size: 1.25em;
font-weight: normal;
color: white;
background-color: blue;
display: inline-block;
padding: 5px;
}
.file-input:focus + label,
.file-input + label:hover {
background-color: red;
}
.file-input + label {
cursor: pointer;
}
.file-input + label * {
pointer-events: none;
}
For the CSS a lot of this is to make the website and button accessible for everyone. Style your button to whatever you like.
The following seems to work for me (on desktop, windows):
var openFile = function (mimeType, fileExtension) {
var defer = $q.defer();
var uploadInput = document.createElement("input");
uploadInput.type = 'file';
uploadInput.accept = '.' + fileExtension + ',' + mimeType;
var hasActivated = false;
var hasChangedBeenCalled = false;
var hasFocusBeenCalled = false;
var focusCallback = function () {
if (hasActivated) {
hasFocusBeenCalled = true;
document.removeEventListener('focus', focusCallback, true);
setTimeout(function () {
if (!hasChangedBeenCalled) {
uploadInput.removeEventListener('change', changedCallback, true);
defer.resolve(null);
}
}, 300);
}
};
var changedCallback = function () {
uploadInput.removeEventListener('change', changedCallback, true);
if (!hasFocusBeenCalled) {
document.removeEventListener('focus', focusCallback, true);
}
hasChangedBeenCalled = true;
if (uploadInput.files.length === 1) {
//File picked
var reader = new FileReader();
reader.onload = function (e) {
defer.resolve(e.target.result);
};
reader.readAsText(uploadInput.files[0]);
}
else {
defer.resolve(null);
}
};
document.addEventListener('focus', focusCallback, true); //Detect cancel
uploadInput.addEventListener('change', changedCallback, true); //Detect when a file is picked
uploadInput.click();
hasActivated = true;
return defer.promise;
}
This does use angularjs $q but you should be able to replace it with any other promise framework if needed.
Tested on IE11, Edge, Chrome, Firefox, but it does not seem to work on Chrome on a Android Tablet as it does not fire the Focus event.
The file-type field, frustratingly, doesn't respond to a lot of events (blur would be lovely). I see a lot of people suggesting change-oriented solutions and them getting downvoted.
change does work, but it has a major flaw (vs what we want to happen).
When you freshly load a page containing a file field, open the box and press cancel. Nothing, frustratingly, changes.
What I chose to do is load in a gated-state.
The next part of the form a section#after-image in my case is hidden from view. When my file field changes, an upload button is shown. Upon successful upload, section#after-image is shown.
If the user loads, opens the file-dialog, then cancels out, they never see the upload button.
If the user chooses a file, the upload button is shown. If they then open the dialog and cancel, the change event is triggered by this cancel, and there I can (and do) re-hide my upload button until a proper file is selected.
I was fortunate that this gated-state was already the design of my form. You do not need to use the same style, merely having the upload button initially hidden and upon change, setting a hidden field or javascript variable to something you can monitor on submit.
I tried changing the value of files[0] before the field was interacted with. This didn't do anything regarding onchange.
So yes, change works, at least as good as we're going to get. The filefield is secured, for obvious reasons, but to the frustration of well-intentioned developers.
It's not fitting to my purpose, but you might be able to, onclick, load a warning prompt (not an alert(), because that stalls page-processing), and hide it if change is triggered and files[0] is null. If change is not triggered, the div remains in its state.
Solution for file selection with hidden input
Note: this code doesn't detect cancellation, it offers a way to circumvent the need to detect it in a common case in which people try to detect it.
I got here while looking for a solution for file uploads using a hidden input, I believe that this is the most common reason to look for a way to detect cancellation of file input (open file dialog -> if a file was selected then run some code, otherwise do nothing), here's my solution:
var fileSelectorResolve;
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.addEventListener('input', function(){
fileSelectorResolve(this.files[0]);
fileSelectorResolve = null;
fileSelector.value = '';
});
function selectFile(){
if(fileSelectorResolve){
fileSelectorResolve();
fileSelectorResolve = null;
}
return new Promise(function(resolve){
fileSelectorResolve = resolve;
fileSelector.dispatchEvent(new MouseEvent('click'));
});
}
Usage example:
Note that if no file was selected then the first line will return only once selectFile() is called again (or if you called fileSelectorResolve() from elsewhere).
async function logFileName(){
const file = await selectFile();
if(!file) return;
console.log(file.name);
}
Another example:
async function uploadFile(){
const file = await selectFile();
if(!file) return;
// ... make an ajax call here to upload the file ...
}
There is a hackish way to do this (add callbacks or resolve some deferred/promise implementation instead of alert() calls):
var result = null;
$('<input type="file" />')
.on('change', function () {
result = this.files[0];
alert('selected!');
})
.click();
setTimeout(function () {
$(document).one('mousemove', function () {
if (!result) {
alert('cancelled');
}
});
}, 1000);
How it works: while file selection dialog is open, document does not receive mouse pointer events. There is 1000ms delay to allow the dialog to actually appear and block browser window. Checked in Chrome and Firefox (Windows only).
But this is not a reliable way to detect cancelled dialog, of course. Though, might improve some UI behavior for you.
Here is my solution, using the file input focus (not using any timers)
var fileInputSelectionInitiated = false;
function fileInputAnimationStart() {
fileInputSelectionInitiated = true;
if (!$("#image-selector-area-icon").hasClass("fa-spin"))
$("#image-selector-area-icon").addClass("fa-spin");
if (!$("#image-selector-button-icon").hasClass("fa-spin"))
$("#image-selector-button-icon").addClass("fa-spin");
}
function fileInputAnimationStop() {
fileInputSelectionInitiated = false;
if ($("#image-selector-area-icon").hasClass("fa-spin"))
$("#image-selector-area-icon").removeClass("fa-spin");
if ($("#image-selector-button-icon").hasClass("fa-spin"))
$("#image-selector-button-icon").removeClass("fa-spin");
}
$("#image-selector-area-wrapper").click(function (e) {
$("#fileinput").focus();
$("#fileinput").click();
});
$("#preview-image-wrapper").click(function (e) {
$("#fileinput").focus();
$("#fileinput").click();
});
$("#fileinput").click(function (e) {
fileInputAnimationStart();
});
$("#fileinput").focus(function (e) {
fileInputAnimationStop();
});
$("#fileinput").change(function(e) {
// ...
}
Well, this doesn't exactly answers your question. My assumption is that, you have a scenario, when you add a file input, and invoke file selection, and if user hits cancel, you just remove the input.
If this is the case, then: Why adding empty file input?
Create the one on the fly, but add it to DOM only when it is filled in. Like so:
var fileInput = $("<input type='file' name='files' style='display: none' />");
fileInput.bind("change", function() {
if (fileInput.val() !== null) {
// if has value add it to DOM
$("#files").append(fileInput);
}
}).click();
So here I create <input type="file" /> on the fly, bind to it's change event and then immediately invoke click. On change will fire only when user selects a file and hits Ok, otherwise input will not be added to DOM, therefore will not be submitted.
Working example here: https://jsfiddle.net/69g0Lxno/3/
//Use hover instead of blur
var fileInput = $("#fileInput");
if (fileInput.is(":hover") {
//open
} else {
}
function file_click() {
document.body.onfocus = () => {
setTimeout(_=>{
let file_input = document.getElementById('file_input');
if (!file_input.value) alert('please choose file ')
else alert(file_input.value)
document.body.onfocus = null
},100)
}
}
Using setTimeout to get the certain value of the input.
If you already require JQuery, this solution might do the work (this is the exact same code I actually needed in my case, although using a Promise is just to force the code to wait until file selection has been resolved):
await new Promise(resolve => {
const input = $("<input type='file'/>");
input.on('change', function() {
resolve($(this).val());
});
$('body').one('focus', '*', e => {
resolve(null);
e.stopPropagation();
});
input.click();
});
There are several proposed solutions in this thread and this difficulty to detecting when the user clicks the "Cancel" button on the file selection box is a problem that affects many people.
The fact is that there is no 100% reliable way to detect if the user has clicked the "Cancel" button on the file selection box. But there are ways to reliably detect if the user has added a file to the input file. So this is the basic strategy of this answer!
I decided to add this answer because apparently the other answers don't work on most browsers or guaranteed on mobile devices.
Briefly the code is based on 3 points:
The input file is initially created dynamically in "memory" in js
(we don't add it to the "HTML" at this moment);
After adding the file then the input file is added to the HTML, otherwise nothing occurs;
The removal of the file is done by removing the input file from the
HTML by a specific event, which means that the
"editing"/"modification" of the file is done by removing the old
input file and creating a new one.
For a better understanding look at the code below and the notes as well.
[...]
<button type="button" onclick="addIptFl();">ADD INPUT FILE!</button>
<span id="ipt_fl_parent"></span>
[...]
function dynIptFl(jqElInst, funcsObj) {
if (typeof funcsObj === "undefined" || funcsObj === "") {
funcsObj = {};
}
if (funcsObj.hasOwnProperty("before")) {
if (!funcsObj["before"].hasOwnProperty("args")) {
funcsObj["before"]["args"] = [];
}
funcsObj["before"]["func"].apply(this, funcsObj["before"]["args"]);
}
var jqElInstFl = jqElInst.find("input[type=file]");
// NOTE: Open the file selection box via js. By Questor
jqElInstFl.trigger("click");
// NOTE: This event is triggered if the user selects a file. By Questor
jqElInstFl.on("change", {funcsObj: funcsObj}, function(e) {
// NOTE: With the strategy below we avoid problems with other unwanted events
// that may be associated with the DOM element. By Questor
e.preventDefault();
var funcsObj = e.data.funcsObj;
if (funcsObj.hasOwnProperty("after")) {
if (!funcsObj["after"].hasOwnProperty("args")) {
funcsObj["after"]["args"] = [];
}
funcsObj["after"]["func"].apply(this, funcsObj["after"]["args"]);
}
});
}
function remIptFl() {
// NOTE: Remove the input file. By Questor
$("#ipt_fl_parent").empty();
}
function addIptFl() {
function addBefore(someArgs0, someArgs1) {
// NOTE: All the logic here happens just before the file selection box opens.
// By Questor
// SOME CODE HERE!
}
function addAfter(someArgs0, someArgs1) {
// NOTE: All the logic here happens only if the user adds a file. By Questor
// SOME CODE HERE!
$("#ipt_fl_parent").prepend(jqElInst);
}
// NOTE: The input file is hidden as all manipulation must be done via js.
// By Questor
var jqElInst = $('\
<span>\
<button type="button" onclick="remIptFl();">REMOVE INPUT FILE!</button>\
<input type="file" name="input_fl_nm" style="display: block;">\
</span>\
');
var funcsObj = {
before: {
func: addBefore,
args: [someArgs0, someArgs1]
},
after: {
func: addAfter,
// NOTE: The instance with the input file ("jqElInst") could be passed
// here instead of using the context of the "addIptFl()" function. That
// way "addBefore()" and "addAfter()" will not need to be inside "addIptFl()",
// for example. By Questor
args: [someArgs0, someArgs1]
}
};
dynIptFl(jqElInst, funcsObj);
}
Thanks! =D
We achieved in angular like below.
bind click event on input type file.
Attach focus event with window and add condition if uploadPanel is true then show console.
when click on input type file the boolean uploadPanel value is true. and dialogue box appear.
when cancel OR Esc button click then dialogue box dispensary and console appear.
HTML
<input type="file" formControlName="FileUpload" click)="handleFileInput($event.target.files)" />
/>
TS
this.uploadPanel = false;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
console.log("ggg" + files);
this.uploadPanel = true;
}
#HostListener("window:focus", ["$event"])
onFocus(event: FocusEvent): void {
if (this.uploadPanel == true) {
console.log("cancel clicked")
this.addSlot
.get("FileUpload")
.setValidators([
Validators.required,
FileValidator.validate,
requiredFileType("png")
]);
this.addSlot.get("FileUpload").updateValueAndValidity();
}
}
Just add 'change' listener on your input whose type is file. i.e
<input type="file" id="file_to_upload" name="file_to_upload" />
I have done using jQuery and obviously anyone can use valina JS (as per the requirement).
$("#file_to_upload").change(function() {
if (this.files.length) {
alert('file choosen');
} else {
alert('file NOT choosen');
}
});