google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Accessing the System Clipboard content with JavaScript Access System clipboard content - not a new issue in the based system applications (OS), but it is rather complicated with the based Web applications. Although jsB@nk introduced a code can access clipboard data but it still need the middle application - Flash.

Today, within this article, the author will help you better understand this operation with the facts, reality and solutions for each issue. Please view this article for more.


Label: accessing, system clipboard, clipboard data, windows clipboard, Flash

Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

Using Silverlight?

To the point: None of the Silverlight versions (currently up to version 3) does not provide system clipboard access. This is a shame because it interacts well with JavaScript and is supported by all the common browsers (even on Linux via Moonlight).

Mozilla's XUL Approach

Mozilla has this inbuilt plugin called "clipboard helper" which can be accessed with JavaScript using the XUL API. Dion Almaer explored this approach, click here for a demo (try downloading it and viewing it locally on your machine).

The XUL approach has some issues, as pointed out by Dion. If you run the script locally an ugly dialog pops up containing a vague (and scary) message warning the user about the possibility of malicious code being executed. The user's decision can be remembered. However it fails to access the clipboard when not running script from a local file. This can be overcome: One option is to set some obscure user preferences for Mozilla to allow access. This might not be practical, especially if you are planning to use the script on public sites. Another option is to digitally sign the JavaScript containing the XUL clipboard code - which of coarse is a pricey option.

Making use of execCommand

The execCommand JavaScript function is supported by all major browsers. The browsers all support the "Copy" and "Paste" commands. All browsers except for IE only expose the execCommand function for documents with design-mode turned on (for wizzywig editing).

Webkit does not protect the copy command, I wrote a post about this security hole. In both Chrome 2 and Safari 4 (on windows and mac) I managed to copy text to the system clipboard without any security warnings/promptings what-so-ever via execCommand. My assumption is that this will be the same for older versions of Webkit. This is very concerning. Mozilla throws security exceptions which can be only avoided via setting the user preferences or signing the JavaScript code. Opera and Konqueror just does not work. For IE it is possible to use this approach, as well as other approaches with MicrosoftTextRange objects, but it has no benefits over using the clipboardData object since it safeguards the copy and paste operations in the same way.

Implementation

Try it out here. The first time the copy operation is invoked, an inline document in design mode is dynamically created and appended to the main document - thus exposing the execCommand. The inline document contains an textarea and is always hidden from the user. So to copy text to the system clipboard, the textarea's value is set to the text to be copied, then the textarea is displayed, focused and selected, and finally the execCommand("copy") method is invoked. The textarea will never be rendered (i.e. the user will not see a random flash on the page) because it is hidden straight after the copy command has executed (the UI will not refresh until after the script finishes executing).

The demo does have a scrolling issue: since the textarea is selected and focused the scrollbars will change if the iframe is not in view. You can easily overcome this behavior this by placing the iframe in a float (see below regarding keyboard events).

This script will work in IE, the first time the copy operation is executed a dialog will pop up asking the user for the script for permission to access the clipboard. Unfortunately there is no way of telling whether the user allowed or denied access. The MSDN docs specifies that execCommand returns true of false depending if the command succeeds or fails, however it will always return true even if the user denies access. Furthermore, while the prompt is displayed the users will see the internal frame rendered which might be confusing for the user (although this could be better concealed by using floats). The window.clipboardData object would be a better option, even if the user denies access via window.clipboardData, you probably would not want to blast them with any more security-risk dialogs.

Fabricating DOM Events

This is merely an idea, which is a similar approach to the execCommand approach. If it were possible to manually fire CTRL+C and CTRL+V events such that the browsers execute their "default" handlers, then by using similar trickery used with the execCommand implementation on demand access to the clipboard would be possible. However, the Web's sandbox environment does not let JavaScript simulate user interactions (that would be very bad!). Just a thought.

Clipboard Events

IE, Webkit and FF 3+ supports up to six different clipboard events which can be invoked from context menus or key-commands like CTRL+C:

  • onbeforecut
    • FF does not support this.
    • IE raises this event before a context menu is displayed and something in the document is selected.
    • IE only raises these on editable elements.
  • oncut
    • IE only raises these on editable elements.
  • onbeforecopy
    • FF does not support this.
    • IE and Safari raises this event before a context menu is displayed and something in the document is selected.
  • oncopy
    • Only executed when about to copy something in the default handler.
    • Webkit exposes clipboardData on the event object.
  • onbeforepaste
    • FF does not support this.
    • IE raises this event before a context menu is displayed and something in the document is selected.
  • onpaste
    • IE only raises these on editable elements.

