Skip to content

Commit

Permalink
🐛 Fix: solve the problem that navigator.clipboard is unavailable unde…
Browse files Browse the repository at this point in the history
…r http
  • Loading branch information
Lruihao committed Oct 29, 2024
1 parent 64f954c commit 894c512
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion assets/js/theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ class FixIt {
}
$copy.title = this.config.code.copyTitle;
$copy.addEventListener('click', () => {
navigator.clipboard.writeText(code).then(() => {
this.util.copyText(code).then(() => {
this.util.animateCSS($code, 'animate__flash');
}, () => {
console.error('Clipboard write failed!', 'Your browser does not support clipboard API!');
Expand Down
25 changes: 25 additions & 0 deletions assets/js/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,29 @@ export default class Util {
}
}
}

/**
* copy text to clipboard
* @param {String} text text to copy
* @returns {Promise} promise
*/
copyText(text) {
if (navigator.clipboard) {
this.copyText = (text) => navigator.clipboard.writeText(text);
return this.copyText(text);
}
this.copyText = (text) => new Promise((resolve, reject) => {
const input = document.createElement('input');
input.value = text;
document.body.appendChild(input);
input.select();
if (document.execCommand('copy')) {
document.body.removeChild(input);
resolve();
} else {
reject();
}
});
return this.copyText(text);
}
}
2 changes: 1 addition & 1 deletion layouts/partials/init/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{{- .Scratch.Set "version" "v0.3.14-c08671de" -}}
{{- .Scratch.Set "version" "v0.3.14-35221731" -}}
{{- .Scratch.Set "this" dict -}}

{{- partial "init/detection-env.html" . -}}
Expand Down

0 comments on commit 894c512

Please sign in to comment.