{"id":2132,"date":"2015-05-24T13:09:04","date_gmt":"2015-05-24T07:39:04","guid":{"rendered":"http:\/\/codetheory.in\/?p=2132"},"modified":"2015-05-24T13:13:32","modified_gmt":"2015-05-24T07:43:32","slug":"javascript-copy-to-clipboard-without-flash-using-cut-and-copy-commands-with-document-execcommand","status":"publish","type":"post","link":"https:\/\/codetheory.in\/javascript-copy-to-clipboard-without-flash-using-cut-and-copy-commands-with-document-execcommand\/","title":{"rendered":"JavaScript Copy to ClipBoard (without Flash) using Cut and Copy Commands with document.execCommand()"},"content":{"rendered":"

Using the cut<\/code> and copy<\/code> commands via document.execCommand()<\/code><\/a>, a text selection can be cut or copied to the user’s clipboard in Chrome 43+, Opera 29+ and IE 10+. This means we can now cater to a part of our web userbase with the copy to clipboard feature without using Flash. Let’s write some code to see these commands in action.<\/p>\n

<\/p>\n

Here’s a simple HTML representing an input field with a button to copy the contents of the field.<\/p>\n

\r\n<input id="url_field" type="url" value="http:\/\/google.com">\r\n<input id="copy_btn" type="button" value="copy">\r\n<\/pre>\n

and here’s the JavaScript magic:<\/p>\n

\r\nvar copyBtn = document.querySelector('#copy_btn');\r\ncopyBtn.addEventListener('click', function () {\r\n  var urlField = document.querySelector('#url_field');\r\n  \/\/ select the contents\r\n  urlField.select();\r\n  \r\n  document.execCommand('copy'); \/\/ or 'cut'\r\n}, false);\r\n<\/pre>\n

Supporting Firefox will require a preference change, check out the cut and copy commands here<\/a>. Since your users won’t probably have those preferences changed, feel free to wrap document.execCommand('copy')<\/code> in a try\/catch block to prevent Firefox from throwing errors.<\/p>\n

The example we just covered shows how the text of an input field or a textarea can be selected and eventually copied. But what if the text to copy is not a part of a form field but a general span<\/code> or p<\/code> (or some other HTML) tag. In that case we can use the Selection API to make a selection and then execute the copy command. Let’s change our HTML:<\/p>\n

\r\n<span id="url_field">http:\/\/google.com<\/span>\r\n<input id="copy_btn" type="button" value="copy">\r\n<\/pre>\n

and here goes the JS again:<\/p>\n

\r\nvar copyBtn = document.querySelector('#copy_btn');\r\ncopyBtn.addEventListener('click', function () {\r\n  var urlField = document.querySelector('#url_field');\r\n  \r\n  \/\/ create a Range object\r\n  var range = document.createRange();  \r\n  \/\/ set the Node to select the "range"\r\n  range.selectNode(urlField);\r\n  \/\/ add the Range to the set of window selections\r\n  window.getSelection().addRange(range);\r\n  \r\n  \/\/ execute 'copy', can't 'cut' in this case\r\n  document.execCommand('copy');\r\n}, false);\r\n<\/pre>\n

So we created a Range<\/code><\/a> object using the document.createRange()<\/code><\/a> method and selected our urlField<\/code>. Then using the window.getSelection()<\/code><\/a> method of the Selection API<\/a> we added the “range” of selection (which is the entire URL selection) to our existing set of user selection ranges. Finally, since the text (url) is selected, executing the copy<\/code> command via document.execCommand()<\/code> copies the text to clipboard.<\/p>\n

Make sure to call document.queryCommandSupported()<\/code><\/a> before document.execCommand()<\/code> to check whether a particular editor query command (copy<\/code> and cut<\/code> in this case) is supported by the browser or not. You could possibly disable the copyBtn<\/code> based on the value (true<\/code> or false<\/code>) returned by document.queryCommandSupported()<\/code>.<\/p>\n

This approach of executing copy\/cut commands might seem a little dirty or hacky also because of the need to select the piece of text (programatically) first which has to be copied or cut. The HTML5 Clipboard API<\/a> when properly implemented by all the browsers will solve this problem. With the Clipboard API we’ll have to write something like this (which is much simpler and elegant):<\/p>\n

\r\nvar copyEvent = new ClipboardEvent('copy', { dataType: 'text\/plain', data: 'My string' } );\r\ndocument.dispatchEvent(copyEvent);\r\n<\/pre>\n

This way we can read whatever text from whichever element we want using JS and pass as data<\/code> to the object argument.<\/p>\n

Hope that helps!<\/p>\n","protected":false},"excerpt":{"rendered":"

Using the cut and copy commands via document.execCommand(), a text selection can be cut or copied to the user’s clipboard in Chrome 43+, Opera 29+ and IE 10+. This means we can now cater to a part of our web userbase with the copy to clipboard feature without using Flash. Let’s write some code to … Continue reading “JavaScript Copy to ClipBoard (without Flash) using Cut and Copy Commands with document.execCommand()”<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[152,8],"_links":{"self":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/2132"}],"collection":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/comments?post=2132"}],"version-history":[{"count":3,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/2132\/revisions"}],"predecessor-version":[{"id":2135,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/posts\/2132\/revisions\/2135"}],"wp:attachment":[{"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/media?parent=2132"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/categories?post=2132"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codetheory.in\/wp-json\/wp\/v2\/tags?post=2132"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}