新手搭建含Google Sign-In的网站遇第29行Unexpected token报错求解
报错核心原因
Unexpected token报错的触发根源是 将HTML标签直接嵌入在了<script>标签内部。
浏览器解析<script>包裹的内容时,会将块内所有字符识别为JavaScript语法,当碰到块内的<a>链接的尖括号结构时,会判定为非法JS语法,直接触发解析失败。
修正步骤
- 把错位夹在JS代码中间的登出链接,移动到
<script>标签外部的<body>正常渲染区,所有HTML元素不能直接放置在<script>块内部 - 确保
<script>块内仅存放纯JavaScript逻辑代码,修正后的代码结构可参考:
<meta name="google-signin-scope" content="profile email"> <meta name="google-signin-client_id" content="936710688088-5fupofi0g9i8nb2ua7tftc9gkt4ndhue.apps.googleusercontent.com"> <script src="https://apis.google.com/js/platform.js" async defer> </script> <title></title> </head> <body> <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> <!-- 登出链接放置在script标签外部 --> <a href="#" onClick="signOut();">Sign out</a> <script> function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); var id_token = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); } function signOut() { var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); } </script> </body> </html>
- 删除代码末尾多余的
```文本字符,这类直接出现在页面上的无效文本同样会触发解析异常
同类报错排查技巧
碰到Unexpected token类的语法报错时,优先校验报错位置附近的代码边界:
- 检查HTML标签是否错位嵌入在JS、CSS代码块内部
- 核对相邻代码的括号、引号闭合数量是否完全匹配
- 确认代码块内没有混入和当前语法规则不兼容的其他文本
内容的提问来源于stack exchange,提问作者Eli
相关产品推荐
相关产品推荐

