Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy to clipboard in jupyter notebook

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 ?

like image 600
Uri Goren Avatar asked Oct 17 '22 09:10

Uri Goren


1 Answers

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.

like image 195
Bennett Hardwick Avatar answered Oct 30 '22 15:10

Bennett Hardwick