0

I want the user to select the text on the page. If the user copies the text and tries to paste the selected text then he should paste the URL of the page only not the selected text. How we can do that using javascript?

  • A (possibly) related question: [Modify Clipboard content after copy event](https://stackoverflow.com/questions/42089713/modify-clipboard-content-after-copy-event-javascript-jquery) – Yogi Sep 17 '22 at 18:04

1 Answers1

0

This is just a simple demonstration of how you can intercept clipboard copy. Keep in mind, that not all browsers do support this, but in general it works:

// Bind copy interceptor to the document
document.addEventListener('copy', e => {
  // Set current page href to clipboard
  e.clipboardData.setData('text/plain', window.location.href);
  // Prevent default action
  e.preventDefault();
});
html {
  font-size: 14px;
}
.box {
  width: 300px;
  border: 1px solid #000;
  padding: 5px;
  margin-bottom: 15px;
  resize: none;
}
<html>
  <div class="box">
There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain...
  </div>
  Paste to test:
  <div>
    <textarea class="box" rows="3"></textarea>
  </div>
</html>
tarkh
  • 2,424
  • 1
  • 9
  • 12