简体   繁体   中英

How to login to a website using javascript?

I am trying to login to a website through java script. I have found the login form on the website and I'm not sure what to do from here.

I have added value ="myemail" and value ="mypass" while inspecting the code and it has logged me in. I am confused on how I would implement a java script function to add to mu own code.

<input name="email" id="emailForSignIn" class="txt-input email float-label ctHidden" type="email" aria-required="true">

<input name="password" id="passwordForSignIn" autocomplete="off" class="txt-input password float-label" type="password" aria-required="true">


In order to 'login' to a website via Javascript you must provide an action to your form.

The form should be setup to redirect you to the next page.

However, user authentication is something that you should learn when you have more experience with Javascript. There are third-party services you can use, or you can work on the back-end yourself. Judging by your question I suspect you are learning the basics of JS.

You could do it by using ajax: https://api.jquery.com/jquery.ajax/

You dont need jQuery but it will make things alot easier.

$.ajax({
    type: "POST",
    url: 'login.php', // script to do the actual authentication, set session etc.
    data: {
        username: 'foo', // get element value of username here
        password: 'bar', // get element value of password here
    },
    success: function(data) {
        // process result
    },
});

Technically you are not logging in via JS but you use JS to not reload the entire page.

If you want a plain JS-Login, you will need to store credentials in your JS, which is possible but not a good idea:

Example (not persistens, you will have to log in every time you reload the page):

 var loggedIn = false; function authenticate() { var password = document.getElementById('password').value; loggedIn = login(password); status(); } function login(password) { var storedPassword = '123'; return password == storedPassword; } function status() { if(loggedIn) { console.log('You are in :)'); } else { console.log('You are not in :('); } }
 <input type='password' value='' id='password'> <input type='button' onclick='authenticate()' value='login'><br/> <small>Try 123 :D</small>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM