5分钟封装一个主流社交平台工具函数!

17 Max

1. 社交媒体分享

社交媒体分享是一个比较常见的需求,但是自己去一个个查找各大平台的分享 API 链接又比较麻烦,所以封装了真么一个工具函数来实现一键分享

2. 社交媒体 API 集合

1
2
3
4
5
6
7
8
9
const networks = {
email: "mailto:?subject=@t&body=@u%0D%0A@d",
facebook: "https://www.facebook.com/sharer/sharer.php?u=@u&title=@t&description=@d&quote=@q&hashtag=@h",
sms: "sms:?body=@t%0D%0A@u%0D%0A@d",
telegram: "https://t.me/share/url?url=@u&text=@t%0D%0A@d",
twitter: "https://twitter.com/intent/tweet?text=@t&url=@u&hashtags=@h@tu",
whatsapp: "https://api.whatsapp.com/send?text=@t%0D%0A@u%0D%0A@d",
};
// 链接中的 '@*' 作为占位符后续使用正则替换为分享内容

3. 工具函数封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
*
* @param {*} network 需要分享的社交平台
* @param {*} url 分享链接
* @param {*} context 分享内容
* @param {*} option 特定平台可添加附加内容
*/
export default function share(
network,
url,
context,
option = {
twitterUser: "",
description: "",
quote: "",
encodedHashtags: "",
media: "",
}
) {
let ua = navigator.userAgent.toLowerCase();

let key = network.toLowerCase();

/**
* On IOS, SMS sharing link need a special formatting
* Source: https://weblog.west-wind.com/posts/2013/Oct/09/Prefilling-an-SMS-on-Mobile-Devices-with-the-sms-Uri-Scheme#Body-only
*/
if (key === "sms" && (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1)) {
networks[key].replace(":?", ":&");
}

let link = networks[key];

/**
* Twitter sharing shouldn't include empty parameter
* Source: https://github.com/nicolasbeauvais/vue-social-sharing/issues/143
*/
if (key === "twitter") {
link = link.replace("&hashtags=@h", "").replace("@tu", "");
}

link = link
.replace(/@tu/g, "&via=" + encodeURIComponent(option.twitterUser))
.replace(/@u/g, encodeURIComponent(url))
.replace(/@t/g, encodeURIComponent(context))
.replace(/@d/g, encodeURIComponent(option.description))
.replace(/@q/g, encodeURIComponent(option.quote))
.replace(/@h/g, option.encodedHashtags)
.replace(/@m/g, encodeURIComponent(option.media));

/**
* 如果是 IOS 在当前页打开,避免出现空白页签
*/
if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1) {
window.location.href = link;
} else {
window.open(link, "sharer-" + key, ",height=426,width=626");
}
}

关于特定平台的附加信息可查看对应 share 文档

  • Title: 5分钟封装一个主流社交平台工具函数!
  • Author: 17
  • Created at : 2024-11-18 15:07:29
  • Updated at : 2024-11-18 15:54:31
  • Link: http://17mc.top/2024/11/18/wiki-share函数封装/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
5分钟封装一个主流社交平台工具函数!