Reputation: 2153
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?
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>
Upvotes: 2
Views: 2650
Reputation: 2153
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.
Upvotes: 1
Reputation: 149
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.
Upvotes: 1
Reputation: 2930
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()
Upvotes: 2