Webkit exposes the clipboardData object in clipboard events by attaching it to the event objects. Webkit's clipboardData object is implemented in the same way as IE's clipboardData object.

In order to get text from the clipboard, clipboardData.getData can only be accessed in the onpaste event. This is nice and simple:

		document.body.onpaste = function(e) {
			alert(e.clipboardData.getData("Text"));
			e.preventDefault();
		}

Note: preventing the default behavior is necessary if you are planning to handle the event, but if your code is just sniffing, then exclude the e.preventDefault() call.

Ideally the code would be similar for setting the clipboard data upon copy events. Unfortunately Webkit has a bug where you cannot set clipboard data in any of the clipboard events! You can use a work-around by using the same approach in the following section.

Using Keyboard Events

In most Web applications you do not have to worry about setting/getting the system clipboard data via key presses like CTRL+C, all browsers implement this for you. However, my API needs to get/set system clipboard data whenever the user presses clipboard key combinations like CTRL+C, on an non-editable document. Specifically: on CTRL/CMD+C/X keystrokes, the text to be copied is not the selected text in the document. And, on CTRL/CMD+V keystrokes, no matter where the focus is, the API must be able to retrieve the system clipboard text.

Webkit and FF3+ browsers' default handlers for copying, cutting and pasting occur in the oncopy, oncut and onpaste events respectively. Browsers which do not use clipboard events execute their copy and paste code in their keydown/keypress default handlers.

Click here for the demo. Whenever a clipboard command is raised from a keyboard stroke, a textarea appears and is selected/focused. The browser's default handler then executes its clipboard command on the selected textarea. A timer event is scheduled with no delay so that once the browsers default handler has executed its clipboard command, the timer event is queued afterward - where it then hides the textarea from view.

This approach was inspired from Webkit's lack of support for using clipboardData.setData, I started with a solution which used the oncopy event, which was then generalized to use keyboard events. You may want to use oncopy/onpaste in Webkit/FF3+ browsers instead of keyboard commands - however there is no real benefit from this except for Chrome: Chrome's copy button in its window's context menu is clickable, even if nothing in the document is selected (which raises the oncopy event).

The textarea element is very small and usually displayed outside of the view-port. If the vertical and horizontal scrollbars are not at the hard top or left of the document then the textarea is briefly flashed at the top right section of the window. If for example, the float is positioned at an absolute left position of -100 (out of viewport) but the horozontial scrollbars are scrolled to 40 pixels, the scrollbars would scroll to zero (hard left) whenever the textarea is selected/focused. (Note: restoring them to their original values will just create an ugly scrollbar jolting effect).

Originally I developed a bulky solution without floats, but I stumbled across a blog that had happened to use this same approach but instead using floats (many thanks to Dion).

It is important to avoid race conditions while showing and hiding the textarea before and after the browsers' default handlers for clipboard operations. Clipboard events are guaranteed to work. Opera queues a settimeout with zero delay after all events in the current event batch - onkeydown, onkeypress, onkeyup event sequence is seen as an event batch (see timing-and-synchronization-in-javascript) - so it is safe to use onkeydown in Opera. From my own experiments, my observations are that Firefox's clipboard operations are executed on keypress events. IE and Webkit can only use keydown since clipboard key combinations do not get keypress events. There was no luck with getting Konqureror to work with this approach - KHTML has problems with selecting and focusing on an input element (it works sometimes).

Summary

Go here to see a summary of the explored approaches and their demos (sorry about the external link but my blog layout does not handle large tables!).

Conclusion

The "ideal interface" previously discussed is not possible: there are different contexts in which you may want to copy and retrieve data to and from the clipboard, so packaging up a universal clipboard solution is not realistic.

There is a lot of (hacky) code to get cut, copy and paste in a JavaScript application. Is it really worth the time and effort to support copy and paste? I think so. Copy and paste is extremely useful, especially for some type of web-page editor. Microsoft found that paste was the most commonly used operation in their Word application, and copy was the third most common (see http://blogs.msdn.com/jensenh/archive/2005/11/07/489864.aspx and most-used-features-commands-in-microsoft-word-and-a-few-design-lessons).

AIVideo-App.com
Generate your business videos by AI with voice or just text

chatGPTaz.com
Talk to ChatGPT by your mother language

AppAIVideo
Your first FREE AI Video App

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing

Dall-E-OpenAI.com
Generate creative images automatically with AI

chatGPT4.win
Talk to ChatGPT by your mother language

First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language

Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

iPhoneKer.com
Save up to 630$ when buy new iPhone 16

Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web