nope/resources/ui/helpers/clipboard.ts

104 lines
2.8 KiB
TypeScript
Raw Normal View History

2020-10-25 20:14:51 +00:00
/**
* Function to Copy a String to the Clipboard
* @param input
*/
export function writeToClipboard(input: string){
const element = document.createElement('textarea');
const previouslyFocusedElement = document.activeElement as any;
element.value = input;
// Prevent keyboard from showing on mobile
element.setAttribute('readonly', '');
element.style.position = 'absolute';
element.style.left = '-9999px';
element.style.fontSize = '12pt'; // Prevent zooming on iOS
const selection = document.getSelection();
let originalRange: any = false;
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0);
}
document.body.append(element);
element.select();
// Explicit selection workaround for iOS
element.selectionStart = 0;
element.selectionEnd = input.length;
let isSuccess = false;
try {
isSuccess = document.execCommand('copy');
} catch (_) {}
element.remove();
if (originalRange) {
selection.removeAllRanges();
selection.addRange(originalRange);
}
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
previouslyFocusedElement.focus();
}
return isSuccess;
}
2020-10-30 18:30:59 +00:00
export async function readDataFromClipboard(){
if (navigator && (navigator).clipboard) {
const text = await (navigator).clipboard.readText();
return text;
} else if (navigator && (navigator).permissions) {
const permissionStatus = await (navigator).permissions.query({
name: 'clipboard-read'
} as any);
// Listen for changes to the permission state
permissionStatus.onchange = () => {
console.log('Current Permission State is ',permissionStatus.state)
};
}
return null;
}
2020-10-25 20:14:51 +00:00
/**
* Function to Read from Clipboard. Returns a String.
*/
export function readFromClipboard(){
const id = 'paster'+Date.now().toString();
const element = document.createElement('textarea');
const previouslyFocusedElement = document.activeElement as any;
// Prevent keyboard from showing on mobile
// element.setAttribute('readonly', '');
element.style.position = 'absolute';
element.style.left = '300px';
element.style.fontSize = '12pt'; // Prevent zooming on iOS
element.setAttribute('id', id);
document.body.append(element);
document.getElementById(id).focus();
(document.getElementById(id) as any).select();
document.execCommand('paste', true);
const text: string = element.textContent;
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
previouslyFocusedElement.focus();
}
// Remove the Text
element.parentNode.removeChild(element);
return text;
}