Category Archives: jQuery

HTTPAuth Logout in Chrome, Firefox and IE with jQuery

I’ve recently setup a site which has multiple users and uses HTTP Auth. I wanted to implement a Logout button to allow switching users. Turns out, there’s no easy programmatic way to stop a browser from remembering your username and password.

Being a client feature it must be done in JavaScript, and since I’m using jQuery on the page I’ve utilised that. It should be easy enough to translate this into vanilla JavaScript, feel free to send me another version and I’ll post it alongside.

After much reading I came across this post: which works well in Firefox and Internet Explorer, below is my modified version which also works in Chrome. (I’ve only tested this on the latest versions of these browsers).

I’ve basically added a fallback which should work everywhere, all be it in a not entirely beautiful fashion (it doesn’t work in the background, and forces an authentication popup where you might prefer to redirect to another page).This refreshes the page to request another login, but you could easily adapt it to send the user to a different page.

    $('#user_logout').on('click', function(e){
        // HTTPAuth Logout code based on:
        try {
            // This is for Firefox
                // This can be any path on your same domain which requires HTTPAuth
                url: "/any/path",
                username: 'reset',
                password: 'reset',
                // If the return is 401, refresh the page to request new details.
                statusCode: { 401: function() {
                    document.location = document.location;
        } catch (exception) {
            // Firefox throws an exception since we didn't handle anything but a 401 above
            // This line works only in IE
            if (!document.execCommand("ClearAuthenticationCache")) {
                // exeCommand returns false if it didn't work (which happens in Chrome) so as a last
                // resort refresh the page providing new, invalid details.
                document.location = "http://reset:reset@" + document.location.hostname + document.location.pathname;