I am making a password creator script, in which I don't want to show the generated password, but only copy the generated password to clipboard.
I have script for achieving the aforementioned functionality as below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="alert(generatePassword())">Generate Password</button>
<script type="application/x-javascript">
function generatePassword() {
var length = 15,
charset1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
charset2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&",
charset3 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&*()!+=~",
retVal = "";
for (var i = 0, n = charset3.length; i < length; ++i) {
retVal += charset3.charAt(Math.floor(Math.random() * n));
}
copyToClipboard2(retVal);
return 'Password ready to be pasted';
}
const copyToClipboard2 = str => {
const el1 = document.createElement('input');
el1.setAttribute('type','text');
// el1.setAttribute('type','hidden');
el1.value = str;
document.body.appendChild(el1);
el1.select();
document.execCommand('copy');
document.body.removeChild(el1);
};
</script>
</body>
</html>
Notice the commented out line, I have commented it because it is not working.
So as I have already mentioned in question, how do I make use of on-the-fly created hidden
input
field to temporary store the password before copying to clipboard, with the same code as above ?