James
James

Reputation: 1501

Automate Log In on Website (Autofill and Submit)

I am trying to visit a website and log in automatically.

After this, I want to return whether or not this was a success or failure, but I can't get it to work. The page loads blank and nothing happens.

Note: I have deliberately greyed out the URL.

Below is my attempt,

<HTML>
<HEAD>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<TITLE>Login</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>

<script type="text/javascript">
    $(document).ready(function () {
            runLogin();
        });

    function runLogin(){
        alert("start");

        if (window.location.indexOf("url") > -1) {
                jQuery("#j_username").val("username");
                jQuery("#j_password").val("password");
                jQuery("#loginForm").submit();
            }
    }
</script>

Upvotes: 1

Views: 160

Answers (2)

castletheperson
castletheperson

Reputation: 33466

It's loading a blank page because your back-end script isn't redirecting back to the page you started on. One option is to send the current webpage URL as an extra field to the login form so that it can redirect back after it has logged in. This will require you to refactor your back-end code so that it can handle this extra information (not really possible if you're using j_security_check). Another option is to make an AJAX request to your login page so that it doesn't actually redirect the page, it just submits the form quietly and then JS handles the response.

If you want to add the URL of the current page to the login request, do this:

function runLogin() {
    if (window.location.indexOf("url") > -1) {
            jQuery("#j_username").val("username");
            jQuery("#j_password").val("password");
            jQuery("#loginForm").append(
                '<input type="hidden" name="url" value="'+window.location.href+'"/>'
            );
            jQuery("#loginForm").submit();
    }
}

If you want to use AJAX to send a login request:

function runLogin() {
    var $form = $("#loginForm");
    $.post($form.attr("action"), $form.serialize(), function(data) {
        // login successful/unsuccessful message displays
        // depending on what "data" contains
    });
}

Upvotes: 0

andreew123
andreew123

Reputation: 36

If you want to test your login form, use Protractor or other e2e test framework, but this way does not seem very safe.

http://angular.github.io/protractor/

Upvotes: 1

Related Questions