Javascript 如何让两个js函数一起工作?

Javascript 如何让两个js函数一起工作?,javascript,function,parsing,web,autologin,Javascript,Function,Parsing,Web,Autologin,我想使用JS登录到一个网站,然后将URL更改为同一网站上的不同页面。我有两个功能,它们各自工作,但不是一起工作。我不知道如何编写/组织这些函数,使它们可以一个接一个地执行 function autoLogin() { document.getElementById("userName").value = "username"; document.getElementById("pwd").value = "password"; document.getElementById("LoginBut

我想使用JS登录到一个网站,然后将URL更改为同一网站上的不同页面。我有两个功能,它们各自工作,但不是一起工作。我不知道如何编写/组织这些函数,使它们可以一个接一个地执行

function autoLogin() {

document.getElementById("userName").value = "username";
document.getElementById("pwd").value = "password";
document.getElementById("LoginButton").click();

}
autoLogin();

function nextPage() {
window.location.replace("https://www.website.com/page2");
}

nextPage();

您始终可以向第一个函数添加回调,以调用传入的第二个函数。例如:

function autoLogin(callback) {

    document.getElementById("userName").value = "username";
    document.getElementById("pwd").value = "password";
    document.getElementById("LoginButton").click();
    callback();
}

function nextPage() {
    window.location.replace("https://www.website.com/page2");
}

autoLogin(nextPage);
这将取决于您的登录按钮,但在后台同步执行某些操作。如果您想等待登录中发生的任何事情首先发生,您可能只想调用使用登录按钮调用的函数,而不是实际触发单击。然后您可以将回调传递到该函数中

假设您的LoginButton click调用了一个名为doLogin()的函数。将回调添加到该函数中,然后在调用之前检查它在调用时是否存在,以保持向后兼容性

function doLogin(callback) {
   // get username and password and then asynchronously login

   if (callback) {
      callback();
   }
}

function autoLogin(callback) {

    document.getElementById("userName").value = "username";
    document.getElementById("pwd").value = "password";
    doLogin(callback);
}

function nextPage() {
    window.location.replace("https://www.website.com/page2");
}

autoLogin(nextPage);  //This calls autoLogin, which passes the callback to doLogin.                  
                      //Once doLogin is done, it calls nextPage.

我猜下面的内容将带你进入新的一页

document.getElementById("LoginButton").click();
因此,不会调用nextPage()


也许,对于第2页上加载的脚本,您可以在页面加载时有条件重定向到第2页

我的猜测是,当您单击“登录”按钮时,浏览器会离开您所在的页面,因此
nextPage
永远不会被调用您正在描述服务器将在您提交表单的脚本中管理的功能。