Facebook社交插件在动态添加时不显示

时间:2015-03-18 22:02:55

标签: javascript facebook

我正在将facebook社交插件添加到网页

当我手动添加:

<div class="fb-comments" data-href="http://website.com/z" data-width="700" data-numposts="7" data-colorscheme="light"></div>

但是,当javascript代码添加它时,它不会

任何想法?

2 个答案:

答案 0 :(得分:18)

JS SDK在初始化时会遍历您的文档,以查找要解析为社交插件的元素。如果您还想要解析稍后添加到文档中的内容,则需要调用FB.XFBML.parse()

https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/

答案 1 :(得分:0)

太棒了@CBroe!

谢谢!它适用于 Nextjs/React 项目。

作为参考,请查看实现它的自定义钩子:


import { useEffect } from 'react';
let FB;

const useFacebook = ({ addTrack }) => {

  useEffect(() => {
 
    const facebookScript = document.createElement("script");

    facebookScript.id = 'fb-sdk';
    facebookScript.async = true;
    facebookScript.defer = true;
    facebookScript.crossOrigin = "anonymous";
    facebookScript.nonce = "5JOEwLPT";
    const track = addTrack ? `&appId=${process.env.NEXT_PUBLIC_FACEBOOK_ID}&autoLogAppEvents=1` : '';
    facebookScript.src = `https://connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v10.0${track}`;

    document.body.appendChild(facebookScript);

    const startScript = document.createElement('script');
    const code = `window.fbAsyncInit = function() {
      FB.init({
        appId            : '${process.env.NEXT_PUBLIC_FACEBOOK_ID}',
        autoLogAppEvents : ${addTrack},
        xfbml            : true,
        version          : 'v10.0'
      });
    };`;
    startScript.appendChild(document.createTextNode(code));
    document.body.appendChild(startScript);
    if(window.FB) {
      window.fbAsyncInit();
    }
    return () => {
      document.body.removeChild(facebookScript);
      document.body.removeChild(startScript);
    }
  }, [addTrack]);
};

export default useFacebook;

完整代码 Nextjs Facebook SDK 评论示例: https://github.com/cmdaniel/nextjs-facebook-sdk