What are techniques to get around the IE file download security rules? - javascript

Internet Explorer (with default settings, which I generally assume will be in effect on the desktops of the Great Unwashed) seems to dislike the idea of accepting attachment content in an HTTP response if the corresponding request wasn't made directly from a user action (like a "click" handler, or a native form submit). There are probably more details and nuances, but that's the basic behavior that's frustrating me.
It seems to me that this situation is common: the user interface in front of some downloadable content — say, a prepared PDF report — allows for some options and inputs to be used in the creation of the content. Now, as with all forms that allow the user to stipulate how an application does something, it's possible that the input will be erroneous. Not always, but sometimes.
Thus there's a dilemma. If the client tries to do something fancy, like run an AJAX transaction to let the server vet the form contents, and then resubmit to get the download, IE won't like that. It won't like it because the actual HTTP transaction that carries the attachment back will happen not in the original user-action event handler, but in the AJAX completion callback. Worse, since the IE security bar seems to think that the solution to all one's problems is to simply reload the outer page from its original URL, its invitation to the user to go ahead and download the suspicious content won't even work.
The other option is to just have the form fire away. The server checks the parameters, and if there's anything wrong it responds with the form-container page, peppered appropriately with error messages. If the form contents are OK, it generates the content and ships it back in the HTTP response as an attached file. In this case (I think), IE is happy because the content was apparently directly requested by the user (which is, by the way, a ridiculously flimsy way to tell good content from bad content). This is great, but the problem now is that the client environment (that is, the code on my page) can't tell that the download worked, so the form is still just sitting there. If my form is in some sort of dialog, then I really need to close that up when the operation is complete — really, that's one of the motivations for doing it the AJAX way.
It seems to me that the only thing to do is equip the form dialogs with messaging that says something like, "Close this when your download begins." That really seems lame to me because it's an example of a "please push this button for me" interface: ideally, my own code should be able to push the buutton when it's appropriate. A key thing that I don't know is whether there's any way for client code to detect that form submission has resulted in an attachment download. I've never heard of a way to detect that, but that'd break the impasse for me.

I take it you're submitting the form with a different target window; hence the form staying in place.
There are several options.
Keep the submit button disabled and do ongoing validation in the background, polling the form for changes to fields and then firing off the validation request for a field as it changes. When the form is in a valid state, enable the button; when it isn't, disable the button. This isn't perfect, as there will tend to be a delay, but it may be good enough for whatever you're doing.
Do basic validation that doesn't require round-trips to the server in a handler for the form's submit event, then submit the form and remove it (or possibly just hide it). If the further validation on the server detects a problem, it can return a page that uses JavaScript to tell the original window to re-display the form.
Use a session cookie and a unique form ID (the current time from new Date().getTime() would do); when the form is submitted, disable its submit button but keep it visible until the response comes back. Make the response set a session cookie with that ID indicating success/failure. Have the window containing the form poll for the cookie every second or so and act on the result when it sees it. (I've never done this last one; not immediately seeing why it wouldn't work.)
I expect there are about a dozen other ways to skin this cat, but those are three that came to mind.
(Edit) If you're not submitting to a different target, you might want to go ahead and do that -- to a hidden iframe on the same page. That (possibly combined with the above or other answers) might help you get the user experience you're looking for.

There's a whole number of really good reasons IE does this, and I'm sure it's not something anyone would argue with - so the main objective is to get around it somehow to make things better for your users.
Sometimes its worth re-thinking how things are done. Perhaps disable the button, use javascript to check when all the fields are filled out, and fire off an ajax request once they are. If the ajax was successful, enable the button. This is but one suggestion, I'm sure there will be more...
Edit: more...
Do simple submission (non-AJAX), and if the checks fail, send a page back rather than an attachment. The page sent back could contain all the information originally submitted (plus whatever error message to the user) so the user doesn't need to fill out the entire form again. And I'm also sure there will be more ideas...
Edit: more...
I'm sure you've seen this type of thing before - and yes, it is an extra click (not ideal, but not hard).... an "if your download fails, click here" -> in this case, do it as you want to do it, but add a new link/button to the page when the AJAX returns, so if the download failed, they can submit the already validated form from a "direct user action". And I'm sure I'll think of more (or someone else will).....

