简体   繁体   中英

If I select and copy any text on website page it should paste URL of the opened page how to do that using JavaScript

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM