google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Truy xuất nội dung clipboard dùng JavaScript Truy xuất nội dung clipboard - một vấn không có gì là mới đối với các ứng dụng hoạt động trên nền hệ thống (hệ điều hành), nhưng lại là một vấn đề khá "xương xẩu" với các ứng dụng hoạt động trên nền web. Tuy jsB@nk đã giới thiệu một đoạn mã có thể thực hiện truy xuất dữ liệu của clipboard nhưng vẫn phải xử lí thông qua một ứng dụng trung gian - Flash.

Hôm nay, đến với bài viết này; tác giả sẽ giúp bạn hiểu rõ hơn về cơ chế này cùng với những nguyên nhân, thực trạng và giải pháp cho từng vấn đề cụ thể. Vui lòng xem bài viết để biết chi tiết.


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

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).

Ứng dụng AI Video.com
Tạo video doanh nghiệp của bạn bằng AI chỉ với giọng nói hoặc văn bản

chatGPTaz.com
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn

Ứng dụng AI Video
Ứng dụng video AI MIỄN PHÍ đầu tiên của bạn

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 trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ

Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ

Temu tặng $500 cho người dùng mới
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Tín dụng quảng cáo TikTok miễn phí
Làm chủ quảng cáo TikTok cho hoạt động tiếp thị doanh nghiệp của bạn

Dall-E-OpenAI.com
Tự động tạo ra hình ảnh sáng tạo với AI

chatGPT4.win
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn

Sản phẩm AI đầu tiên của Elon Musk - Grok/UN.com
Nói chuyện với Grok AI Chatbot bằng ngôn ngữ của bạn

Công cụ.win
Mở trung tâm công cụ miễn phí để mọi người sử dụng với hàng trăm công cụ

GateIO.gomymobi.com
Airdrop miễn phí để nhận, chia sẻ lên đến 150.000 đô la cho mỗi dự án

iPhoneKer.com
Tiết kiệm tới 630$ khi mua iPhone 16 mới

Mua Robot Tesla Optimus
Đặt mua Tesla Bot: Robot Optimus Gen 2 ngay hôm nay với giá dưới 20.000 đô la

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web