Question

I have a RichTextArea

 private RichTextArea richTextArea;

and I'm trying to capture a paste event like this:

DOM.sinkEvents((com.google.gwt.user.client.Element) richTextArea.getElement(), com.google.gwt.user.client.Event.ONPASTE);
DOM.setEventListener((com.google.gwt.user.client.Element) richTextArea.getElement(), new EventListener(){
  @Override public void onBrowserEvent(Event event) {
     switch (event.getTypeInt()) {
        case Event.ONPASTE: Window.alert("hey");break;
     }
   }
});

But it doesn't work, when I paste text on the richTextArea the alert is not triggered.

Any idea how to capture this paste event?

Thanks!

Was it helpful?

Solution

You cannot add the event to the RichTextArea, which actually is an iframe, but to it's body.

Although you could use jsni, I would use gwtquery because its simplicity:

// First attach the widget to the DOM
RootPanel.get().add(richTextArea);

// We only can bind events to the content, once the iframe document has been created, 
// and this happens after it has been attached. Note that richtTextArea uses a timeout
// to initialize, so we have to delay the event binding as well
$(richTextArea).delay(1, lazy().contents().find("body").bind(Event.ONPASTE, new Function(){
  @Override public boolean f(Event e) {
    Window.alert("OnPaste");
    return true;
  }
}).done());

OTHER TIPS

Have you seen the rendered HTML of RichTextArea ? it's an iframe not an actual textarea input type. it sets the user input under a body element. So that's why you don't get sinked onpaste events. For example if you listen to onpaste on TextArea widget it works fine.

private static class MyTextArea extends TextArea
    {
        public MyTextArea()
        {
            sinkEvents(Event.ONPASTE);              
        }

        @Override
        public void onBrowserEvent(Event event)
        {
            if(event.getTypeInt() == Event.ONPASTE)
            {
                Window.alert("text pasted !");
            }
            super.onBrowserEvent(event);
        }
    }

maybe you can bind a handler to that iframe body element using JSNI and get the callback on that event (haven't tried it though )

Just for the sake of completeness, the native (JSNI) solution would be something like:

setPastehandler(richTextArea.getElement());

private native void setPasteHandler(Element e) /*-{
    e.contentDocument.onpaste = function (event) {
        alert("pasted!");
    };
}-*/;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top