The context menu is managed by the browser, which decides whether to add a Copy (along with Cut and Paste) command in it. It can happen only when the context menu is opened on an user selection.
You can add a listener for the contextmenu
event, which you can cancel and you can therefore create your custom context menu - which is pretty cool, but you won't be able to access to the clipboard without the help of some fancy technology like Flash.
There's a (dirty) trick you can use, though. But the <textarea>
trick is a trick anyway. Style it like this:
textarea {
position: absolute;
margin: 0;
padding: 0;
border: 0 none;
opacity: 0;
}
Now you can add an event listener for the contextmenu
event:
var textarea = document.getElementsByTagName("TEXTAREA")[0];
document.addEventListener("contextmenu", function(e) {
textarea.style.zIndex = 10000; // must be high enough
textarea.style.left = e.pageX + "px";
textarea.style.top = e.pageY + "px";
textarea.setSelectionRange(0, textarea.value.length);
setTimeout(function() {
textarea.style.zIndex = -10000; // must be low enough
}, 10);
});
What you'd be doing here is to place the textarea right below the cursor and select its whole content, so that the cursor will actually be on the selection.
The textarea must be on top of all the other elements, so you have to set its z-index
style property to a high value. But then you will not want a "ghost" floating on your page which may prevent the expected mouse behaviour, so you immediately after you push it behind all the other elements (hence the setTimeout
).
There, you have a working Copy on the context menu.
I've tested it on Chrome only, sorry. Should work on other browsers I guess, you only have to test. Will not work on IE8 and lower (which use attachEvent
instead of addEventListener
, and have a totally different way to select the text - check it out) and definitely not in IE8 (which always prevents the context menu to appear if you set a contextmenu
event listener - must use the mousedown
event and check for right clicks).
Caveat: depending on where the user clicks, the textarea may go outside the bottom and right page boundaries, thus causing the page scrollbars to appear. You can try to resize the textarea to be 1px wide and tall, and setting overflow: hidden
.
Well, this answer has been quite informative for my own self too. Hope you'll like it.
Edit: live test