How do I copy to the clipboard in JavaScript? -
what best way copy text clipboard? (multi-browser)
i have tried:
function copytoclipboard(text) { if (window.clipboarddata) { // internet explorer window.clipboarddata.setdata("text", text); } else { unsafewindow.netscape.security.privilegemanager.enableprivilege("universalxpconnect"); const clipboardhelper = components.classes["@mozilla.org/widget/clipboardhelper;1"].getservice(components.interfaces.nsiclipboardhelper); clipboardhelper.copystring(text); } }
but in internet explorer gives syntax error. in firefox, says unsafewindow not defined
.
edit nice trick without flash: how trello access user's clipboard?
browser support
the javascript document.execcommand('copy')
support has grown, see links below browser updates:
- ie10+ (although this document indicates support there ie5.5+).
- google chrome 43+ (~april 2015)
- mozilla firefox 41+ (shipping ~september 2015)
- opera 29+ (based on chromium 42, ~april 2015)
simple example
var copytextareabtn = document.queryselector('.js-textareacopybtn'); copytextareabtn.addeventlistener('click', function(event) { var copytextarea = document.queryselector('.js-copytextarea'); copytextarea.select(); try { var successful = document.execcommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('copying text command ' + msg); } catch (err) { console.log('oops, unable copy'); } });
<p> <button class="js-textareacopybtn" style="vertical-align:top;">copy textarea</button> <textarea class="js-copytextarea">hello i'm text</textarea> </p>
complex example: copy clipboard without displaying input
the above simple example works great if there textarea
or input
element visible on screen.
in cases might wish copy text clipboard without displaying input
/ textarea
element. 1 example of way work around (basically insert element, copy clipboard, remove element):
tested google chrome 44, firefox 42.0a1 , ie 11.0.8600.17814.
function copytexttoclipboard(text) { var textarea = document.createelement("textarea"); // // *** styling step not required. *** // // why here? ensure: // 1. element able have focus , selection. // 2. if element flash render has minimal visual impact. // 3. less flakyness selection , copying **might** occur if // textarea element not visible. // // likelihood element won't render, not flash, // of these precautions. in ie element // visible whilst popup box asking user permission // web page copy clipboard. // // place in top-left corner of screen regardless of scroll position. textarea.style.position = 'fixed'; textarea.style.top = 0; textarea.style.left = 0; // ensure has small width , height. setting 1px / 1em // doesn't work gives negative w/h on browsers. textarea.style.width = '2em'; textarea.style.height = '2em'; // don't need padding, reducing size if flash render. textarea.style.padding = 0; // clean borders. textarea.style.border = 'none'; textarea.style.outline = 'none'; textarea.style.boxshadow = 'none'; // avoid flash of white box if rendered reason. textarea.style.background = 'transparent'; textarea.value = text; document.body.appendchild(textarea); textarea.select(); try { var successful = document.execcommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('copying text command ' + msg); } catch (err) { console.log('oops, unable copy'); } document.body.removechild(textarea); } var copybobbtn = document.queryselector('.js-copy-bob-btn'), copyjanebtn = document.queryselector('.js-copy-jane-btn'); copybobbtn.addeventlistener('click', function(event) { copytexttoclipboard('bob'); }); copyjanebtn.addeventlistener('click', function(event) { copytexttoclipboard('jane'); });
<div style="display:inline-block; vertical-align:top;"> <button class="js-copy-bob-btn">set clipboard bob</button><br /><br /> <button class="js-copy-jane-btn">set clipboard jane</button> </div> <div style="display:inline-block;"> <textarea class="js-test-textarea" cols="35" rows="4">try pasting here see have on clipboard: </textarea> </div>
additional notes
only works if user takes action
all document.execcommand('copy')
calls must take place direct result of user action, e.g. click event handler. measure prevent messing users clipboard when don't expect it.
see google developers post here more info.
clipboard api
note full clipboard api draft specification can found here: https://w3c.github.io/clipboard-apis/
is supported?
document.querycommandsupported('copy')
should returntrue
if command "is supported browser".- and
document.querycommandenabled('copy')
returntrue
ifdocument.execcommand('copy')
succeed if called now. checking ensure command called user-initiated thread , other requirements met.
however example of browser compatibility issues, google chrome ~april ~october 2015 returned true
document.querycommandsupported('copy')
if command called user-initiated thread.
note compatibility detail below.
browser compatibility detail
whilst simple call document.execcommand('copy')
wrapped in try
/catch
block called result of user click compatibility use following has provisos:
any call document.execcommand
, document.querycommandsupported
or document.querycommandenabled
should wrapped in try
/catch
block.
different browser implementations , browser versions throw differing types of exceptions when called instead of returning false
.
different browser implementations still in flux , clipboard api still in draft, remember testing.
Comments
Post a Comment