w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Linux SWT Browser JavaScript.window.close() method not working

Keep in mind that window.close() is not allowed in all browsers. Internet Explorer (which is used on Windows when you use SWT.NONE) allows scripts to close browser windows (although it may show a prompt).

Chrome and Firefox (tested on Windows and Linux) won't allow scripts to close the window.

Since you can't really use IE in SWT on Linux, I can't think of a way to make window.close() work.


However, you can call Java code from JavaScript within the SWT Browser:

private static Browser browser;

public static void main(String[] args)
{
    Display display = new Display();
    Shell shell = new Shell(display);

    browser = new Browser(shell, SWT.NONE);
    browser.setBounds(5, 5, 600, 600);

    browser.addListener(SWT.Close, new Listener()
    {
        @Override
        public void handleEvent(Event event)
        {
            System.out.println("closing");
            Browser browser = (Browser) event.widget;
            Shell shell = browser.getShell();
            shell.close();
        }
    });

    new CustomFunction(browser, "theJavaFunction");

    browser.setText("<a href="javascript:theJavaFunction();">Close
this Window</a>");
    shell.open();

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

private static class CustomFunction extends BrowserFunction
{
    CustomFunction(Browser browser, String name)
    {
        super(browser, name);
    }

    @Override
    public Object function(Object[] arguments)
    {
        System.out.println("theJavaFunction() called from javascript");
        Shell shell = browser.getShell();
        shell.close();
        return null;
    }
}

There's a nice tutorial by Vogella here.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.