Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy/Paste in JavaScript?

I know this question was asked like a million times by now, but I couldn't really find a good up-to-date solution.

I've implemented my own menu to provide the user the ability to Cut, Copy and Paste into my WebApp. But I'm not sure how to actually work with the clipboard on Firefox, IE, Safari/Chrome.

Thank you for your help.

like image 417
thedp Avatar asked Dec 23 '09 09:12

thedp


People also ask

How do I paste text into JavaScript?

clipboard. readText(). then((clipText) => (paste. innerText = clipText));

How do I restrict copy and paste in JavaScript?

You can use jquery for this: $('body'). bind('copy paste',function(e) { e. preventDefault(); return false; });

How do I copy a paragraph in JavaScript?

Create the textarea element and add it to the DOM. Populate its value with the text from the paragraph - or any other element. Use the above execCommand('copy') - method to copy the textual content.

How do you copy paste in HTML?

Press CTRL + C. Select "Copy" from the Edit menu in your browser. Right click to display the context menu and select the "Copy" command.


1 Answers

I just wrote a detailed technical blog post on this very subject (I work for Lucidchart and we recently did an overhaul on our clipboard). Included in the post is this fiddle which is a working example of copying and pasting via Javascript.

The good news is that this example gives you working code for setting/getting any supported clipboard data types whenever the user uses a clipboard hotkey.

The bad news is that using your own context menu to copy and paste is problematic. Even Google can't get around this (try using context-menu copy or paste in Google Docs in Firefox). You'll be able to get it to work without too much trouble in IE. This is because you can access the clipboardData object at anytime from Javascript via:

window.clipboardData

(When you attempt to do this outside of a system cut, copy, or paste event, however, IE will prompt the user to grant the web application clipboard permission.)

In Chrome, you can create a chrome extension that will give your web app clipboard permissions (this is what we do for Lucidchart). Then for users with your extension installed you'll just need to fire the system event yourself when they click the menu option:

document.execCommand('copy');

It looks like Firefox has some options that allow users to grant permissions to certain sites to access the clipboard, but I haven't tried any of these personally.

like image 64
Richard Shurtz Avatar answered Oct 20 '22 09:10

Richard Shurtz