Skip to main content
 首页 » 编程设计

google-apps-script之如何使用 Google App Script 检测移动用户

2024年11月24日16dudu

我正在为一个组织开发一个应用程序,他们经常使用 Google 表格,其中大约一半使用移动表格应用程序。

现在,如果它们更改了某些单元格的值,我想要一个 UI 警报。这适用于桌面浏览器(Chrome PC、Firefox 等),但不适用于移动应用程序。我知道它行不通,而且它弄乱了我的代码,因为在警报之后还有一些其他代码要执行,例如:

function showAlert(message) { 
  var ui = SpreadsheetApp.getUi(); 
 
  var result = ui.alert( 
     'Please confirm', 
     message, 
      ui.ButtonSet.YES_NO); 
 
  // Process the user's response. 
  if (result == ui.Button.YES) { 
    // User clicked "Yes". 
    return true; 
  } else { 
    // User clicked "No" or X in the title bar. 
    return false; 
  } 
} 
 
function Test(){ 
   if(showAlert("Are you sure?")){ 
       Logger.log("User says yes"); 
   }else{ 
       Logger.log("No"); 
   } 
} 

Google App Script 中一个函数的执行时间是 300 秒,虽然没有显示警报,但计时器继续等待用户输入。结果是脚本超时而没有执行其他代码,如下所示:



如果有一种方法可以检测用户是否在移动设备上,我可以跳过警报以便执行代码,就像这样
function Test(){ 
    if( user not on mobile && showAlert("Are you sure?"){ 
         Logger.log("User says Yes"); 
    } 
} 

这可能吗?或者我可以等待 1 分钟,如果用户没有响应,跳过警报并继续其他代码?

请您参考如下方法:

简短的回答,这是不可能的。如果您使用的是 web 应用程序而不是 SpreadsheetsApp.getUI(),那么答案很长。

这意味着您必须重写整个应用程序,因此请记住这一点。

如果您使用的是网络应用程序,您可以使用 reference并修改它以适应 your needs像这样:

UserBrowserAgent.hmtl

<!DOCTYPE html> 
<html> 
  <head> 
    <base target="_top"> 
  </head> 
  <body> 
    <div id="response"> 
    </div> 
    <script> 
      if (/Mobi/.test(navigator.userAgent)) { 
        // mobile! 
        document.getElementById("response").textContent = "mobile"; 
      } else { 
        // something else 
        document.getElementById("response").textContent = "other"; 
      } 
    </script> 
  </body> 
</html> 

调用页面的 Web 应用程序
function doGet() { 
  return HtmlService.createTemplateFromFile("UserBrowserAgent").evaluate().setTitle("User Agent - Google Apps Script"); 
} 

希望这可以帮助!