function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
M Relova 9M Relova 9 

Copy to clipboard only works on 2nd to nth click

Does anyone know why our Javascript code works only on the 2nd to nth try in SFDC, but on 1st attempt in stand-alone HTML?

We are creating "button" that executes Javascript to copy certain contents of a Case into the clipboard. The same result is seen under Chrome, IE, Safari, and Firefox.

The problem code we're attaching to the button is below.  Works 2nd to nth try:
{!REQUIRESCRIPT("/soap/ajax/38.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/38.0/apex.js")}

console.log('browser supports copy?: ' + document.queryCommandSupported("copy"));

var text = 'Ticket #: {!Case.Id}\n';

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

var tempInput = document.createElement("textarea");
tempInput.setAttribute('id', 'copyid');
tempInput.value = text;
document.body.appendChild(tempInput);

i = document.getElementById('copyid');
i.select();

try {
    var result = document.execCommand("Copy");

    // clicking button this JS is embedded in first time results in a FALSE
    // clicking button this JS is embedded in second to nth time results in a TRUE
    console.log('execcommand copy result: ' + result);
}
catch (e) {
    console.log('Copy exception: ' + e);
}


And here is the same code in a standalone HTML which works 1st to nth click:
<script>

function doit() {

    console.log ('browser supports copy?: ' + document.queryCommandSupported("copy"));

    var text = 'blah blah';
    var tempInput = document.createElement("textarea");
    tempInput.setAttribute('id', 'copyid');
    tempInput.value = text;
    document.body.appendChild(tempInput);
    document.getElementById('copyid').select();

    try {
        var result = document.execCommand("copy", false, null);
        // clicking button this JS is embedded in first time results in a FALSE
        // clicking button this JS is embedded in second to nth time results in a TRUE
        console.log('execcommand copy result: ' + result);
    }
    catch (e) {
        console.log('Copy exception: ' + e);
    }

    document.body.removeChild(tempInput);

</script>

<input type="button" value="copy text" onClick="doit()">

 
satya aryasatya arya
Hello Relova,

Did you tried it on all browser? If it working on any of the major browser, then definitely one element must be browser specific.
Or try to use static text in "var text" variable (no Case.Id)

Thanks,
Satya
Jason SparksJason Sparks
Great idea! If you need help, you can use our research therapy template from regain therapy review (https://drmental.org/regain-review) or hire a professional to write your therapy. Our custom research help service is ready to work on your therapy while you enjoy your time. However, no matter which option you choose, both must conform to a specific format.