clipboard-copy
Advanced tools
Comparing version 1.0.1 to 1.1.0
36
index.js
@@ -1,23 +0,33 @@ | ||
/* global Range */ | ||
module.exports = clipboardCopy | ||
function clipboardCopy (text) { | ||
var div = document.createElement('div') | ||
div.textContent = text | ||
document.body.appendChild(div) | ||
// A <span> contains the text to copy | ||
var span = document.createElement('span') | ||
span.textContent = text | ||
span.style.whiteSpace = 'pre' // Preserve spaces and newlines | ||
var range = new Range() | ||
range.selectNode(div) | ||
window.getSelection().addRange(range) | ||
// An <iframe> isolates the <span> from the page's styles | ||
var iframe = document.createElement('iframe') | ||
iframe.sandbox = 'allow-same-origin' | ||
var successful = false | ||
document.body.appendChild(iframe) | ||
var win = iframe.contentWindow | ||
win.document.body.appendChild(span) | ||
var selection = win.getSelection() | ||
var range = win.document.createRange() | ||
var success = false | ||
try { | ||
successful = document.execCommand('copy') | ||
selection.removeAllRanges() | ||
range.selectNode(span) | ||
selection.addRange(range) | ||
success = win.document.execCommand('copy') | ||
} catch (err) {} | ||
window.getSelection().removeAllRanges() | ||
div.remove() | ||
selection.removeAllRanges() | ||
iframe.remove() | ||
return successful | ||
return success | ||
} |
{ | ||
"name": "clipboard-copy", | ||
"description": "Lightweight copy to clipboard for the web", | ||
"version": "1.0.1", | ||
"version": "1.1.0", | ||
"author": { | ||
@@ -6,0 +6,0 @@ "name": "Feross Aboukhadijeh", |
@@ -14,4 +14,8 @@ # clipboard-copy [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] | ||
modern web browsers using the fewest bytes. To do so, this package only supports | ||
modern browsers. No fallback using Adobe Flash, no hacks. Just 25 lines of code. | ||
modern browsers. No fallback using Adobe Flash, no hacks. Just 30 lines of code. | ||
Unlike other implementations, text copied with `clipboard-copy` is clean and | ||
unstyled. Copied text will not inherit HTML/CSS styling like the page's background | ||
color. | ||
Works in the browser with [browserify](http://browserify.org/)! | ||
@@ -18,0 +22,0 @@ |
4758
6
35
56