0

I'm building a web app right now that has a couple of text-fields that I would ideally like to be able to copy (individually) using a "copy" button next to each field. Right now I'm attempting to write a Pyperclip function in my main file, and then passing that as an onclick value for a button, but as soon as the page loads, the Pyperclip function executes and my clipboard is updated without pressing anything. So for example:

@app.route('/converted.html', methods = ['GET', 'POST'])
def converted():
    pyperclip_Test = pyperclip.copy("apple")

    return render_template('converted.html', 
        pyperclip_Test = pyperclip_Test)

Then in my template file:

<a href="#" onClick = "{{ pyperclip_Test }}; return false">Test</a>
<div>Data that I want to copy</div>

I know the pyperclip function isn't copying that div - I retracted the original data that I can pass - but the problem still remains that the script executes without me pressing the button.

Any idea on how to get this working?

Marc Monforte
  • 11
  • 1
  • 5

1 Answers1

2

you cannot use pyperclip in a webpage ... you are confusing client side and serverside ... you are copying the text on the serverside clipboard, which does nothing for the client(or anyone else)

try something like the following (javascript)

<script>
function clip_text(a_string){
    var input = document.createElement('input')
    input.id="__copyText__";
    input.value = a_string; // OOPS! document.getElementById(divId).innerText;
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    var txt = input.value
    input.remove()
    console.log("OK COPIED: '"+txt+"'")
}
function clip_div(divId){
   return clip_text(document.getElementById(divId).innerText)
}
</script>

and then call it like this

<a href="#" onClick = "clip_div('copyme')">Test</a>
<div id="copyme">Data that I want to copy</div>
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Ah, still learning so my mistake. Tossed your script into my sheet, but it doesn't seem to be working. I'm rusty on my Javascript, but the `clip_div` function I get; the `clip_text` I'm having trouble following what exactly is happening. – Marc Monforte Feb 23 '18 at 19:06
  • ahh i had to change it to set the input value to the string that was passed in ... originally it took a div apparently (I just took it from one of my projects where i have a copy text functionality) – Joran Beasley Feb 23 '18 at 22:20