Search code examples
javascriptphpinputhidden-fieldexeccommand

Make execCommand("Copy") work on hidden input tags


I'm currently working with a function hard coded in javascript in order to copy a tag's custom address combined with a pre-defined link. What I made is make an input type text element and set its value to what I want to copy but what happens turns out it didn't work the way I wanted to be. After pressing Ctrl +V, it pasted the second to the latest value in my device's clipboard. How to make execCommand("Copy") to work on a hidden input tag? (The function is called upon an img tag's onclick attribute)

function shareFile() {
        var hiddenItem = document.createElement("input");
        hiddenItem.type = "text";
        hiddenItem.setAttribute("style","display: none");
        hiddenItem.value = <?php echo (isset($_SERVER['HTTPS'])?"\"https://":"\"http://").$_SERVER['SERVER_NAME']."/filesystem/openfile.php?dir=\" + " ?> encodeURI(this.parentNode.parentNode.parentNode.getAttribute("r-directory"));
        hiddenItem.select();
        console.log(hiddenItem.value);
        document.execCommand("Copy");
        // location.href = "resources.php?smsg=The file's link has been successfully copied to your clipboard." <?php if (!empty($_GET['dir'])) echo " + \"&dir=".$_GET['dir']."\""?>;
        return false;

    }

P.S. As much a possible no jQuery please! Thank you.


Solution

  • The execCommand works to those elements added to the any part of the document element.

    the code lacks document.querySelector("body").appendChild(hiddenItem);

    and can be hidden after executing the command -> hiddenItem.setAttribute("style","display: none");