You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google文本转语音API调用报错:Identifier 'url'已声明的解决

解决Google文本转语音API调用中的Identifier 'url' has already been declared语法错误

问题情况

使用JavaScript调用Google文本转语音API已有一年多,近期突然触发语法错误:Uncaught SyntaxError: Identifier 'url' has already been declared(报错位置texttospeech.js:1)。脚本已正确引入,但因为语法错误完全无法执行——哪怕在脚本首行添加console.log也没有输出,仅能看到该错误提示。

排查过以下方向但均无效:

  • 将部分const替换为let
  • 验证OAuth2授权功能正常
  • 确认脚本未被重复加载
  • 排除JS压缩工具的影响

最终通过重写URL解析逻辑解决了问题。

错误根源

查看原脚本的URL解析部分,发现关键错误行:

const url = window.location.href;let url = window.location.href;

在同一作用域内连续用const和let重复声明了标识符url,这违反了JavaScript的变量声明规则,直接导致脚本在执行前就触发语法错误,所以首行的日志也无法输出。

原问题脚本的URL解析片段

console.log("BEFORE!")
// // Declare a variable to store the access Token
let accessToken

// Get the current WindowURL.
const url = window.location.href;let url = window.location.href;

function parseAccessTokenFromUrl(url) {
  // Get the current URL.
  const urlObject = new URL(url);

  // Get the hash fragment of the URL.
  const hashFragment = urlObject.hash;

  // Remove the leading `#` character from the hash fragment.
  const hashFragmentWithoutHash = hashFragment.substring(1);

  // Find the index of the `&token_type` parameter in the hash fragment.
  const tokenTypeIndex = hashFragmentWithoutHash.indexOf('&token_type');

  // Extract the substring of the hash fragment from the index of the `#access_token=` sign to the index of the `&token_type` parameter.
  const extractedAccessToken = hashFragmentWithoutHash.substring(hashFragmentWithoutHash.indexOf('#access_token=') + 14, tokenTypeIndex);

  // Assign the extracted access token to the global variable
  accessToken = extractedAccessToken;

}

解决后的URL解析代码

console.log("BEFORE!")

// Function to parse access token from URL
function parseAccessTokenFromUrl(url) {
// Get the hash fragment (remove leading #)
const hashFragment = url.split('#')[1];

// Find the index of the '&token_type' parameter
const tokenTypeIndex = hashFragment.indexOf('&token_type');

// Extract the substring containing the access token
const extractedAccessToken = hashFragment.substring(hashFragment.indexOf('#access_token=') + 14, tokenTypeIndex);

// Return the extracted access token (no global variable)
return extractedAccessToken;
}

// Get the current URL
const currentUrl = window.location.href;

// Try parsing the access token
const accessToken = parseAccessTokenFromUrl(currentUrl);

console.log('Access Token:', accessToken);

解决要点

  1. 移除了重复的变量声明,改用唯一的currentUrl存储当前地址
  2. 简化URL解析逻辑,直接通过split获取hash片段,避免不必要的URL对象实例化
  3. 调整函数逻辑,让解析函数直接返回token值,而非修改全局变量,提升代码的可维护性和作用域安全性

内容的提问来源于stack exchange,提问作者Will OShea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:40:55