Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

What is the best way to copy text to the clipboard? (multi-browser)

I have tried:

function copyToClipboard(text) {

if (window.clipboardData) { // Internet Explorer window.clipboardData.setData("Text", text); 

} else { unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 

const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper); clipboardHelper.copyString(text); 

   } 

}

but in Internet Explorer, it gives a syntax error. In Firefox, it says unsafeWindow is not defined.

1 Answer

0 votes
by (106k points)
edited by

You should not directly copy to the clipboard in JavaScript it can be wrong, so you can use the following code before copying:-

function copyToClipboard(text) { 

window.prompt("Copy to clipboard: Ctrl+C, Enter", text);

}

When you use this code the user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press Ctrl+C and Enter.

So after the above step, the clipboard copy operation is safe, because the user does it manually.

This is the code to copy to the clipboard and it runs on all the browsers:-

<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy

</button> 

<script> 

function copyToClipboard(text) {

 window.prompt("Copy to clipboard: Ctrl+C, Enter", text);

 } 

</script>

Want to become a Salesforce expert, join Web Development Courses Online Training now! 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...