Linux SWT浏览器JavaScript.window.close()方法不起作用

时间:2014-09-24 06:40:16

标签: java linux eclipse browser swt

我已经实现了示例swt浏览器应用程序,它在windows操作系统中工作,但是我在linux操作系统中测试的代码相同,浏览器正在打开,但window.close()函数在linux中不起作用。如何解决这个问题?

示例代码

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

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

        browser.addCloseWindowListener(new CloseWindowListener()
        {
            public void close(WindowEvent event)
            {
                System.out.println("closing");
                Browser browser = (Browser) event.widget;
                Shell shell = browser.getShell();
                shell.close();
            }
        });

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

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

}

1 个答案:

答案 0 :(得分:1)

请注意,并非所有浏览器都允许使用window.close()。 Internet Explorer(在使用SWT.NONE时在Windows上使用)允许脚本关闭浏览器窗口(尽管它可能会显示提示)。

Chrome和Firefox(在Windows和Linux上测试)不允许脚本关闭窗口。

由于你无法在Linux上的SWT中真正使用IE,我想不出让window.close()工作的方法。


但是,您可以在SWT Browser中从JavaScript调用Java代码:

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;
    }
}

Vogella提供了一个很好的教程here