Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

java - Search string in SWT Webbrowser Widget

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...