问题
I wrote a program which includes the browser widget from swt. Now I navigate to google and want to search for the string "Pictures" for example. This is my code but it doesn't work:
browser.addProgressListener(new ProgressAdapter() {
boolean firstCompleted = false;
@Override
public void completed(ProgressEvent evt) {
if (!firstCompleted) {
String search = "Pictures";
// this row doesn't work... - not yet ;)
int n = (int) browser.evaluate("return str.search(\"" + search + "\"));");
if (n == -1) {
// string not found
} else if(n >= 1) {
// string found
}
firstCompleted = true;
}
}
});
JavaScript should check if the string is available and return the integer n
which includes the result of the str.search()-Operation. If n == -1
there is no such string, if n == 1
the string was found on the website.
回答1:
Here is a very simple example, that will return a value from JavaScript to Java and print it to the command line:
public static void main(String[] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
final Browser browser = new Browser(shell, SWT.NONE);
browser.setText("......baz");
Button b = new Button(shell, SWT.PUSH);
b.setText("Do something");
b.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
String baz = "baz";
boolean result = (boolean) browser.evaluate("return window.find('" + baz + "');");
System.out.println(result);
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
Note that I used a different JS function than you did and that you have an additional closing bracket in your JS code.
Here is an excellent tutorial.
来源:https://stackoverflow.com/questions/17756726/search-string-in-swt-webbrowser-widget