0

Is there a way to write a google apps script so the user clicks on the login button, a second browser window opens to google form.

Basically, I have created userID and PW pages using index.html. What I was hoping to do is that when the user clicks on the login button, a google form is opened in the second browser window.

I would like to use the code suggested by (OaklandFanatic) in the Google Apps Script to open a URL however, I have been looking at the code for hours but I can not get it to work.

I am very new at google script and javascript so any help would be greatly appreciated:

Below is my index.html*************

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      function AddRow()
    {
      var firstName = document.getElementById("firstName").value;
      var lastName = document.getElementById("lastName").value;
      var center = document.getElementById("center").value;
      var emaill = document.getElementById("emaill").value;
      var phone = document.getElementById("phone").value;
      var passwordd = document.getElementById("passwordd").value;
      // var usernamee = document.getElementById("usernamee").value;
     
      
      
      if (firstName==""|| lastName==""||center==""|| emaill==""|| phone==""||passwordd=="") {
        return false;
      }
      else {
      google.script.run.AddRecord(firstName,lastName,center,emaill,phone,passwordd);
      document.getElementById("page2_id1").className = "page2_id1-off";
      document.getElementById("page3_id1").className = "page3_id1";
     }
    }

     function LoginUser()
    {
    // var username = document.getElementById("username").value;
    var email = document.getElementById("email").value
    var password = document.getElementById("password").value;
    google.script.run.withSuccessHandler(function(output) 
    {
      if(output == 'TRUE')
      {

          function onSuccess(url) 
         {
           var a = document.createElement("a"); 
           a.href = url;
           a.target = "_blank";
           window.close = function () 
           {
             window.setTimeout(function() 
             {
                google.script.host.close();
             }, 9);
           };
        if (document.createEvent)
         {
            var event = document.createEvent("MouseEvents");
            if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) 
            {
               window.document.body.append(a);
            }                        
            event.initEvent("click", true, true); 
            a.dispatchEvent(event);
         } else {
        a.click();
      }
      close();
    }

    function onFailure(url) {
      var div = document.getElementById('failureContent');
      var link = '<a href="' + url + '" target="_blank">Process</a>';
      div.innerHtml = "Failure to open automatically: " + link;
    }
    google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
        // Logger.log("output" + output);
        //document.getElementById("displayusername").innerHTML = output;
        //document.getElementById("page1_id1").className = "page1_class1-off";
        //document.getElementById("page4_id1").className = "page4_id1";    
      }
      else if(output == 'FALSE')
      {
        document.getElementById("errorMessage").innerHTML = "Invalid data";     
      }    
    }).checkLogin(email, password);
    }
    
function function1(){
    document.getElementById("page1_id1").className = "page1_class1-off";
    document.getElementById("page2_id1").className = "page2_id1";
}
 
function function3(){ 
  document.getElementById("page3_id1").className = "page3_id1-off";
  document.getElementById("page1_id1").className = "page1_id1"; 
}

  </script>
  <style>

/*page1*/
.page1_class1-off{
    display: none;
  }


/*page2*/
.page2_class1{
    display: none;
  }

.page2_id1-off{
    display:none;
}

/*page3*/
.page3_class1{
    display:none;

}
.page3_id1-off{
    display:none;
}

/*page4*/
.page4_class1{
    display:none;

}
.page4_id1-off{
    display:none;
}

input[type=text]:hover{
        border-bottom:2px solid black;
      }
input[type=number]:hover{
        border-bottom:2px solid black;
      }
input[type=password]:hover{
        border-bottom:2px solid black;
      }

.user{
display: inline-block;
width: 75px;
height: 75px;
border: 8px solid black;
border-radius: 50%;
position: relative;
overflow: hidden;
box-sizing: border-box;
}

/*the head/*/
.user::before{
content: '';
display: inline-block;
width: 24px;
height: 24px;
background: black;
border-radius: 50%;
position: absolute;
left: calc(50% - 11px);
top: 10px;
}

/*the body*/
.user::after{
content: '';
display: inline-block;
width:50px;
height:40px;
background: black;
border-radius: 50%;
position: absolute;
left: calc(50% - 24px);
top: 39px;
}

