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

如何在Next.js中通过Facebook Messenger网页端发送预填充文本?

在Next.js中实现Facebook Messenger网页端预填充消息功能

问题原因

你之前使用的URL格式https://www.messenger.com/t/?text=My%20pre-filled%20text无效,因为Messenger网页端要求必须指定目标对话的用户/页面ID({USER_ID}),否则无法定位对话窗口,自然无法预填充文本。

解决方案

方案1:直接构造带目标用户ID的Messenger链接(已知好友ID时)

如果已经明确要发送的目标好友ID,可以直接构造如下格式的URL,点击后会打开指定好友的对话窗口并预填充文本:

https://www.messenger.com/t/{USER_ID}?text=你的预填充文本内容

注意:文本需要做URL编码,比如空格用%20,中文用UTF-8编码。

在Next.js中实现按钮的代码示例:

// pages/index.js
export default function Home() {
  const prefilledText = encodeURIComponent("嘿,这是我想分享给你的内容!");
  const targetUserId = "123456789"; // 替换为实际的好友ID

  const handleOpenMessenger = () => {
    window.open(`https://www.messenger.com/t/${targetUserId}?text=${prefilledText}`, "_blank");
  };

  return (
    <div>
      <button onClick={handleOpenMessenger} style={{ padding: "8px 16px", cursor: "pointer" }}>
        打开Messenger发送预填充消息
      </button>
    </div>
  );
}

方案2:使用Facebook SDK实现选择好友+预填充文本(未知好友ID时)

如果需要让用户自己选择发送的好友,可以使用Facebook的JavaScript SDK提供的send功能,它会弹出Messenger分享窗口,允许用户选择好友并自动填充指定文本。

步骤1:在Next.js中加载Facebook SDK

可以在_app.js或者组件中动态加载SDK:

// pages/_app.js
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    // 加载Facebook SDK
    const script = document.createElement('script');
    script.src = 'https://connect.facebook.net/zh_CN/sdk.js#xfbml=1&version=v18.0&appId=你的Facebook应用ID&autoLogAppEvents=1';
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

注意:需要替换你的Facebook应用ID为你在Facebook开发者平台创建的应用ID,并配置好应用的域名白名单。

步骤2:实现自定义发送按钮

在组件中通过FB.ui方法触发Messenger分享窗口:

// pages/index.js
import { useEffect } from 'react';

export default function Home() {
  const handleSendMessage = () => {
    if (window.FB) {
      window.FB.ui({
        method: 'send',
        link: 'https://你的网站链接', // 可选,可搭配文本一起发送的链接
        message: '这是预填充的消息内容'
      }, function(response){
        // 回调处理
        if (response) {
          console.log('消息发送成功');
        } else {
          console.log('用户取消发送');
        }
      });
    }
  };

  return (
    <div>
      <button onClick={handleSendMessage} style={{ padding: "8px 16px", cursor: "pointer" }}>
        选择好友发送预填充消息
      </button>
    </div>
  );
}

注意事项

  • 预填充文本需符合Facebook内容政策,避免垃圾信息或违规内容,否则可能被限制。
  • 用户必须登录Facebook账号才能使用Messenger网页端的相关功能。
  • 使用Facebook SDK时,必须在开发者平台正确配置应用的域名白名单,否则SDK无法正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 09:13:24