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!