Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: copy code in non-secure contexts #792

Merged
merged 6 commits into from Jun 16, 2022
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
47 changes: 46 additions & 1 deletion src/client/theme-default/composables/copy-code.ts
Expand Up @@ -20,6 +20,51 @@ export function useCopyCode() {
)
}

async function copyToClipboard(text: string) {
try {
return navigator.clipboard.writeText(text)
} catch {
const element = document.createElement('textarea')
const previouslyFocusedElement = document.activeElement

element.value = text

// Prevent keyboard from showing on mobile
element.setAttribute('readonly', '')

element.style.contain = 'strict'
element.style.position = 'absolute'
element.style.left = '-9999px'
element.style.fontSize = '12pt' // Prevent zooming on iOS

const selection = document.getSelection()
const originalRange = selection
? selection.rangeCount > 0 && selection.getRangeAt(0)
: null

document.body.append(element)
element.select()

// Explicit selection workaround for iOS
element.selectionStart = 0
element.selectionEnd = text.length

document.execCommand('copy')

element.remove()

if (originalRange) {
selection!.removeAllRanges() // originalRange can't be truthy when selection is falsy
selection!.addRange(originalRange)
}

// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
;(previouslyFocusedElement as HTMLElement).focus()
}
}
}

function handleElement(el: HTMLElement) {
el.onclick = () => {
const parent = el.parentElement
Expand All @@ -38,7 +83,7 @@ function handleElement(el: HTMLElement) {
text = text.replace(/^ *\$ /gm, '')
}

navigator.clipboard.writeText(text).then(() => {
copyToClipboard(text).then(() => {
el.classList.add('copied')
setTimeout(() => {
el.classList.remove('copied')
Expand Down