0

客观的:

在 google 应用程序脚本中构建一个 prechat 表单,以便可以在 google 站点中将其用作 web 应用程序,这样它就可以获取用户的姓名、姓氏、电话和电子邮件,并将这些参数传递给freshchat javascript 片段,以便在启动聊天时,用户的信息可以在freshchat工具中看到。

索引.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <title>Chat form</title>
  </head>
  <body>
    <h1>Chatea Con Nosotros</h1>
    <form>
      <input type="text" id="fname" placeholder="Nombre">
      <input type="text" id="lname" placeholder="Apellido">
      <input type="text" id="email" placeholder="Email">
      <input type="text" id="phone" placeholder="Teléfono">
      <input type="button" value="Iniciar Chat" id="btnStartChat"/> 
    </form>
    <?!= include("index_js"); ?> 
  </body>
</html>

index_js

<script>
  //global variables
  var ffname = '';
  var flname= '';
  var femail = '';
  var fphone = '';

  //freshchat code starts ------------------------
  function initFreshChat() {
    window.fcWidget.init({
      token: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
      host: "https://wchat.freshchat.com",
      open: true,
      externalId: "john.doe1987",     // user’s id unique to your system
      firstName: ffname,              // user’s first name
      lastName: flname,                // user’s last name
      email: femail,    // user’s email address
      phone: fphone,            // phone number without country code
      phoneCountryCode: "+1"          // phone’s country code
    });
  }
  function initialize(i,t){
    var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e. async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))
  }function initiateCall(){
    initialize(document,"Freshdesk Messaging-js-sdk")
  }
//freshchat code ends ---------------------  

  document.getElementById("btnStartChat").addEventListener("click", getFormValues);
  
  function getFormValues(){
    try{
      ffname = document.getElementById("fname").value;
      flname = document.getElementById("lname").value;
      femail = document.getElementById("email").value;
      fphone = document.getElementById("phone").value;
      window.addEventListener("load", initiateCall());
    }
    catch(e){
      console.log('error here: ' + e.message);
    }
  }

</script>

代码.gs

function doGet(){
  var page = HtmlService.createTemplateFromFile('index');
  return page.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).setHeight(400).setWidth(100);
  //return page.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

//funtion to append other files to htmlservice file
function include(filename){
  //return the content of an html file
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

问题:

问题是我不知道如何让freshchat函数只有在我用表单中的输入数据填充全局变量后才能启动。如果我在该区域内手动输入数据,window.fcWidget.init({...})它会很好地工作,但我不确定如何在单击按钮时以编程方式进行操作。

咨询的消息来源:

谢谢你。

4

2 回答 2

1

我假设大部分代码都是来自freshchat的逐字记录?我无权访问 Freshchat 帐户,但在此行触发了连接:

window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);

所以这里发生的基本上是一个 if 语句(一个三元 if https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)所以如果一个监听器可以添加到窗口,然后添加事件侦听器,如果没有,则将事件附加到窗口(这可能是适应不同类型和版本的浏览器的一种方式,对于更现代的浏览器可能不需要)。更多信息:addEventListener 和 attachEvent 有什么区别?

因此,如果您想等到用户输入详细信息,您需要将其移动到您正在检查这些详细信息是否存在的位置:

function getFormValues(){
    try{
      ffname = document.getElementById("fname").value;
      flname = document.getElementById("lname").value;
      femail = document.getElementById("email").value;
      fphone = document.getElementById("phone").value;
      window.addEventListener("load", initiateCall());
    }
    catch(e){
      console.log('error here: ' + e.message);
    }
  }

您实际上并不需要 try/catch 来获取表单信息,但您应该检查它是否是有效的输入(即电子邮件地址的格式正确,并且给出了名称并且没有留空)。

您可能还希望在用户按下按钮后禁用该按钮,并在出现错误时重新启用它,以防止对 API 的过度调用(您可能需要为此付费)。防止这种情况发生的另一种方法是为用户提供动画以显示在他们等待聊天开始时正在发生某些事情,但这些超出了本问题的范围。

于 2022-01-26T14:57:14.680 回答
1

我只是按照第一个链接的说明定制了标签。它可以在 Google 协作平台嵌入<>框中工作。

您可能缺少的一件事是这种小部件具有多个安全层,因此可能不支持使用自定义 HTML 表单(引用的资源不包括使用它们的说明)。

代码.gs

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('index');
}

索引.html

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>
<script src="https://snippets.freshchat.com/js/fc-pre-chat-form-v2.min.js"></script>
<script>
  var preChatTemplate = {
    //Form header color and Submit button color.
    mainbgColor: '#0aa4db',
    //Form Header Text and Submit button text color.
    maintxColor: '#fff',
    //Chat Form Title
    heading: 'GadgetGod',
    //Chat form Welcome Message
    textBanner: 'We can\'t wait to talk to you. But first, please take a couple of moments to tell us a bit about yourself.',
    //Submit Button Label.
    SubmitLabel: 'Start Chat',
    //Fields List - Maximum is 5
    //All the values are mandatory and the script will not work if not available.
    fields : {
      field1 : {
        //Type can be either text or title
        type: "title",
        //Label for Field Title, can be in any language
        label: "Nombre",
        //Field ID for Title
        fieldId: "title",
        //Required "yes" or "no"
        required: "yes",
        //Error text to be displayed
        error: "Please Enter a valid Title"
      },
      field2 : {
        //Type for Name - Do not Change
        type: "name",
        //Label for Field Name, can be in any language
        label: "Apellido",
        //Default - Field ID for Name - Do Not Change
        fieldId: "name",
        //Required "yes" or "no"
        required: "yes",
        //Error text to be displayed
        error: "Please Enter a valid name"
      },
      field3 : {
        //Type for Email - Do Not Change
        type: "email",
        //Label for Field Email, can be in any language
        label: "Email",
        //Default - Field ID for Email - Do Not Change
        fieldId: "email",
        //Required "yes" or "no"
        required: "yes",
        //Error text to be displayed
        error: "Please Enter a valid Email"
      },
      field4 : {
        //Type for Phone - Do Not Change
        type: "phone",
        //Label for Field Phone, can be in any language
        label: "Teléfono",
        //Default - Field ID for Phone - Do Not Change
        fieldId: "phone",
        //Required "yes" or "no"
        required: "yes",
        //Error text to be displayed
        error: "Please Enter a valid Phone Number"
      },
      field5 : {
        //Type for Dropdown
        type: "dropdown",
        //Label for Field Dropdown, can be in any language
        label: "Plan",
        //Field ID for Plan Dropdown
        fieldId: "plan",
        //Required "yes" or "no"
        required: "yes",
        //Error text to be displayed
        error: "Please select an option",
        //Options for the Dropdown field
        options: ['Sprout','Blossom','Garden','Estate','Forest']
      }
    }
  };
  window.fcSettings = {
    token: "WEB_CHAT_TOKEN",
    host: "https://wchat.freshchat.com",
    config: {
      cssNames: {
        //The below element is mandatory. Please add any custom class or leave the default.
        widget: 'custom_fc_frame',
        //The below element is mandatory. Please add any custom class or leave the default.
        expanded: 'custom_fc_expanded'
      }
    },
    onInit: function() {
      console.log('widget init');
      fcPreChatform.fcWidgetInit(preChatTemplate);
    }
  };
</script>
<script src="https://wchat.freshchat.com/js/widget.js" async></script>
<body>
  
</body>

</html>
于 2022-01-27T19:26:44.357 回答