From b93e2a15e32910552849ba08503f416373868d87 Mon Sep 17 00:00:00 2001 From: finned-palmer Date: Sat, 10 Jul 2021 09:20:57 -0500 Subject: [PATCH] Fix copy from non-secure context issue --- .../src/js/components/lib/balance.js | 6 +++--- pkg/btc-wallet/src/js/lib/util.js | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/pkg/btc-wallet/src/js/components/lib/balance.js b/pkg/btc-wallet/src/js/components/lib/balance.js index ab72c97d79..d5c0be64a5 100644 --- a/pkg/btc-wallet/src/js/components/lib/balance.js +++ b/pkg/btc-wallet/src/js/components/lib/balance.js @@ -2,7 +2,7 @@ import React, { useState } from 'react'; import { Row, Text, Button, Col } from '@tlon/indigo-react'; import Send from './send.js'; import CurrencyPicker from './currencyPicker.js'; -import { satsToCurrency } from '../../lib/util.js'; +import { copyToClipboard, satsToCurrency } from '../../lib/util.js'; import { useSettings } from '../../hooks/useSettings.js'; import { api } from '../../api'; @@ -23,8 +23,8 @@ const Balance = () => { const [copiedString, setCopiedString] = useState(false); const scanning = scanProgress?.main !== null || scanProgress?.change !== null; - const copyAddress = (arg) => { - navigator.clipboard.writeText(address); + const copyAddress = async (arg) => { + await copyToClipboard(address); api.btcWalletCommand({ 'gen-new-address': null }); if (arg === 'button') { diff --git a/pkg/btc-wallet/src/js/lib/util.js b/pkg/btc-wallet/src/js/lib/util.js index 2c133559a6..fa17b1ec80 100644 --- a/pkg/btc-wallet/src/js/lib/util.js +++ b/pkg/btc-wallet/src/js/lib/util.js @@ -127,3 +127,23 @@ export function mapDenominationToSymbol(denomination) { return denomination; } } + +export function copyToClipboard(textToCopy) { + // navigator clipboard api needs a secure context (https or localhost) + if (navigator.clipboard && window.isSecureContext) { + return navigator.clipboard.writeText(textToCopy); + } else { + let textArea = document.createElement('textarea'); + textArea.value = textToCopy; + textArea.style.position = 'fixed'; + textArea.style.left = '-999999px'; + textArea.style.top = '-999999px'; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + return new Promise((res, rej) => { + document.execCommand('copy') ? res() : rej(); + textArea.remove(); + }); + } +}