</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <br><br>
<!--page1-->
<center>
 <div class="page1_class1" id="page1_id1" style="background:none;border:2px solid gray;border-radius: 20px;width: 250px;padding-top: 10px;padding-bottom: 20px;padding-left: 20px;padding-right: 20px;"> 
    <h1>Login Form</h1>
    <br>
    <input type="text" id="email" placeholder="EmailAddress" required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;"/><br>
    <br>
    <input type="password" id="password" placeholder="Password" required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;"/>
    <br><span id="errorMessage" style="color: red" ></span><br>
    <input type="submit" value="Login" onclick="LoginUser()"  style="float: right;padding-top: 1px;padding-bottom: 1px;padding-left: 10px;padding-right: 10px;font-size: 0.9em;font-weight:bold;" /><br>
    <br>
    <b>If you don't have an account,</b><input type="button" onClick="function1()" value="Create New" style="margin-top: 5px;font-weight:bold;" />
 </div>

<!--page2-->
<div class="page2_class1" id="page2_id1" style="background:none;border:2px solid gray;border-radius: 20px;width: 250px;padding-top: 10px;padding-bottom: 20px;padding-left: 20px;padding-right: 20px;">
 <h1>Create Account</h1>
    <input type="text" id="firstName" placeholder="First Name" required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;"/><br>
    <br>
    <input type="text" id="lastName" placeholder="Last Name" required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;"/><br>
    <br>
    <input type="text" id="center" placeholder="Center Name" required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;"/><br>
    <br>
     <input type="text" id="emaill" placeholder="Email" required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;"/><br>
    <br>
    <input type="tel" id="phone" placeholder="Phone no." required style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size:0.9em ;width: 50%;font-weight:bold;" /><br>
    <br>
    <input type="password" id="passwordd" placeholder="Create password" style="border-top: none;border-right: none;border-left: none;outline: none; text-align: center;font-size: 0.9;width: 50%;font-weight:bold;" /><br>
    <br>
    <b style="color:red;">Password must contain letters and numbers. It will not work without letters and numbers.</b><br><br>
    <input type="submit" value="Create" onclick="AddRow()" style="float: right;padding-top: 1px;padding-bottom: 1px;padding-left: 10px;padding-right: 10px;font-size: 0.9em;font-weight:bold;" />
    <br>
</div>

<!--page3-->
 <div class="page3_class1" id="page3_id1" style="background:none;border:2px solid gray;border-radius: 20px;width: 250px;padding-top: 10px;padding-bottom: 20px;padding-left: 20px;padding-right: 20px;"><center>
    <h2> Your account has been successfully created. Login to your account</h2>
    <input type="submit"  onClick="function3()" value="Login" style="font-weight:bold;"><br>
 </div> 

<!--page4-->
<div class="page4_class1" id="page4_id1" style="background:none;border:2px solid gray;border-radius: 20px;width: 250px;padding-top: 10px;padding-bottom: 20px;padding-left: 20px;padding-right: 20px;" ><center>
    <br>
   <!-- <h2>Hi <b id="displayusername" style="color:red;"></b>!</h2>-->
    <div class="user"></div>
    <div id="failureContent"></div>
    <!--<h2> You are successfully logged in.</h2>-->
    <h2>**************</h2>
    <br>
  </div>
</center>
  </body>
</html>

** code

Below is my code.gs:**********

function doGet(e) {
  var x = HtmlService.createTemplateFromFile("index");
  var y = x.evaluate();
  var z = y.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
  return z;
}

function checkLogin(email, password) {
  var url = 'enter spreadsheet url';
  var ss= SpreadsheetApp.openByUrl(url);
  var webAppSheet = ss.getSheetByName("DATA");
  var getLastRow =  webAppSheet.getLastRow();
  var found_record = '';

  webAppSheet.activate();

  for(var i = 2; i <= getLastRow; i++)
  {
   if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == email.toUpperCase() && 
     webAppSheet.getRange(i, 2).getValue().toUpperCase() == password.toUpperCase())
   {
     found_record = 'TRUE';
   }    
  }
  if(found_record == '')
  {
    found_record = 'FALSE'; 
  }
  
  return found_record;
  
}
function AddRecord(firstName, lastName, center, emaill, phone, passwordd) {
  var url = 'enter spreadsheet url';
  var ss= SpreadsheetApp.openByUrl(url);
  var webAppSheet = ss.getSheetByName("DATA");
  var daysCompleted = 00
  webAppSheet.activate();
  webAppSheet.appendRow([emaill,passwordd,firstName,lastName,center,phone,daysCompleted]);
  
}

