接入Twitter和Facebook分享踩坑记录

2022-11-06,,,,

准备工作

1、首先需要在HTML的head添加下述meta标签内容,在分享时,Twitter和Facebook会爬取该网站页面的meta内容,然后生成分享卡片。

2、按照下述配置完成后,需要把内容发布上线,否则Twitter和Facebook无法爬取到网页配置的meta信息。

3、完成上面的两个步骤后,使用官方的测试工具测试分享效果,如果配置正确就可以预览到分享的效果:

Twitter测试工具:https://cards-dev.twitter.com/validator
facebook测试工具:https://developers.facebook.com/tools/debug/

4、Twitter和Facebook爬取内容填写的url位置有些区别,其中Facebook无法设置自定义内容。

切记: 配置完成后,请务必使用上述的测试工具进行测试,否则可能会出现即使配置正确了,在开发测试分享功能的时候,效果也可能没生效。

Facebook分享

meta标签内容:

<meta property="og:title" content="Remove Image Background for Free">
<meta property="og:description" content="Remove Image Background for Free">
<meta property="og:site_name" content="xxxxxx.com">
<meta property="og:url" content="https://xxxxxx.com">
<meta property="og:image" content="https://xxxxx.com/image_background.jpg">

字段对应关系预览:

使用标签即可调用:

<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u='链接,分享爬取的内容就是这个从这个链接,该链接不会显示在分享卡片上'">Facebook分享</a>

为了方便这里封装了方法:

/**
* 快速分享到Facebook
*/
export const facebookShare = () => {
const url = encodeURIComponent('链接,分享爬取的内容就是这个从这个链接,该链接不会显示在分享卡片上');
const facebook = `http://www.facebook.com/sharer/sharer.php?u=${url}`;
window.open(facebook, '_blank');
};

Twitter分享

meta标签内容:

<!-- 注:下述的twitter:url 链接,即为twitter从这个链接爬取分享的内容  -->
<meta property="twitter:url" content="https://xxxxxx.com">
<meta name="twitter:title" content="Remove Image Background for Free">
<meta name="twitter:description" content="Remove Image Background for Free">
<meta name="twitter:site" content="@PixCut">
<meta property="twitter:image" content="https://xxxxxx.com/image_background.jpg">
<meta name="twitter:card" content="summary_large_image">

字段对应关系预览:

使用标签即可调用:

<a target="_blank"href="https://twitter.com/intent/tweet?text=自定义内容,可以文字链接之类的&amp;via=twitter账号名,会显示@XXX">Twitter分享</a>

为了方便这里封装了方法:

/**
* 快速分享到twitter
*/
export const twitterShare = () => {
// 自定义内容
const content = '点击此处链接领取奖品,可选'
const url = encodeURIComponent('链接,可选');
const text = `${content} ${url}&via=${via}`;
// 分享后会显示 “via @张三”
const via = '张三';
// 拼接链接
const twitter = `https://twitter.com/intent/tweet?text=${text}`;
window.open(twitter, '_blank');
};

接入Twitter和Facebook分享踩坑记录的相关教程结束。

《接入Twitter和Facebook分享踩坑记录.doc》

下载本文的Word格式文档,以方便收藏与打印。