We use DT with markdown for a documentation which also includes a lot of passwords. Selecting those passwords for copy & paste can be a bit challenging as they may include special characters etc. So I was looking for an easy way to create “password fields”, which can be clicked and their content then get’s copied to the clipboard, like in most popular password applications. Could not find way to do this or did I miss something?
I ended up in writing a small javascript code:
// Create dummy element with a value, which can be selected and copied.
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
// Traverse document and append "onclick" to each <cpy> element.
window.onload = function()
{
pwds = document.querySelectorAll("cpy");
pwds.forEach(pwd => {
// Styling for cpy fields.
pwd.style.fontFamily = "Menlo";
pwd.style.background = "#fdd";
pwd.style.border = "1px solid #800";
pwd.style.borderRadius = "4px";
pwd.style.paddingLeft = ".25em";
pwd.style.paddingRight = ".25em";
// Adding click event to copy its content to clipboard.
pwd.addEventListener('click', () => {
copyToClipboard(pwd.innerText)
document.execCommand("copy");
pwd.style.background = "#000";
pwd.style.color = "#f00";
pwd.style.borderColor = "#f00";
// Change styling back after a moment.
setTimeout(function(){
pwd.style.background = "#fdd";
pwd.style.color = "#000";
pwd.style.border = "1px solid #800";
},250)
})
})
}
In my markdown file I have to include this script at the beginning and use tags around these texts:
<script type="text/javascript" src="x-devonthink-item://703B6ACA-…"></script>
# Some Example
Username: <cpy>John Doe</cpy>, password: <cpy>123</cpy>
I hope this helps others, too. And maybe it can get integrated into DT in the future.