function getUrl(email, password) 
{
  var url = 'enter spreadsheet url';
  var ss= SpreadsheetApp.openByUrl(url);
  var webAppSheet = ss.getSheetByName("DATA")
  var getLastRow =  webAppSheet.getLastRow();
  var daysCompleted;
  

  Logger.log ("email from index.html: " + email);
  Logger.log ("password from index.html: " + password);

  webAppSheet.activate();

  for(var i = 2; i <= getLastRow; i++)
  {
   if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == email.toUpperCase() && 
     webAppSheet.getRange(i, 2).getValue().toUpperCase() == password.toUpperCase())

     daysCompleted = webAppSheet.getRange(i, 7).getValue()
     Logger.log ("daysCompleted in getUrl function:" + " " + daysCompleted);
   {
     if ((daysCompleted = daysCompleted + 1) == 1) 
     {
       Logger.log("daysCompleted inside If statement:" + " " + daysCompleted);
       return  'enter google form url';
     }
    
   }    
  } 
}



// Logger Workaround Function *******************************************************************
(function (__g__) {

  // This will replace Logger. If set to false, you'll have to initialize the library with call to ReplaceLogger()
  const auto = true;
  
  // If for some reason you want to use a different spreadsheet each time, or for just one execution, can set reset to true
  const reset = false;
  
  // Shouldn't need to change this
  const PROP = '__getLogger__.id';
  const PROPSERVICE = PropertiesService.getUserProperties;
  
  function _getErrorObject(){
    try { throw new Error('fake error') } catch(err) { return err; }
  }
  
  function _getLineNumOfCallee() {
    const err = _getErrorObject();
    const target_stack = err.stack.split("\n").slice(5);  // 5 because that's where it is in the stack
    //const index = caller_line.indexOf("at ");
    return '→ ' + target_stack.join("\n");
  }

  class SS {
    constructor (id=null, sheetName) {
      this.id = id;
      this.sheetName = sheetName;
      this.spreadsheet = null;
      if (this.id === null)
        this.create();
      else
        this.open();
    }
    
    static new (...args) {
      return new SS(...args);
    }

    create() {
      const [rows, cols] = [3, 2];
      this.spreadsheet = SpreadsheetApp.create('Logger', rows, cols);
      this.sheet = this.spreadsheet.getSheetByName(this.sheetName);
      this.id = this.spreadsheet.getId();
      this.sheet.getRange(1, 1, 1, 3).setValues([['Output', 'Location', 'Date']]);
      this.first();
    }

    open() {
      this.spreadsheet = SpreadsheetApp.openById(this.id);
      this.sheet = this.spreadsheet.getSheetByName(this.sheetName);
      this.id = this.spreadsheet.getId();
      this.first();
    }
    
    first () {
      // draw a line whenever we've opened the file
      this.sheet.getRange(2, 1, 1, 3).setBorder(true, null, null, null, null, null, '#000000', SpreadsheetApp.BorderStyle.SOLID);
    }

    prepend(text) {
      // first column of row should contain plaintext, or stringified version of itself
      const cell_a = (function (txt) {
        if (text instanceof String || typeof text === 'string')
          return text;
        else 
          return JSON.stringify(text, null, 4);
      })(text);  

      const cell_b = _getLineNumOfCallee();
      
      // second column of row should contain date in easy to read format
      const cell_c = (new Date()).toLocaleString();
      
      const data = [ [cell_a, cell_b, cell_c] ];
      
      this.sheet.insertRowsAfter(1, data.length);
      this.sheet.getRange(2, 1, data.length, data[0].length).setValues(data);
    }

    get url () {
      return this.spreadsheet.getUrl();
    }

  }

  let ssObj = null;
  const state = {};

  const __Logger__ = __g__.Logger;

  Logger_ = function (strings, ...values) {
    const text = strings.map( (string, index) => `${string}${values[index] ? values[index] : ''}` );
    ssObj.prepend(text.join(''));
  };
  Logger_.log = function (text) {
    ssObj.prepend(text);
  };

  __g__.ReplaceLogger = function (id=null, sheet='Sheet1') {
    [state.id, state.sheet] = [id, sheet];

    if (state.id === null) {
      // pull in from properties, if available, remains null if not
      const props = PROPSERVICE();
      state.id = props.getProperty(PROP);
    }

    // either opens existing or creates new
    ssObj = SS.new(state.id, state.sheet);

    if (state.id === null) {
      state.id = ssObj.id;
      const props = PROPSERVICE();
      props.setProperty(PROP, state.id);
    }

    // Output with link
    Logger.log("Find logs at the following url:");
    Logger.log(`\n${ssObj.url}\n`);
    __g__.Logger = Logger_;
  };

  __g__.UnreplaceLogger = function () {
    __g__.Logger = __Logger__;
  };
  
  if (reset) {
    PROPSERVICE().deleteProperty(PROP);
  }

  if (auto) ReplaceLogger();
})(this);

//************************************************************ */

0 Answers0