I need to copy any selection from a webpage to the clipboard, it can be on a div, text input, password input, span, etc.
I have the following function that does this for me, but the challenge is have the returned value from the function to be set on the clipboard
const getSelectionText = () => {
let text = "";
let activeDomElement = document.activeElement;
let activeDomElementTagName = activeDomElement ? activeDomElement.tagName.toLowerCase() : null;
if (
(activeDomElementTagName === 'textarea') || (activeDomElementTagName === 'input' &&
/^(?:text|search|password|tel|url)$/i.test(activeDomElement.type)) &&
(typeof activeDomElement.selectionStart === "number")
) {
text = activeDomElement.value.slice(activeDomElement.selectionStart, activeDomElement.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
Any idea, or links to resources would be helpful, thanks