2

So this is how I extract the copied text from clipboard:

const data = event.clipboardData.getData('text/html');

But this code does not work if I copied a URL. The data will be "" empty. Not sure why is it different with a normal text.

How do I get the copied URL?


EDIT

The event I got is from paste event:

paste(event: ClipboardEvent) {
  const data = event.clipboardData.getData('text/html');
}

From this HTML element (I am using Angular):

<div
    id="content"
    contentEditable="true"
    (paste)="paste($event)"
></div>

3 Answers 3

2

Not sure what is the event in your code, but you can get data from clipboard anywhere in your browser via Clipboard API

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/readText

const copiedData = await navigator.clipboard.readText()
Sign up to request clarification or add additional context in comments.

1 Comment

I am using Angular, the event is from paste event from a contenteditable div.
1

So from what I've read from this Codepen, the code takes the textContent from the quote blocks and then put them all in the clipboard

handleCopyClick.addEventListener('click', () => {
    let text = quoteText.textContent;
    let author = quoteAuthor.textContent;
    navigator.clipboard.writeText(`${text} ${author}`);
});

Adapting to your case though, the code would look something like this:

paste(event: ClipboardEvent) {
  let url = urlBlock.textContent;
  navigator['clipboard'].writeText(`${url}`)
}

Props to this FreeCodeCamp article for the inspiration. This one SO post might also answer some of your questions too.

Comments

1

Actually I found that the clipboardData sometimes hold different types of string. In my code:

const data = event.clipboardData.getData('text/html');

This only extract text/html type.

There are other types like text/plain. So this is my solution:

let data = event.clipboardData.getData('text/html');
data = data && data.length > 0 ? data : event.clipboardData.getData('text/plain');

If text/html is empty, then get text/plain data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.