接上一篇文章,我们在创建好telegram机器人后,开始开发小游戏或者mini App,我们有个需求是需要判断用户是在手机端还是PC端打开的。
因为是tg内打开,所以无法直接去获取设备是手机还是PC(后面发现还是有方法的),这里介绍下我这里用到的方法。
User Agent 判断 当用户通过 WebApp 打开 mini app 时,可以通过 navigator.userAgent 来判断用户所使用的设备类型。userAgent 会提供关于浏览器、操作系统等信息。Telegram mini app 中,通过 User Agent判断设备类型的代码通常应该放在 mini app 初始化时执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <html > <head >     <title > Telegram Mini App</title >  </head > <body >     <script >          document .addEventListener ("DOMContentLoaded" , function (             const  userAgent = navigator.userAgent .toLowerCase ();             const  isMobile = /mobile|android|iphone|ipad|phone/i .test (userAgent);             if  (isMobile) {                 console .log ('手机端' );             } else  {                 console .log ('PC电脑端' );             }         });      </script > </body > </html > 
这样你就可以获取到是在手机端还是PC端打开的啦。
cocosCreator中使用 我们的游戏是使用cocosCreator开发的,导出web-mobile后,在index.html中加入上面代码,设置一个全局参数,比如window.Device。cocosCreator中直接调用该参数就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <html > <head >     <title > Telegram Mini App</title >  </head > <body >     <script >          document .addEventListener ("DOMContentLoaded" , function (             const  userAgent = navigator.userAgent .toLowerCase ();             const  isMobile = /mobile|android|iphone|ipad|phone/i .test (userAgent);             if  (isMobile) {                 console .log ('手机端' );                 window .Device  = "mobile" ;             } else  {                 console .log ('PC电脑端' );                 window .Device  = "Desktop" ;             }         });      </script > </body > </html > 
示例ts代码:
1 2 const  paramA = window ['Device' ];console .log ('参数 Device:' , paramA);