GWT: Open window after RPC is prevented by popup b

2019-05-17 02:17发布

问题:

Hi I have a following code:

    button.addClickHandler( new ClickHandler( ) {
        @Override   
        public void onClick( ClickEvent event ) {    
             Call 1 --> Window.open( publicBookingUrl, "_blank", null );                
            dispatcher.execute( new HasServicesAction(true), 
                    new ActionCallback<SomeResult>( ){       
                @Override 
                public void onSuccess( SomeResult result ) {
             Call 2 --> Window.open( publicBookingUrl, "_blank", null );
                } 
            });  
        }        
    });

In Call 1 popup blocker does not block the popup from opening. It successfully opens a window in a new tab or in new window. In Call2 however popup blocker will prevent popup, so user have to explicitly enable popup. I found a post explaining the reasoning behind this: https://groups.google.com/forum/?fromgroups=#!topic/google-web-toolkit/V0s7goJxuhc Unfortunately this solution doesn't work for me.

Does anyone know why this is the case? How can we get around this?

Thanks in advance.

回答1:

As the page you linked to indicated, windows may only be opened as a result of a direct user action. You can get around this by opening the window before your RPC call and setting the URL of the window after the RPC call returns. GWT's built-in Window doesn't expose all of the underlying window object's properties, so a custom implementation is necessary:

public class MyWindow extends JavaScriptObject {
  // All types that extend JavaScriptObject must have a protected,
  // no-args constructor. 
  protected MyWindow() {}

  public static native MyWindow open(String url, String target, String options) /*-{
    return $wnd.open(url, target, options);
  }-*/;

  public native void close() /*-{
    this.close();
  }-*/;

  public native void setUrl(String url) /*-{
    if (this.location) {
      this.location = url;
    }
  }-*/;
}

Then in your click handler:

public void onClick(ClickEvent event) {
  final MyWindow window = MyWindow.open(null, "_blank", null);

  dispatcher.execute(new HasServicesAction(true), 
      new ActionCallback<SomeResult>( ){       
        @Override 
        public void onSuccess(SomeResult result) {
          if (result.isGood()) {
            window.setUrl(publicBookingUrl);
          } else {
            window.close();
          }
        }
      });  
}

Note that, if your call to setUrl() changes the origin of the opened window you won't be able to modify any properties or call any functions afterwards.



回答2:

Get rid of window popups. Use PopupDialog instead.

If a user disabled popups and you found a way to show it, what will this user think about you?