0 votes
1 view
in Web Technology by (47.8k 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 (107k points)

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>

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...