I'd like to implement a clipboard copy in a jupyter notebok.
The jupyter notebook is running remotely, thus I cannot use pandas.to_clipboard
or pyperclip
and I have to use javascript
This is what I came up with:
def js_code_copy(content)
return """
var body = document.getElementsByTagName('body')[0];
var tmp_textbox = document.createElement('input');
body.appendChild(tmp_textbox);
tmp_textbox.setAttribute('value', '{content}');
tmp_textbox.select();
document.execCommand('copy');
body.removeChild(tmp_textbox);
""".format(content=content.replace("'", '\\'+"'"))
Note that the code does what it's supposed to if I run it in my browser's console.
However, if I run it in jupyter with:
from IPython.display import display, Javascript
content = "boom"
display(Javascript(js_code_copy("Copy me to clipboard")))
Nothing works,
Any ideas ?
For security reasons, your browser disables the use of document.execCommand
if the method wasn't called as a result of a user action, e.g clicking a button.
Since you're injecting and running Javascript on the page, this is not considered a user action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With