Disable SWT Browser Drop Handling

I like using the SWT Browser component for embedded web application functionality in a desktop app. Unfortunately, users can drop whatever they want on the Browser and it will load the dropped item.

Let’s take a look at what I’m talking about

SWT Browser is sweet for displaying various content types like PDF

Not looking so sweet after dropping a URL on it!

Coming up with a fix

My first line of thought was to disable drop handling using a DropTarget and DropTargetListener. Short story – that doesn’t work as of SWT 3.5M6.

Well, you can’t disable drop handling in the Browser component, as the title suggests. It *is possible* to capture location change events and cancel them before they actually change the browser’s location. Since location change events fire when a user drops an item on the Browser component, canceling them achieves the desire effect of disabling drop handling.

Disable Browser Location Change Event

See the code snippet below for a simple solution for preventing the Browser from loading user dropped items.

// Prevent browser from changing to unwanted location
// Assumes you have a Browser reference named 'browser'
browser.addLocationListener(new LocationListener() {

    public void changed(LocationEvent event) {
        System.out.println("Changed location to " + event.location);
    }

    public void changing(LocationEvent event) {
        System.out.println("Changing location to " + event.location);
        event.doit = false; // this cancels the browser location change
    }
});

Further Customization

The above example can be tailored to suit your needs. You can put conditions in the ‘changing()’ method to only allow your valid location URLs. To really polish this off, we can add a ‘disabled’ cursor action when the user tries to drop an item on the Browser.

new DropTarget(browser, DND.DROP_NONE);

There! Now the user knows that the drop is invalid and the actual drop will not result in the Browser loading the dropped item.

Leave a Reply