google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Accéder au contenu du Presse-papiers du système avec JavaScript Système d'accès contenu du presse-papier - pas une question nouvelle dans le système fondé sur des applications (OS), mais il est assez compliqué avec les applications basées Web. Bien que JSB @ nk a présenté un code peut accéder à des données du presse-papier, mais il reste encore le moyen d'application - Flash.

Aujourd'hui, dans cet article, l'auteur vous aideront à mieux comprendre cette opération avec les faits, la réalité et des solutions pour chaque problème. S'il vous plaît consulter cet article pour en savoir plus.


�tiquette: l'accès aux, Presse-papiers, presse-papiers de données, Presse-papiers de Windows, Flash

G�n�rez vos vid�os d'entreprise par l'IA avec la voix ou simplement du texte



Votre premi�re application vid�o AI GRATUITE ! Automatisez votre premi�re vid�o AI. Cr�ez votre vid�o professionnelle en 5 minutes gr�ce � l'IA. Aucun �quipement ni comp�tence en montage vid�o requis. Production vid�o sans effort pour les sp�cialistes du marketing de contenu.
Application vid�o AI ILLIMIT�E gratuite � port�e de main

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
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte

chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle

AppAIVidéo
Votre première application vidéo AI GRATUITE

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

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app

Your next top AI Assistant
Claude AI, developed by Anthropic

Your next top AI Assistant
Claude AI, developed by Anthropic

Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise

Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA

chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle

Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue

Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils

GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet

iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16

Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web