diff --git a/web/components/share-embed-button.tsx b/web/components/share-embed-button.tsx index d9af7934..430005d9 100644 --- a/web/components/share-embed-button.tsx +++ b/web/components/share-embed-button.tsx @@ -4,6 +4,7 @@ import { Menu, Transition } from '@headlessui/react' import { Contract } from '../../common/contract' import { contractPath } from '../lib/firebase/contracts' import { DOMAIN } from '../../common/envs/constants' +import { copyToClipboard } from '../lib/util/copy' export function ShareEmbedButton(props: { contract: Contract }) { const { contract } = props @@ -14,15 +15,16 @@ export function ShareEmbedButton(props: { contract: Contract }) { const embedCode = `` - if (navigator.clipboard) navigator.clipboard.writeText(embedCode) + copyToClipboard(embedCode) } return ( - - + + diff --git a/web/lib/util/copy.ts b/web/lib/util/copy.ts new file mode 100644 index 00000000..47dc4dab --- /dev/null +++ b/web/lib/util/copy.ts @@ -0,0 +1,38 @@ +// From: https://stackoverflow.com/a/33928558/1592933 +// Copies a string to the clipboard. Must be called from within an +// event handler such as click. May return false if it failed, but +// this is not always possible. Browser support for Chrome 43+, +// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+. +// Internet Explorer: The clipboard feature may be disabled by +// an administrator. By default a prompt is shown the first +// time the clipboard is used (per session). +export function copyToClipboard(text: string) { + if (navigator.clipboard) { + navigator.clipboard.writeText(text) + } else if ( + (window as any).clipboardData && + (window as any).clipboardData.setData + ) { + console.log('copy 2') + // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible. + return (window as any).clipboardData.setData('Text', text) + } else if ( + document.queryCommandSupported && + document.queryCommandSupported('copy') + ) { + console.log('copy 3') + var textarea = document.createElement('textarea') + textarea.textContent = text + textarea.style.position = 'fixed' // Prevent scrolling to bottom of page in Microsoft Edge. + document.body.appendChild(textarea) + textarea.select() + try { + return document.execCommand('copy') // Security exception may be thrown by some browsers. + } catch (ex) { + console.warn('Copy to clipboard failed.', ex) + return prompt('Copy to clipboard: Ctrl+C, Enter', text) + } finally { + document.body.removeChild(textarea) + } + } +}