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

如何在Manifest V3的JavaScript扩展中使用Google Drive API?

实现Manifest V3 Chrome扩展更新Google Drive文件

以下是基于你已有的Client ID、API Key和Client Secret,实现Drive文件更新的完整步骤:

1. 配置Manifest.json

首先在扩展清单中声明必要的权限、OAuth2配置和API访问权限:

{
  "manifest_version": 3,
  "name": "Drive文件更新工具",
  "version": "1.0",
  "permissions": ["identity"],
  "oauth2": {
    "client_id": "你的Client ID",
    "scopes": ["https://www.googleapis.com/auth/drive.file"]
  },
  "host_permissions": ["https://www.googleapis.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  }
}
  • 选用drive.file权限而非全drive权限,遵循最小权限原则,仅允许扩展访问用户授权的特定文件;
  • identity权限用于OAuth2授权流程。

2. 后台Service Worker实现授权逻辑

在background.js中处理OAuth2令牌的获取、验证和缓存管理:

// 获取授权令牌
async function getAuthToken() {
  return new Promise((resolve, reject) => {
    chrome.identity.getAuthToken({ interactive: true }, (token) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
        return;
      }
      resolve(token);
    });
  });
}

// 验证令牌有效性
async function validateToken(token) {
  const response = await fetch('https://www.googleapis.com/oauth2/v3/tokeninfo', {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  return response.ok;
}
  • interactive: true会触发Google账号授权弹窗,用户首次使用时需要授权;
  • 令牌验证用于处理过期情况,避免无效请求。

3. 调用Drive API执行文件更新

在background.js中添加文件更新函数,支持同时更新文件内容和元数据:

async function updateDriveFile(fileId, newFileBlob, newFileName = null) {
  let token = await getAuthToken();
  
  // 验证令牌,失效则清除缓存并重试
  if (!(await validateToken(token))) {
    chrome.identity.removeCachedAuthToken({ token }, () => {});
    token = await getAuthToken();
  }

  // 构建multipart请求体(同时包含元数据和文件内容)
  const formData = new FormData();
  const metadata = {};
  if (newFileName) metadata.name = newFileName;
  formData.append('metadata', new Blob(
    [JSON.stringify(metadata)],
    { type: 'application/json' }
  ));
  formData.append('file', newFileBlob);

  const response = await fetch(
    `https://www.googleapis.com/upload/drive/v3/files/${fileId}?uploadType=multipart`,
    {
      method: 'PATCH',
      headers: { 'Authorization': `Bearer ${token}` },
      body: formData
    }
  );

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(`API请求失败: ${errorData.error.message}`);
  }

  return await response.json();
}

// 监听前端消息触发更新
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'updateDriveFile') {
    updateDriveFile(message.fileId, message.blob, message.newFileName)
      .then(result => sendResponse({ success: true, data: result }))
      .catch(err => sendResponse({ success: false, error: err.message }));
    return true; // 保持消息通道开放,等待异步结果返回
  }
});
  • 使用PATCH方法和uploadType=multipart,支持同时更新文件名和文件内容;
  • 如果仅需更新文件内容,可改用uploadType=media,请求体直接传入文件Blob即可。

4. 前端Popup触发更新

创建popup.html和popup.js,让用户触发更新操作:

<!-- popup.html -->
<div style="padding: 16px; width: 200px;">
  <input type="text" id="fileId" placeholder="输入Drive文件ID" style="width: 100%; margin-bottom: 8px; padding: 4px;">
  <input type="text" id="newFileName" placeholder="新文件名(可选)" style="width: 100%; margin-bottom: 8px; padding: 4px;">
  <button id="updateBtn" style="width: 100%; padding: 6px;">更新文件</button>
</div>
<script src="popup.js"></script>
// popup.js
document.getElementById('updateBtn').addEventListener('click', async () => {
  const fileId = document.getElementById('fileId').value.trim();
  const newFileName = document.getElementById('newFileName').value.trim() || null;
  
  if (!fileId) {
    alert('请输入Drive文件ID');
    return;
  }

  // 示例:创建一个文本Blob,实际场景可替换为用户选择的文件
  const testBlob = new Blob(['这是更新后的文件内容'], { type: 'text/plain' });

  const response = await chrome.runtime.sendMessage({
    action: 'updateDriveFile',
    fileId,
    blob: testBlob,
    newFileName
  });

  if (response.success) {
    alert('文件更新成功!');
  } else {
    alert(`更新失败: ${response.error}`);
  }
});

关键注意事项

  • Client Secret使用:在Chrome扩展中,Client Secret不需要暴露在代码中,OAuth2授权流程会通过Chrome的identityAPI自动处理;
  • Service Worker生命周期:MV3的Service Worker是临时运行的,不要依赖它持久化存储数据,所有状态和令牌管理都通过Chrome API完成;
  • API密钥场景:API Key仅适用于公开、只读的Drive数据请求,更新操作必须使用OAuth2授权;
  • 错误处理:务必处理令牌过期、用户拒绝授权、API请求失败等异常情况,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:43:20