I’m using JavaScript’s Clipboard API to create a “link generator” that allows users to enter a URL, display text, and press a button to copy a link into Office suite/Outlook much the same way Edge works when copying a link from the address bar. It lets users copy HTML link data to the clipboard, so users can paste it directly into Microsoft Office apps (e.g., Outlook, Word, Teams). When pasting into Excel or Teams, the link appears correctly, but pasting into Word or Outlook results in an unwanted line break or “carriage return” after the link.
Here’s my code snippet for copying the link:
function copyLinkToClipboard() {
const linkText = document.getElementById('linkText').value.trim();
const url = document.getElementById('url').value.trim();
const screenReaderText = document.getElementById('screenReaderText').value.trim();
if (!linkText || !url) {
flashButtonError('generateOutlookButton');
document.getElementById('generatedLinkCode').value = 'Error: Please fill out the URL and Display Text fields.';
return;
}
const html = `<a href="${url}"${screenReaderText ? ` title="${screenReaderText}"` : ''}>${linkText}</a>`;
navigator.clipboard.write([
new ClipboardItem({
"text/html": new Blob([html], { type: 'text/html' }),
"text/plain": new Blob([linkText], { type: 'text/plain' })
})
]).then(() => {
flashButtonEffect('generateOutlookButton');
document.getElementById('generatedLinkCode').value = "Link copied. If pasting into Word or Outlook, press Backspace after pasting to remove the included carriage return.";
}).catch(err => {
console.error('Failed to copy: ', err);
flashButtonError('generateOutlookButton');
document.getElementById('generatedLinkCode').value = 'Error: Unable to copy the link. Please try again.';
});
}
Problem: When users paste the copied link into Word or Outlook, it automatically adds a line break, as if the Enter key was pressed after the link. This behavior isn’t ideal, and I’d prefer the cursor to remain directly after the link text without an extra line break. It works fine in Excel and Teams, but not in Word and Outlook.
Question: Is there a way to modify the code so the link doesn’t add this extra line break when pasted in Word or Outlook? Any help or insight would be greatly appreciated!
I’ve tried different formats and experimented with the Blob content types, but haven’t been able to prevent this extra line break.