Google Script: get values from input forms

2019-09-05 17:59发布

问题:

I implemented an authentication process using google scripts but with hard-coded data for username and password values from payload option and I can't find a way to get these values from the html page when user presses the Login button...

Is there a way to get this values from input fields to payload option?

Here is my code:

HTML:

  <body>
    <form>
        <fieldset class='login'>

            <div class="required">
                <label for="email">Email:</label>
                <input type="text" name="email" id="email" class="input-text" />
            </div>

            <div class="required">
                <label for="pass">Password:</label>
                <input type="password" name="pass" id="pass" class="input-password" />
            </div>
        </fieldset>

        <input type="submit" id="submit-btn" value="Login" name='Submit' class='btn'/>
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        $('#submit-btn').click(function() {
          google.script.run.login();
        });
    </script>
  </body>

Google Script:

function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('Menu')
      .addItem('Show sidebar', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('login')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setTitle('SDR Tag Governance')
      .setWidth(300);
  SpreadsheetApp.getUi()
      .showSidebar(html);
}

function login(){
  var endpoint = 'login';
  var url = 'https://example.com/api/'+endpoint;
  var payload = {
    'username' : 'email', //Add here the value from #email input
    'password' : 'pass' //Add here the value from #pass input
  }
  var headers = {
    'Connection':'keep-alive',
    'Content-Type':'application/json;charset=utf-8',
    'Accept':'application/json, text/plain, */*',
  }
  var options = {
    'method' : 'post',
    'headers' : headers,
    'payload': JSON.stringify(payload),
  };
  var urlResponse = UrlFetchApp.fetch(url, options);
  Logger.log(urlResponse);
}

I tried to add this code to the HTML page:

<script>
    $('#submit-btn').click(function() {
      google.script.run
        .withSuccessHandler(function(response) {
          return urlResponse;
        })
        .login({
           email: $('#email').val(),
           pass: $('#pass').val()
        });
    });
</script>

With GS function:

function login(email,pass){
  var endpoint = 'login';
  var url = 'https://example.com/api/'+endpoint;
  var payload = {
    'username' : email,
    'password' : pass
  }
  var headers = {
    'Connection':'keep-alive',
    'Content-Type':'application/json;charset=utf-8',
    'Accept':'application/json, text/plain, */*',
    'Cookie':'...',
  }
  var options = {
    'method' : 'post',
    'headers' : headers,
    'payload': JSON.stringify(payload),
  };
  var urlResponse = UrlFetchApp.fetch(url, options);
  Logger.log(urlResponse);
}

But it doesn't work...

回答1:

In your original HTML file you are not passing anything to the login() function in you .gs file. You can use jquery to grab those values.

<script>
    $('#submit-btn').click(function() {
      google.script.run
        .withSuccessHandler(function(response) {
          // this is where you handle the response from your Code.gs
        })
        .withFailureHandler(function(error) {
          console.log(error);
        })
        .login({
          email: $('#email').val(),
          pass: $('#pass').val()
        });
    });
</script>

EDIT: login function in gs file

function login(data){
  // i dont think you need this endpoint variable
  var endpoint = 'login';   
  var url = 'https://example.com/api/'+endpoint;

  // since you are passing in an object in the html, you can
  // access the properties of data
  var payload = {
    'username': data.email,
    'password': data.pass
  }

  // this is the same as your original
  var headers = {
    'Connection':'keep-alive',
    'Content-Type':'application/json;charset=utf-8',
    'Accept':'application/json, text/plain, */*',
    'Cookie':'...',
  }

  // are you sure you need to JSON.stringify the payload?
  // try just passing the payload object as is
  var options = {
    'method' : 'post',
    'headers' : headers,
    'payload': JSON.stringify(payload),
  };
  var urlResponse = UrlFetchApp.fetch(url, options);

  // Logger.log shows you what comes back
  // when that is fine change it to return urlResponse;
  // this will then get sent to the withSuccessHandler that is 
  // in your HTML file.
  Logger.log(urlResponse);
}