From 894c512b1d8980f29b0b19c084da227c2515a0fb Mon Sep 17 00:00:00 2001 From: Cell <1024@lruihao.cn> Date: Tue, 29 Oct 2024 11:14:53 +0800 Subject: [PATCH] :bug: Fix: solve the problem that navigator.clipboard is unavailable under http --- assets/js/theme.js | 2 +- assets/js/util.js | 25 +++++++++++++++++++++++++ layouts/partials/init/index.html | 2 +- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/assets/js/theme.js b/assets/js/theme.js index 6b0c62490..bb2965bf4 100644 --- a/assets/js/theme.js +++ b/assets/js/theme.js @@ -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!'); diff --git a/assets/js/util.js b/assets/js/util.js index 301356d3c..6fabd153b 100644 --- a/assets/js/util.js +++ b/assets/js/util.js @@ -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); + } } diff --git a/layouts/partials/init/index.html b/layouts/partials/init/index.html index 349ea2afe..b7321b3bb 100644 --- a/layouts/partials/init/index.html +++ b/layouts/partials/init/index.html @@ -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" . -}}