-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshare.js
More file actions
112 lines (91 loc) · 2.28 KB
/
Copy pathshare.js
File metadata and controls
112 lines (91 loc) · 2.28 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { CustomButton } from './button.js';
const sheet = new CSSStyleSheet();
sheet.replace(`@layer components {
:host([hidden]) { display: none; }
}`);
export class ShareButton extends CustomButton {
constructor() {
super();
if (typeof navigator.share === 'function') {
this.hidden = false;
} else {
this.hidden = true;
this.disabled = true;
}
}
connectedCallback() {
super.connectedCallback();
if (typeof navigator.share === 'function') {
// Parent class creates controller and aborts on disconnect
this.addEventListener('click', ShareButton.#share, { signal: this.signal });
}
}
get shareText() {
return this.dataset.shareText;
}
set shareText(val) {
if (typeof val === 'string') {
this.dataset.shareText = val;
} else {
delete this.dataset.shareText;
}
}
get shareTitle() {
return this.dataset.shareTitle ?? document.title;
}
set shareTitle(val) {
if (typeof val === 'string') {
this.dataset.shareTitle = val;
} else {
delete this.dataset.shareTitle;
}
}
get shareURL() {
return this.dataset.shareUrl ?? location.href;
}
set shareURL(val) {
if (typeof val === 'string') {
this.dataset.shareUrl = val;
} else {
delete this.dataset.shareUrl;
}
}
static async #share(event) {
const btn = event.currentTarget;
if (! btn.disabled) {
btn.disabled = true;
try {
const {
shareTitle: title = document.title,
shareUrl = location.href,
shareText: text,
utmSource,
utmMedium = 'referrer',
utmCampaign,
utmContent = 'share-button',
utmTerm,
} = btn.dataset;
const url = new URL(shareUrl, document.baseURI);
if (typeof utmSource === 'string') {
url.searchParams.set('utm_source', utmSource);
url.searchParams.set('utm_medium', utmMedium);
url.searchParams.set('utm_content', utmContent);
if (typeof utmCampaign === 'string') {
url.searchParams.set('utm_campaign', utmCampaign);
}
if (typeof utmTerm === 'string') {
url.searchParams.set('utm_term', utmTerm);
}
}
await navigator.share({ title, url, text });
} catch(error) {
btn.dispatchEvent(new ErrorEvent('error', { error, message: error.message }));
} finally {
btn.disabled = false;
}
}
}
static {
this.register('share-button');
}
}