While reuploading a bunch of old ImageShack images to imgur, I noticed something funny: sometimes, after uploading an image from the web, I would no longer be able to paste anything into the edit box. A bit more investigation revealed that the following steps are needed to reproduce this bug:
In the SE post editor, click the button to upload an image.
In the image upload dialog, click "You can also provide a link from the web."
Make sure the URL input box has the focus, and then close the dialog by pressing Esc.
Alternatively, on Firefox, type or paste an image URL into the text box and submit the form by pressing Enter. (This does not seem to trigger the bug on Chrome; thanks, Chris Jester-Young.)
Either way, the bug will not be triggered if you close the dialog by clicking something outside the URL input box, like the submit button or the close button.
Once back in the Markdown editor, try pasting something into the edit box. Nothing will happen.
Reopening and closing the image upload dialog will make paste work again.
Apparently, what happens is that the image upload dialog installs its own paste event handler onto the <body>
element, in order to let you paste images into the dialog to upload them. This handler should be removed when the dialog closes, but the steps above break this, leaving the handler in place.
Why? Well, it turns out that the dialog itself removes the paste event handler when the URL entry box gains focus (so that you can paste an URL into it, of course), and adds it back when the box loses focus. But if you submit the upload form while the URL entry box still has focus, then the blur event handler on the box runs only after the dialog has closed. Thus, the sequence of events (no pun intended) runs like this:
- Open upload dialog. Paste event handler is added.
- URL entry box gets focus. Paste event handler is removed.
- Close upload dialog by pressing Esc. Paste event handler is (again, redundantly) removed.
- URL entry box loses focus as it disappears from the page. Paste event handler is added back. (Oops!)
How do we fix this? Well, I see a bunch of ways:
- Have the code that closes the popup remove the
blur
event handler from the URL input, so that it cannot run any more, before removing the popup from the DOM. - Have the
blur
event handler itself check a flag to see if we've already closed the dialog, and if so, not add back thepaste
handler on<body>
. - Have the
paste
handler itself check if the upload dialog is present, and if not, do nothing and let the event propagate.
Any of these should work. Heck, you could implement all of them, just to make sure. :)