I have been fighting a similar issue for a while. In my case, posting to a hidden iframe didn't work if my web app was embedded in an iframe on another site (third party cookie issues) unless our site was added to the Trusted Sites list.
I have found that I could break up the download into POST and GET sequence. The post returns a short lived GUID that can be used in a GET request to initiate the download. The POST can do the form validation as well as return the GUID in a successful response. Once the client has the GUID, you can set the src property of a hidden iframe element to the download URL. The browser sees the 'Content-Disposition': 'attachement' header and gives the user a download ribbon to download the file.
So far it appears to work in all the latest browsers. Unfortunately it requires you to modify you server side API for downloading the file.

Related

Collecting a response without requiring log in - one time URL? Issues with false positives

Background and Problem
I have a system that has core users augmented by some minor contributors who only need to be able to provide approvals for certain things. To support this, the system reacts to database changes and emails those approvers with a single button in the body of the email. This button is just a link to a unique url - something like https://myapp/response/12345-abcdefg-6789.
That "response" page is listed in the web config as not requiring a log in. Thus, the approver should only have to click on the link in the email, and the system should detect that and mark their response.
In all of our testing, this works great. All we're doing is marking the response via the page's code behind, and then displaying a message on the page that the response was received. On the surface, this seems like about as easy of a task as you can dream up.
However, we're getting false positives in production. The approvers are telling us that things are being marked as approved when they never clicked the link. I assume this has something to do with their browsers checking the links for safety or something - and by performing that safety check, it's triggering the system to record the response. Unfortunately, i haven't been able to reproduce this - even when we have some of the approvers on the phone while we try it.
The question is - what is the best strategy to avoid a false positive with buttons in an email?
Lots of companies do this kind of thing - i'm looking right now at an invitation from a friend via evite. It has Yes, Maybe, and No which appear to have the same kind of setup i described above.
Is there something i should be doing with redirects after x seconds? Is there some other javascript i should be deploying on the page? Is there some other potential cause for this? The IIS logs seem to indicate that the "fake clicks" are coming from the target users computers. Which is a bit of a relief, since it's hard to imagine how some other external machine could end up at a GUID based url that is not represented by a physical file that could be crawled over in some way.
I would like to avoid having another button for the user to click, where they would click "Approve" in the email, and then when they get to the page they have click the same thing again.
Thanks!
From my understanding there are two ways to go about it. But both methods assume the current "response" page is just an intermediary.
Add another button on the page (#
https://myapp/response/12345-abcdefg-6789 for instance) that actually
submits the response (or redirects to the actual response page). It would add an extra step for your approvers but
it should work. (You can even add a captcha there if paranoid)
Once the page is loaded, redirect to the actual response page via
javascript. The idea being if the link is automatically opened by
some kind of bot it's unlikely it runs the script.

Form post parameters ending up in URL

This is going to be a difficult one to explain but basically I have an angular application with a login form which runs a function on submit which sends an ajax request to the server to do the login.
Now, I'm not using ng-submit but hijacking the normal submit attribute like this:
<form my-form submit="controllername.doSubmit()">
I then have an angular directive called "my-form" which uses {require: 'form'} in it's definition object and then does this in the postLink function:
element.bind('submit', function(event)
{
// Removed for brevity
scope.$apply(scope.submit);
});
So, basically this form submit stuff was written a long time ago and does a lot of other stuff like triggering form validation and stuff by default so I don't wnt to rewrite any of this or go back to using ng-submit. Aside form anything else I have a few big apps using this code which would need to change a lot.
Anyway, it all works fine on the surface but if I fill in the log in form and then do some other stuff (including filling in other forms set up the same way) and then leave my laptop for a few days and come back to the page, somehow all the form data has been added into the URL bar, after the ?? and before the # including the password in plain view!
Not sure why this doesn't happen straight away, ony after un-sleeping the PC, and not always. The other weird thing is that the names of the parameters are not the original ones (email, password) but the names of the parameters of the first form currently on the page (actionStatus, required), so Chrome is obviously getting very confused.
My instinct tells me that when the form is submitted, the formData is being stored somewhere for later because I'm not cancelling the default action of the form correctly when I'm running my javascript function and because it's a single page application that formData never leaves the memory. It's then thinking it's gone to a new page and putting that data in the URl, but it's getting the names wrong because the forms on the page has changed.
Sorry, I can't provide more code, just a fairly wooly description but I don't know what else to say really, it's all very strange.
I finally have an answer to this and the answer is totally unexpected.
I use a plugin called browserSync to sync multiple browsers I'm testing on and it had a feature called form syncing switched on.
I had chrome open and when I opened up another browser (typically in the morning when the computer first woke up) I had to log in and because they were on different pages it was copying my login details from Firefox into the first form it found in my existing chrome window. It was also putting the contents of Firefox's login form into chrome's URL.
Crazy.

With the Javascript event onbeforeunload, is it possible to do anything other than an alert dialog?

In all of the sample code I have seen, it appears that the only function of onbeforeunload is to serve up an alert dialog box prior to the person leaving the page. Is that the only thing that can be triggered by the event or is it possible to do something else, like an unobtrusive function that sends off partial form data?
I am trying to capture abandoned shopping carts in Yahoo! Small Business and unfortunately I do not have access to any server side scripting, so I'm forced to work client-side only.
I was also thinking of doing an ajax posting of data after the email field was changed, and then comparing the list of all forms partially submitted against completed carts to determine which were incomplete.
You can save the partial form data in localStorage. Then, when another page is loaded, you could check for the presence of that data and AJAX it to the server, deleting it from localStorage on success. Or you might be able to just use that data in JavaScript, without involving the server, but that depends on your setup.
<body onbeforeunload="return ('You will lose all your data')" onunload="alert('You have gone away!')">
</body>
Onbeforeunload uses for alert box. Onunload for anything else.
You can technically fire off an ajax event, but there is no guarantee that it will complete before the page is actually reloaded.

How to do nice and simple file uploading in javascript?

All I want is:
select a file
small progress bar (unless it is not simple)
fail/success confirmation on client side
trigger action on server side.
all that without page reloading
Except that, the simpler the better.
Snippet would be most welcome.
There are plenty of scripts and tutorials around. Check for example http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Apparently that's not as trivial as one might think, since you can't just take the body of a form, containing an <input type='file'/> tag, and submit that.
But you can submit the form with a target of another <iframe/> and then poll the server with a XMLHttpRequest object for status updates, that however, requires that your sever-side script, that handles the upload, does so in a asynchronous manner, otherwise you will only get a status update once the file has been fully uploaded, not the kind of progress status updates you want. I think this is a challenge for most web frameworks to date, but I have never actually had any reason to dig into it. Sounds fun though...
If you just want to submit the file, independently of the actual form, you'll do the same, but you don't have to worry about the progress status updates.
What you can do, is to replaces the <input type='file'/> once the upload completes, with a <input type='hidden'/> containing the server-side ID of the recently uploaded file. That way you'll know when the user hits save, what files you'll want to actually save.
That hidden thing can also be a checkbox, which would let you undo a file upload, by simply unchecking that checkbox before hitting save.
File uploads using the XMLHttpRequest object is not possible in all browsers (only Firefox and Safari/Chrome support it), so for a cross-browser implementation use the <iframe> trick.
If you want a real XHR file upload, I have written an extended article on how to do it in Firefox 3. It's so low level that you actually have to build the actual HTTP request from JavaScript strings.
Maybe GearsUploader will fit.

Is there a way to detect the start of a download in JavaScript?

In our current project we are providing a PDF download that can be customized by the user through an HTML form he submits. It takes several seconds to dynamically generate the PDF and I'd like to visualize this, e.g. by disabling the submit button until the download starts. Unfortunately, I couldn't find a way to detect when the download starts*. So I wouldn't know when to re-enable the submit button.
I already tried to specify an IFrame as the target of my HTML form, hoping that the onload event would be triggered. It is not, however -- probably because the PDF is sent with a "Content-disposition: attachment" header and it is not actually loaded into the IFrame.
The only solution I can think of right now involves generating the PDF to a temporary file on the server, which I would like to avoid.
*)Let me clarify this: I wouldn't need to know if the download was finished or even if it was really started. I'd like to detect the point at which the browser will ask the user whether to open or to save the file. I guess this happens when the browser receives the HTTP header.
If I was you I would do an AJAX call to the server with the information, generate the file, then return the file name/id/whatever back to the javascript, which then makes window.location something like download.php?id=x (but the file was already generated, so it is just setting the headers and reading it out) at which point you can re-enable the submit.
What you want is to be able to detect when the size of the downloaded file changes from 0 to a positive value. As far as I know it is impossible to do that with javascript - you need a plug-in that can access the client's file system.
A recommended work around: Create a session per download. Have the client poll the server about the status of the download. This could be "non existed", "not started", "started", "finished". You need some server's side work to persist and update the status of the download plus an AJAX framework.
The simplest solution would be to estimate the time (generously) and do it that way. It's a hack, but it gives the desired effect. The other option might be to submit the form with a callback using Ajax to submit the form and have the generator return details to the calling page. http://www.jquery.com/ might be a good place to start for that option.

Categories

Resources