method does this by injecting some
JavaScript that will modify the style of the
page’s body (see Listing 7).
We can inject only a string, so first I
put all the code into a StringBuffer. (A
more robust version of this might load
the JavaScript from a file instead of
creating it in code.) Once we have the
script, we can inject it by calling
engine.executeScript(). This will return
an object wrapping the return value
of the code, which in this case is the
bodys object. It is possible to use this
return value to pass simple data from
the JavaScript side to the Java side, but
in this case, I just care that the code
executed successfully.
private void modifyDoc(Document newDoc, WebEngine engine) {
StringBuffer script = new StringBuffer();
//grab the body
script.append("var bodys = document.getElementsBy TagName('body');");
//change the colors
script.append("bodys[0]. style.backgroundColor = '#FFFFFF';");
script.append("bodys[0]. style.color = '#000000';");
//set a new default font
script.append("bodys[0]. style.fontFamily = 'sans-serif';");
COMMUNITY
JAVA IN ACTION
script.append("bodys;");
//execute
Object retval = engine.executeScript( script.toString());
//return value doesn't matter in this case
p("return value = " + retval);
JSObject obj = (JSObject) retval;
}
Download all listings in this issue as text
Figure 3
Figure 6
ABOUT US
Figure 4
Working with Generated Content
For the final example, I’d like to use the
WebView to show some content that
comes from the app itself: a help system. In days gone by, you would have to
use a proprietary help engine to display
rich text help within your app. Now, we
can just write it all as HTML and show it
in a window.
For this example, I created an imaginary media player called Pi Tunes. It has
a toolbar at the top, a list of media types
on the left side (called the source list),
and a list of media files on the right, as
shown in Figure 5.
To see the list of movies, the user
clicks the Movies item in the list. This
might not be obvious, however, so we
can add some online help to explain.
When the user clicks the Help button, a
second window is opened with the help
content. See Listing 8.