Reputation: 13690
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 ?
Upvotes: 5
Views: 2644
Reputation: 1399
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.
Upvotes: 4
Reputation: 166
You could try using selenium and phantomJS to run the code in a headless browser in the background.
Upvotes: -1