From ab4fd95ab59be04f1c97ba92abb6ce7120be0d4d Mon Sep 17 00:00:00 2001 From: Mimi <1119186082@qq.com> Date: Tue, 24 Nov 2020 21:27:23 +0800 Subject: [PATCH] Use Clipboard.writeText --- _config.yml | 2 +- source/js/utils.js | 38 +++++++++++++++++++++++--------------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/_config.yml b/_config.yml index 111e4f7..a8312a0 100644 --- a/_config.yml +++ b/_config.yml @@ -849,7 +849,7 @@ canvas_ribbon: #! ============================================================== # It's recommended to use the same version as in `_vendors.yml` to avoid potential problems. -# Remember to use the https protocol of CDN links when you enable https on your site. +# Remember to use the HTTPS protocol of CDN links when you enable HTTPS on your site. vendors: # The CDN provider of NexT internal scripts. # Available values: local | jsdelivr | unpkg | cdnjs diff --git a/source/js/utils.js b/source/js/utils.js index 1fea7e2..b32c41d 100644 --- a/source/js/utils.js +++ b/source/js/utils.js @@ -85,21 +85,29 @@ NexT.utils = { button.addEventListener('click', () => { const lines = element.querySelector('.code') || element.querySelector('code'); const code = lines.innerText; - const ta = document.createElement('textarea'); - ta.style.top = window.scrollY + 'px'; // Prevent page scrolling - ta.style.position = 'absolute'; - ta.style.opacity = '0'; - ta.readOnly = true; - ta.value = code; - document.body.append(ta); - ta.select(); - ta.setSelectionRange(0, code.length); - ta.readOnly = false; - const result = document.execCommand('copy'); - button.querySelector('i').className = result ? 'fa fa-check-circle fa-fw' : 'fa fa-times-circle fa-fw'; - ta.blur(); // For iOS - button.blur(); - document.body.removeChild(ta); + if (navigator.clipboard) { + navigator.clipboard.writeText(code).then(() => { + button.querySelector('i').className = 'fa fa-check-circle fa-fw'; + }, () => { + button.querySelector('i').className = 'fa fa-times-circle fa-fw'; + }); + } else { + const ta = document.createElement('textarea'); + ta.style.top = window.scrollY + 'px'; // Prevent page scrolling + ta.style.position = 'absolute'; + ta.style.opacity = '0'; + ta.readOnly = true; + ta.value = code; + document.body.append(ta); + ta.select(); + ta.setSelectionRange(0, code.length); + ta.readOnly = false; + const result = document.execCommand('copy'); + button.querySelector('i').className = result ? 'fa fa-check-circle fa-fw' : 'fa fa-times-circle fa-fw'; + ta.blur(); // For iOS + button.blur(); + document.body.removeChild(ta); + } }); element.addEventListener('mouseleave', () => { setTimeout(() => {