Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix copy with formatting for IE #93

Merged
merged 1 commit into from
Feb 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example/index.js

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

32 changes: 20 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

var deselectCurrent = require("toggle-selection");

var clipboardToIE11Formatting = {
"text/plain": "Text",
"text/html": "Url",
"default": "Text"
}

var defaultMessage = "Copy to clipboard: #{key}, Enter";

function format(message) {
Expand Down Expand Up @@ -46,8 +52,16 @@ function copy(text, options) {
e.stopPropagation();
if (options.format) {
e.preventDefault();
e.clipboardData.clearData();
e.clipboardData.setData(options.format, text);
if (typeof e.clipboardData === "undefined") { // IE 11
debug && console.warn("unable to use e.clipboardData");
debug && console.warn("trying IE specific stuff");
window.clipboardData.clearData();
var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]
window.clipboardData.setData(format, text);
} else { // all other browsers
e.clipboardData.clearData();
e.clipboardData.setData(options.format, text);
}
}
});

Expand All @@ -63,16 +77,10 @@ function copy(text, options) {
success = true;
} catch (err) {
debug && console.error("unable to copy using execCommand: ", err);
debug && console.warn("trying IE specific stuff");
try {
window.clipboardData.setData(options.format || "text", text);
success = true;
} catch (err) {
debug && console.error("unable to copy using clipboardData: ", err);
debug && console.error("falling back to prompt");
message = format("message" in options ? options.message : defaultMessage);
window.prompt(message, text);
}
debug && console.error("unable to copy using clipboardData: ", err);
debug && console.error("falling back to prompt");
message = format("message" in options ? options.message : defaultMessage);
window.prompt(message, text);
} finally {
if (selection) {
if (typeof selection.removeRange == "function") {
Expand Down