如何将Facebook聊天信使添加到Next.js?

uqcuzwp8  于 2023-03-12  发布在  其他
关注(0)|答案(5)|浏览(311)

我尝试在我的Next.js应用程序中添加Facebook客户聊天,但它不工作。我找不到我的代码有任何问题。
1.如何在Next.js应用中添加Facebook客户聊天?
1.我的代码有什么错误吗?
1.有更好的实现来解决这个问题吗?
这是我的代码。

_文档. js

import Document, { Html, Head, Main, NextScript } from "next/document";
import React from "react";
import { getLangParam } from "../utils";

export default class MyDocument extends Document {
  render() {
    return (
      <Html >
        <Head />
          <noscript
            dangerouslySetInnerHTML={{
              __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MPQD53D"
                        height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
            }}
        <body>
          <Main />
          <NextScript />
        </body>
          <div id="fb-root"></div>
          <script
          dangerouslySetInnerHTML={{
            __html: `
            window.fbAsyncInit = function() {
              FB.init({
                xfbml            : true,
                version          : 'v10.0'
              });
            };
            (function(d, s, id) {
              var js, fjs = d.getElementsByTagName(s)[0];
              if (d.getElementById(id)) return;
              js = d.createElement(s); js.id = id;
              js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';
              fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
            `,
          }}
        />
        <div className="fb-customerchat"
          attribution="biz_inbox"
          page_id="1043670075778655">
        </div>
      </Html>
    );
  }
}
pbpqsu0x

pbpqsu0x1#

我的解决方案:

import Script from 'next/script';

function Facebook() {
  return (
    <div>
      <div id="fb-root"></div>

      <div id="fb-customer-chat" className="fb-customerchat"></div>
      <Script strategy="lazyOnload">
        {`
            var chatbox = document.getElementById('fb-customer-chat');
            chatbox.setAttribute("page_id", "YOUR_PAGE_ID");
            chatbox.setAttribute("attribution", "biz_inbox");
      
            window.fbAsyncInit = function() {
              FB.init({
                xfbml            : true,
                version          : 'v12.0'
              });
            };
      
            (function(d, s, id) {
              var js, fjs = d.getElementsByTagName(s)[0];
              if (d.getElementById(id)) return;
              js = d.createElement(s); js.id = id;
              js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';
              fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
        `}
      </Script>
    </div>
  );
}

export default Facebook;
44u64gxh

44u64gxh2#

∮我的解决方案∮
嵌入FB聊天插件到React(特别是Next.js)需要一些调整。

  • 按照FB的说明嵌入,但是添加了一个清理(删除FB,window.fb),使其在导航到另一个页面时工作。
  • 记得在FB聊天插件配置页面中将您的域列入白名单(FB聊天需要https)。

使用下面的Facebook1组件:

import { useEffect } from "react";

/**
 *
 */
export function init() {
  var chatbox = document.getElementById("fb-customer-chat");
  chatbox.setAttribute("page_id", "your_page_id"); // TODO: move to args
  chatbox.setAttribute("attribution", "biz_inbox");

  window.fbAsyncInit = function () {
    FB.init({
      xfbml: true,
      version: "v11.0",
    });
  };

  (function (d, s, id) {
    var js,
      fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js";
    fjs.parentNode.insertBefore(js, fjs);
  })(document, "script", "facebook-jssdk");
}

/**
 *
 */
export function cleanup() {
  (function (d, id) {
    var target = d.getElementById(id);
    if (target) {
      target.parentNode.removeChild(target);
    }
  })(document, "facebook-jssdk");

  delete window.FB;
}

export function Facebook1() {
  useEffect(() => {
    console.log("Facebook1");
    init();

    return () => {
      cleanup();
    };
  }, []);

  return (
    <div>
      <div id="fb-root"></div>

      <div id="fb-customer-chat" className="fb-customerchat"></div>
    </div>
  );
}

你可以在https://github.com/nghiaht/examples/tree/develop/with-fb查看我的完整例子,谢谢你鼓励我写下来,因为有时我会在项目中遇到他。
∮我最后的笔记∮
试着把功能放进组件(Facebook1 ...),然后把它们导入需要的地方。放入_document.js会让那些东西在你的应用中全局出现(这很伤:D)。

mum43rcc

mum43rcc3#

问得好。我一直在寻找一个解决方案,并找到了一个似乎适合我的。我在script标签中使用了dangerouslySetInnerHTML。我将script标签放在body中的**下面,**是FB在body标签中提供的div元素。当我将script标签放在__documents.js页面中更高的位置时,它没有加载信使。它看起来像这样。

<body>
          
                <div id="fb-root"></div>

               <div id="fb-customer-chat" className="fb-customerchat"></div>

              <script dangerouslySetInnerHTML = {{
                        __html : 

                        `
                        var chatbox = document.getElementById('fb-customer-chat');
                        chatbox.setAttribute("page_id", “22xxxx”xx);
                        chatbox.setAttribute("attribution", "biz_inbox");
                  
                        window.fbAsyncInit = function() {
                          FB.init({
                            xfbml            : true,
                            version          : 'v12.0'
                          });
                        };……

我相信有办法检测你在哪个页面上,这样信使就不会出现在所有页面上。
我将脚本放在<Head/>标记之外

unhi4e5o

unhi4e5o4#

在布局组件中使用它

import MessengerCustomerChat from 'react-messenger-customer-chat'
const DefaultLayout = ({ childrens }) => {
    return (
     <> 
     {childres}
     <MessengerCustomerChat
          pageId={"Your Page Id if any"}
          appId={process.env.NEXT_PUBLIC_FACEBOOK_APP_ID}
          version={"version of your app like 12.0"}          
          xfbml={true}
        />
    </>

    )}

就是这样。
资源:
https://www.npmjs.com/package/react-messenger-customer-chat

5lhxktic

5lhxktic5#

我意识到我在_document.tsx中插入了我的脚本,它应该在_app. tsx中。它也应该在Head组件之外。(Next 11 and adding Script tags not working. No scripts are rendered)对我有效的是..
我创建了一个这样的实用程序..

import Script from "next/script";

const FacebookMessenger = () => {
return (
<div>
  <div id="fb-root"></div>
  <div id="fb-customer-chat" className="fb-customerchat"></div>
  {/* eslint-disable-next-line @next/next/inline-script-id */}
  <Script strategy="lazyOnload">
    {`
      var chatbox = document.getElementById('fb-customer-chat');
      chatbox.setAttribute("page_id", "xxREPLACEMEWITHREALDATAxxxx");
      chatbox.setAttribute("attribution", "biz_inbox");

      window.fbAsyncInit = function() {
        FB.init({
          xfbml            : true,
          version          : 'v15.0'
        });
      };

      (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));
    `}
  </Script>
</div>
 );
};

export default FacebookMessenger;

然后将其插入到_app.tsx..**“next/head”**外部,如下所示...

_app.tsx
import Head from "next/head";
import FacebookMessenger from "utils/FacebookMessenger";

const App = ({ Component, pageProps }: MyAppProps) => {
return (
<Fragment>
  <FacebookMessenger /> // < ------ Outside Head 
  <Head>
    <title>PC Worth - We make IT worth</title>
    <meta
      name="description"
      content="Fastest-growing computer parts business. Wide selection of high-quality components at competitive prices. Shop now and see the difference."
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta httpEquiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="canonical" href="https://pcworth.com/" />
    <GoogleAnalytics />
  </Head>

  <Main />
  <Analytics />
</Fragment>
 );
 };

export default App;

相关问题