Skip to content

Commit 10e1be5

Browse files
committed
fix: copy to clipboard for maximum browser compat
1 parent e8cc35c commit 10e1be5

File tree

1 file changed

+46
-5
lines changed

1 file changed

+46
-5
lines changed

www/pages/_layout.html

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,55 @@
1717
<script>
1818
document.addEventListener("alpine:init", () => {
1919
Alpine.magic("clipboard", () => {
20-
return (subject) => navigator.clipboard.writeText(subject);
20+
return (subject) => copyToClipboard(subject);
2121
});
2222
});
23+
24+
// copy to clipboard with fallback for protocols
25+
// and navigator permissions
26+
function copyToClipboard(strToCopy) {
27+
if (window.location.protocol === "http:") {
28+
return fallBackCopy(strToCopy);
29+
}
30+
31+
if (!(navigator && navigator.clipboard)) {
32+
return fallBackCopy(strToCopy);
33+
}
34+
35+
navigator.permissions
36+
.query({ name: "clipboard-write" })
37+
.then((result) => {
38+
if (result.state == "granted" || result.state == "prompt") {
39+
navigator.clipboard.writeText(strToCopy).then(
40+
function () {
41+
// ignore and digest
42+
},
43+
function () {
44+
return fallBackCopy(strToCopy);
45+
}
46+
);
47+
} else {
48+
return fallBackCopy(strToCopy);
49+
}
50+
});
51+
}
52+
53+
function fallBackCopy(strToCopy) {
54+
const el = document.createElement("textarea");
55+
el.value = strToCopy;
56+
el.setAttribute("readonly", "");
57+
el.style.position = "absolute";
58+
el.style.left = "-9999px";
59+
document.body.appendChild(el);
60+
el.select();
61+
document.execCommand("copy");
62+
document.body.removeChild(el);
63+
}
2364
</script>
2465
</head>
2566

26-
<body x-data="{
67+
<body
68+
x-data="{
2769
copied: false,
2870
hits: 0,
2971
async init() {
@@ -34,7 +76,8 @@
3476
await await `https://hits.goblin.run/hits?url=${window.location.href}`;
3577
this.hits = hitsCount.count
3678
},
37-
}">
79+
}"
80+
>
3881
<a href="#content" class="sr-only">Skip to main content</a>
3982

4083
<nav
@@ -207,7 +250,5 @@ <h1 class="text-4xl font-bold tracking-tight sm:text-6xl">
207250
</p>
208251
</div>
209252
</footer>
210-
211-
212253
</body>
213254
</html>

0 commit comments

Comments
 (0)