@baken667/share-kit
Version:
A simple share utility kit with native and social media share options
86 lines (83 loc) • 2.41 kB
JavaScript
var PlatformFormats = /* @__PURE__ */ ((PlatformFormats2) => {
PlatformFormats2["WA_LINK_FORMAT"] = "https://wa.me/?text={0}%20{1}";
PlatformFormats2["TG_LINK_FORMAT"] = "https://t.me/share/url?url={0}&text={1}";
PlatformFormats2["NOT_SUPPORTED_MESSAGE"] = "This feature is not supported on this browser or operating system.";
return PlatformFormats2;
})(PlatformFormats || {});
const appendUtmParams = (url, utmParams) => {
if (!utmParams) return url;
const urlObject = new URL(url);
Object.keys(utmParams).forEach((key) => {
if (utmParams[key]) {
urlObject.searchParams.append(key, utmParams[key]);
}
});
return urlObject.toString();
};
const formatLink = (template, ...args) => {
return template.replace(/{(\d+)}/g, (_, number) => args[number] || "");
};
const share = ({
url = window.location.href,
title,
desc,
platform,
utmParams
}) => {
const finalUrl = appendUtmParams(url, utmParams);
const encodedUrl = encodeURIComponent(finalUrl);
const encodedText = encodeURIComponent(
title && desc ? `${title} - ${desc}` : title || desc || ""
);
let link = "";
switch (platform) {
case "whatsapp":
link = formatLink(
PlatformFormats.WA_LINK_FORMAT,
encodedText,
encodedUrl
);
break;
case "telegram":
link = formatLink(
PlatformFormats.TG_LINK_FORMAT,
encodedUrl,
encodedText
);
break;
case "email":
const subject = encodeURIComponent(title || "Check this out!");
const body = encodeURIComponent(
`${title ? `${title}
` : ""}${desc ? `${desc}
` : ""}${encodedUrl}`
);
link = `mailto:?subject=${subject}&body=${body}`;
break;
case "native":
if (!navigator.canShare) {
console.error(PlatformFormats.NOT_SUPPORTED_MESSAGE);
return;
}
if (navigator.canShare({ url: finalUrl })) {
navigator.share({
title,
text: `${title ? title : ""}${encodedUrl}${desc ? ` - ${desc}` : ""}`,
url: finalUrl
}).catch((err) => console.error("Sharing failed", err));
return;
} else {
console.error(PlatformFormats.NOT_SUPPORTED_MESSAGE);
return;
}
default:
console.warn(PlatformFormats.NOT_SUPPORTED_MESSAGE);
break;
}
window.open(link, "_blank");
};
export {
appendUtmParams,
formatLink,
share
};