Repository URL to install this package:
|
Version:
4.0.61 ▾
|
/**
* @see https://w3c.github.io/clipboard-apis/#clipboard-event-paste
* @see https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
*/
const IS_BROWSER = typeof document === 'object'
export function isOS(): boolean {
return (navigator.userAgent.match(/ipad|iphone/i) ? true : false)
}
export function copyToClipboard(urlToCopy: string): void {
if (IS_BROWSER) {
const listener = event => {
event.clipboardData.setData('text/plain', urlToCopy)
event.preventDefault()
}
document.addEventListener('copy', listener)
document.execCommand('copy')
document.removeEventListener('copy', listener)
}
}
export function makeEditable(dom: Element): void {
if (IS_BROWSER) {
dom.contentEditable = true
dom.readonly = false
}
}
export function createElement(text: string, scoped): void {
console.debug('[Copy] creating element')
if (IS_BROWSER) {
scoped.textArea = document.createElement('textArea')
scoped.textArea.value = text
scoped.textArea.innerHTML = text
makeEditable(scoped.textArea)
document.body.appendChild(scoped.textArea)
// window.textarea = scoped.textArea
scoped.actions.push('appended textArea')
}
}
export function selectText(scoped): void {
console.debug('[Copy] selecting text')
if (IS_BROWSER) {
const range = document.createRange()
range.selectNodeContents(scoped.textArea)
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
scoped.textArea.setSelectionRange(0, 999999)
scoped.actions.push('set selection range')
}
}
export function executeCopyToClipboard(scoped): void {
console.debug('[Copy] executing copy')
if (IS_BROWSER) {
document.execCommand('copy')
document.body.removeChild(scoped.textArea)
}
}
export function copy(text: string): void {
if (IS_BROWSER) {
const scoped = {
textArea: document.createElement('textArea'),
editableDiv: document.createElement('div'),
actions: [],
}
if (isOS()) {
console.debug('[Copy] iOS')
createElement(text, scoped)
selectText(scoped)
executeCopyToClipboard(scoped)
} else {
console.debug('[Copy] native export functionality')
copyToClipboard(text)
}
}
}