2014-09-24 60 views
0

我已经实现样品SWT浏览器应用程序,它的工作在Windows操作系统中,但我已经在Linux操作系统中测试相同的代码,浏览器被打开,但window.close()功能不在linux上工作。如何解决这个问题?Linux的SWT浏览器JavaScript.window.close()方法不工作

示例代码

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

记住window.close()不是在所有的浏览器允许的。 Internet Explorer(当您使用SWT.NONE时,在Windows上使用)允许脚本关闭浏览器窗口(尽管它可能会显示提示)。

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

既然你不能真正使用IE浏览器在SWT在Linux上,我不能想办法让window.close()工作。


但是,你可以从JavaScript的SWT Browser内调用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