@parsonic/share-button
Version:
Native share button web component
64 lines (63 loc) • 2.01 kB
JavaScript
// src/ShareButton.js
function getGraphContent(property, defaultValue) {
return document.querySelector(`meta[property='og:${property}']`)?.getAttribute("content") ?? defaultValue;
}
var ShareButton = class _ShareButton extends HTMLElement {
/**
* Defines the custom element with provided tag name if `navigator.share` is supported
*/
static register(tag = "share-button") {
if ("share" in navigator) {
customElements.define(tag, _ShareButton);
}
}
connectedCallback() {
const defaultButton = document.createElement("button");
defaultButton.textContent = this.dataset.buttonLabel ?? "Share";
defaultButton.setAttribute("part", "button");
const slot = document.createElement("slot");
slot.setAttribute("name", "button");
slot.appendChild(defaultButton);
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(slot);
slot.addEventListener("click", () => {
let {
url = getGraphContent("url", location.href),
title = getGraphContent("title", document.title),
text = getGraphContent("description"),
shareEventName = "share",
resultEventName = "shareResult"
} = this.dataset;
const data = { url, text, title };
if (navigator.canShare(data) && this.dispatchEvent(
new CustomEvent(shareEventName, {
cancelable: true,
bubbles: true,
detail: data
})
)) {
navigator.share(data).then(() => {
this.dispatchEvent(
new CustomEvent(resultEventName, {
bubbles: true,
detail: {
result: "success",
data
}
})
);
}).catch((error) => {
this.dispatchEvent(
new CustomEvent(resultEventName, {
bubbles: true,
detail: { result: "error", data, error }
})
);
});
}
});
}
};
export {
ShareButton as default
};