Skip to content

Commit

Permalink
Select a bogus element if nothing is selected. Ugly, but fixes #30 (S…
Browse files Browse the repository at this point in the history
…afari support).
  • Loading branch information
lgarron committed Sep 23, 2016
1 parent 01c4e78 commit dbd90f4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
32 changes: 32 additions & 0 deletions clipboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@
clipboard.copy = (function() {
var _intercept = false;
var _data = null; // Map from data type (e.g. "text/html") to value.
var _bogusSelection = false;

function cleanup() {
_intercept = false;
_data = null;
if (_bogusSelection) {
window.getSelection().removeAllRanges();
}
_bogusSelection = false;
}

document.addEventListener("copy", function(e) {
Expand All @@ -28,6 +33,32 @@
}
});

// Workaround for Safari: https://bugs.webkit.org/show_bug.cgi?id=156529
function bogusSelect() {
var sel = document.getSelection();
// If "nothing" is selected...
if (!document.queryCommandEnabled("copy") && sel.isCollapsed) {
// ... temporarily select the entire body.
//
// We select the entire body because:
// - it's guaranteed to exist,
// - it works (unlike, say, document.head, or phantom element that is
// not inserted into the DOM),
// - it doesn't seem to flicker (due to the synchronous copy event), and
// - it avoids modifying the DOM (can trigger mutation observers).
//
// Because we can't do proper feature detection (we already checked
// document.queryCommandEnabled("copy") , which actually gives a false
// negative for Blink when nothing is selected) and UA sniffing is not
// reliable (a lot of UA strings contain "Safari"), this will also
// happen for some browsers other than Safari. :-()
var range = document.createRange();
range.selectNodeContents(document.body);
sel.addRange(range);
_bogusSelection = true;
}
};

return function(data) {
return new Promise(function(resolve, reject) {
_intercept = true;
Expand All @@ -39,6 +70,7 @@
_data = data;
}
try {
bogusSelect();
if (document.execCommand("copy")) {
// document.execCommand is synchronous: http://www.w3.org/TR/2015/WD-clipboard-apis-20150421/#integration-with-rich-text-editing-apis
// So we can call resolve() back here.
Expand Down
17 changes: 9 additions & 8 deletions clipboard.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit dbd90f4

Please sign in to comment.