如何在Chrome扩展中通过Google Identity API向Google Calendar写入事件?
在Chrome扩展中通过Google Identity API创建Google日历事件
首先要确保你的扩展已申请到Google日历的写入权限:在manifest.json的oauth2.scopes数组中添加https://www.googleapis.com/auth/calendar.events(如果之前仅配置了只读权限,需要更新配置并重新完成授权流程)。
创建日历事件需要使用POST请求,而非读取时的GET,同时要构造符合Google Calendar API规范的事件请求体。以下是整合了读取日历、创建事件逻辑的完整代码:
chrome.identity.getAuthToken({ interactive: true }, async function (token) { // 基础请求头配置,移除原代码中多余的contentType字段(fetch不支持该属性) const baseHeaders = { Authorization: "Bearer " + token, "Content-Type": "application/json", }; // 获取主日历ID async function getCalendarId() { const response = await fetch( "https://www.googleapis.com/calendar/v3/calendars/primary", { method: "GET", headers: baseHeaders, } ); const data = await response.json(); return data.id; } // 创建日历事件的核心函数 async function createCalendarEvent(calendarId, eventData) { const response = await fetch( `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events`, { method: "POST", headers: baseHeaders, body: JSON.stringify(eventData), } ); const result = await response.json(); if (response.ok) { console.log("事件创建成功:", result); return result; } else { console.error("创建事件失败:", result); throw new Error(result.error.message); } } try { const calendarId = await getCalendarId(); // 保留你原有的读取日历事件逻辑 const eventsResponse = await fetch( `https://www.googleapis.com/calendars/${calendarId}/events`, { method: "GET", headers: baseHeaders, } ); const eventsData = await eventsResponse.json(); // 处理读取到的事件 for (const item of eventsData.items) { if (!item.end) { console.log("发现无结束时间的事件"); } else { // 你的事件处理逻辑 } } // 构造示例事件数据,可根据需求修改 const newEvent = { summary: "Chrome扩展测试事件", location: "线上会议", description: "通过Chrome扩展创建的日历事件", start: { dateTime: "2024-10-05T14:00:00+08:00", // ISO 8601格式时间 timeZone: "Asia/Shanghai", }, end: { dateTime: "2024-10-05T15:30:00+08:00", timeZone: "Asia/Shanghai", }, attendees: [{ email: "participant@example.com" }] // 可选参会者 }; // 调用创建事件函数 await createCalendarEvent(calendarId, newEvent); } catch (error) { console.error("操作出错:", error); } });
关键改动说明:
- 移除了原代码中
init对象里无效的contentType: "json"字段,fetch的请求格式由headers中的Content-Type控制 - 新增
createCalendarEvent函数,使用POST请求并通过body传递序列化后的事件JSON数据 - 统一使用
async/await处理异步逻辑,避免then链式调用的混乱 - 添加了错误捕获逻辑,便于排查创建失败的原因
- 事件的
start和end字段必须使用ISO 8601格式,并指定正确的时区(或直接使用UTC时间)
内容的提问来源于stack exchange,提问作者sweglord
相关产品推荐
相关产品推荐

