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

使用Node.js和Firebase Functions开发sendNotification函数遇ReferenceError问题

解决Firebase Functions中ReferenceError: context is not defined的问题

这个错误我之前调试Functions的时候也碰到过,其实根源很明确——你在onWrite触发器的代码里引用了context参数,但你的函数回调里根本没把它作为参数传进来,或者是用了不匹配的Functions语法版本。

我给你分两种情况来解决:

一、使用Firebase Functions v1.0+的新语法(推荐)

从v1.0开始,Firebase Functions的触发器回调参数结构变了,onWrite需要接收两个参数:change(用来获取数据变化前后的状态)和context(包含触发上下文,比如路径参数、时间戳等)。

如果你的代码之前是这样写的(没传context):

exports.sendNotification = functions.database.ref('/your/path').onWrite((event) => {
  // 这里错误地用了context,比如 context.params.userId
});

那改成下面这样就可以了:

exports.sendNotification = functions.database.ref('/your/path/{userId}').onWrite((change, context) => {
  // 现在可以正常使用context了,比如获取路径里的userId参数
  const targetUserId = context.params.userId;
  
  // 你的通知逻辑代码...
});

二、如果你还在使用旧版本的Functions(不建议)

如果你的firebase-functions版本低于1.0,那时候的触发器参数是event对象,上下文信息都在event里,不能直接用context。比如要获取路径参数得用event.params.userId,而不是context.params。

不过还是强烈建议你升级到最新版本的firebase-functions,旧版本的语法已经被官方弃用了,升级命令如下:

npm install firebase-functions@latest --save

给你一个完整的sendNotification示例

我把常用的通知发送逻辑整理了一下,你可以参考:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.sendNotification = functions.database.ref('/notifications/{userId}').onWrite((change, context) => {
  // 从context里获取触发的用户ID
  const userId = context.params.userId;
  
  // 获取新写入的通知数据
  const newNotification = change.after.val();
  
  // 构建推送的通知内容
  const notificationPayload = {
    notification: {
      title: newNotification.title,
      body: newNotification.content,
      clickAction: 'FLUTTER_NOTIFICATION_CLICK' // 根据你的客户端平台调整,比如Android/iOS的跳转逻辑
    }
  };
  
  // 从数据库获取用户的设备令牌(假设你存在/users/{userId}/tokens路径下)
  return admin.database().ref(`/users/${userId}/tokens`).once('value')
    .then(tokensSnapshot => {
      const deviceTokens = Object.keys(tokensSnapshot.val() || {});
      
      // 发送通知到用户的所有设备
      return admin.messaging().sendToDevice(deviceTokens, notificationPayload);
    })
    .catch(error => {
      console.error('发送通知出错:', error);
      return null;
    });
});

改完代码后,记得重新部署函数:

firebase deploy --only functions

然后再去查看Firebase控制台的函数日志,应该就能解决这个context is not defined的错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:27:31