-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-share.js
40 lines (33 loc) · 1.01 KB
/
data-share.js
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
/**
* @copyright 2023 Chris Zuber <[email protected]>
*/
export const SELECTOR = '[data-share-title], [data-share-text], [data-share-url]';
export const SUPPORTED = navigator.share instanceof Function;
export function hasShareAttrs(target) {
return target instanceof Element && target.matches(SELECTOR);
}
async function shareHandler() {
this.disabled = true;
const { shareTitle: title, shareText: text, shareUrl: url } = this.dataset;
try {
await navigator.share({ title, text, url });
} catch(err) {
console.error(err);
} finally {
this.disabled = false;
}
}
export function shareInit(target = document.body) {
if (typeof target === 'string') {
return shareInit(document.querySelector(target));
} else if (SUPPORTED && target instanceof Element) {
const targets = hasShareAttrs(target) ? [target] : [...target.querySelectorAll(SELECTOR)];
targets.forEach(el => {
el.addEventListener('click', shareHandler, { passive: true });
el.hidden = false;
});
return true;
} else {
return false;
}
}