Question

How to write text in the clipboard in BOLD format using Javascript?

javascript:(() => {
    navigator.clipboard.writeText("From : \n Info : \n Resp : "); 
})();

I am trying to write predefined data in the clipboard directly in bold format whenever I click a button. Here is the code I am using to write data in plain text.

We are able to copy data in bold format & paste it in the same format in other places hence there has to be a way to write bold text directly in the clipboard but I am not able to figure out the code for this

 2  68  2
1 Jan 1970

Solution

 2

Option 1: Clipboard:write

async function setClipboard(text) {
  const type = "text/html";
  const blob = new Blob([text], { type });
  const data = [new ClipboardItem({ [type]: blob })];
  await navigator.clipboard.write(data);
}

then you can call it with

await setClipboard("<strong>strong bold text</strong>")

Option 2: using listener

function copyToClip(str) {
  function listener(e) {
    e.clipboardData.setData("text/html", str);
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
};

you can test it in Chrome Developer console on this screen

copyToClip(document.querySelector("#question > div.post-layout > div.postcell.post-layout--right > div.s-prose.js-post-body > p:nth-child(2)").innerHTML)

Paste it in word to test the formatting.

PS: It has been noted that document.execCommand is deprecated.

2024-07-23
Derviş Kayımbaşıoğlu