GWT中复制到剪贴板

今天看到有个Google Code的项目,叫ZeroClipboard:http://code.google.com/p/zeroclipboard/

大意是使用flash作为媒介,将内容复制到剪贴板。这比用纯javascript好,因为不同浏览器会出于安全的原因,有不同反应,例如IE会给出提示,有的浏览器不支持复制到剪贴板。

但是用flash就可以复制。例子就是VeryCd,看“复制选中的连接”按钮是一个flash。看来flash的安全沙箱没有限制将内容复制到剪贴板 

 

但是也是有限制的: 

1 根据ZeroClipborad的人们说,这些flash必须通过网络加载。

 Zero Clipboard Does Not Work From Local Disk


This is a security restriction by Adobe Flash Player. Unfortunately, since we are utilizing the JavaScript-to-Flash interface ("ExternalInterface") this only works while truly online (if the page URL starts with "http://" or "https://"). It won't work running from a local file on disk.

However, there is a way for you to edit your local Flash Player security settings and allow this. Go to this website:

http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html

And add the path to your local "ZeroClipboard.swf" file to the trusted files list, or try the "allow all" option.


2 flash虽然提供复制功能,但是前提是要通过用户的一次点击。意思就是不能在javascript中通过函数的方式setText就复制到剪贴板,而是调用了这个setText函数后,用户的鼠标在flash上有了一次点击,才可以。

This library is fully compatible with Flash Player 10, which requires that the clipboard copy operation be initiated by a user click event inside the Flash movie.  

这里和使用flash上传文件的swfupload有同样的问题。 


使用ZeroClipboard,可以将网页内容复制到剪贴板。但是ZeroClipboard没有GWT封装,我们项目是用GWT的,所以就学着swfupload的GWT封装,把ZeroClipboard也封装成GWT可以调用的形式。

1 先封装了一个zeroclipboard.jar 

2 项目中使用的是GXT控件库,为了和控件紧密结合,写了一个ZClipboardBinder类,将两者结合起来

3 使用方法见下(Zeroclipboard_test.java)

 1 package zero.clipboard.test.client;
 2 
 3 import java.util.Date;
 4 
 5 import zero.clipboard.test.client.ZClipboardBinder.ClipboardListener;
 6 
 7 import com.extjs.gxt.ui.client.widget.LayoutContainer;
 8 import com.extjs.gxt.ui.client.widget.button.Button;
 9 import com.google.gwt.core.client.EntryPoint;
10 import com.google.gwt.user.client.ui.RootPanel;
11 
12 /**
13  * Entry point classes define <code>onModuleLoad()</code>.
14  */
15 public class Zeroclipboard_test implements EntryPoint {
16 
17     public void onModuleLoad() {
18         LayoutContainer c = new LayoutContainer();
19         c.setSize(400300);
20 
21         Button btn = new Button("Copy Hello World");
22         // 将控件和ZeroClipboard绑定
23         // ZClipboardBinder.bind(btn, "Hello World");
24         ZClipboardBinder.bind(btn, new ClipboardListener() {
25 
26             @Override
27             public String prepareCopy() {
28                 return (new Date()).toString();
29             }
30         });
31         c.add(btn);
32 
33         RootPanel.get().add(c);
34     }
35 }
36 

相关下载都在附件中了。 

  /Files/anic/attachment.zip

示意结果

 
点击按钮后——其实是点击了上面的flash,使用ctrl+v,就能看到结果。

 

现在发现有很多有意义的功能都不能用javascript实现,例如多文件上传和复制到剪贴板,都是通过flash做中介,“曲线”实现的 ,不知道最后HTML5有没有解决这些问题,不用我们兜兜转转。

原文地址:https://www.cnblogs.com/anic/p/1679679.html