Reputation: 19305
Consider the following jsfiddle where the user can click on a div containing bold text and then do a copy (ctrl+c win cmd+c mac) to copy the html to the clipboard as HTML. If you then paste into for example a gmail you get the html formatting.
Basically the 'copyHtmlToClipboard' function creates a hidden div, copy the html to it, selects it with document.createRange and then calls document.execCommand('copy')
function copyHtmlToClipboard(html) {
var div = document.createElement("div");
div.style.opacity = 0;
div.style.position = "absolute";
div.style.pointerEvents = "none";
div.style.zIndex = -1;
div.setAttribute('tabindex', '-1'); // so it can be focused
div.innerHTML = html;
document.body.appendChild(div);
var focused=document.activeElement;
div.focus();
window.getSelection().removeAllRanges();
var range = document.createRange();
// not using range.selectNode(div) as that makes chrome add an extra <br>
range.setStartBefore(div.firstChild);
range.setEndAfter(div.lastChild);
//range.selectNode(div);
window.getSelection().addRange(range);
var ok=false;
try {
ok = document.execCommand('copy');
} catch (err) {
console.log(err);
}
if (!ok) console.log('execCommand failed!');
window.getSelection().removeAllRanges();
document.body.removeChild(div);
focused.focus();
}
On windows Chrome/Firefox this works fine.
However on Mac Chrome execCommand returns false.
How can I make this code work on Mac ?
Thx!
Upvotes: 0
Views: 2435
Reputation: 19305
As far as I can tell this is a chrome bug see:
https://bugs.chromium.org/p/chromium/issues/detail?id=552975
Upvotes: 0
Reputation: 9766
It happens because you are allowed to call copy
command only after some events that caused by user actions.
These events are named "Semi-trusted events" and you can find the list in spec. copy
event is not in the list, so can't copy text in your event handler. You can listen to keyup
event instead and then trigger your actions after check that ctrl+c
was pressed
Upvotes: 1
Reputation: 9356
Safari doesn't have support for copy
and cut
commands.
Upvotes: 1