The thing i want to do is to replace some part(s) of the web page HTML content (that is currently getting loaded inside WebView engine) with my own HTML content.
As a simple example - i want to replace every loaded page body's background color to RED. Meaning i will need to add or replace existing body bgcolor attribute with my own value. What should i do to achieve that?
Here is the basic browser code based on JavaFX WebView component:
public class BrowserTest extends Application
{
    public static void main ( String[] args )
    {
        launch ( args );
    }
    public void start ( Stage stage )
    {
        stage.setTitle ( "WebView" );
        Browser browser = new Browser ();
        browser.load ( "http://google.com" );
        Scene scene = new Scene ( browser );
        stage.setScene ( scene );
        stage.show ();
    }
    public class Browser extends Region
    {
        final WebView browser;
        final WebEngine webEngine;
        public Browser ()
        {
            super ();
            browser = new WebView ();
            webEngine = browser.getEngine ();
            getChildren ().add ( browser );
        }
        public void load ( String url )
        {
            webEngine.load ( url );
        }
        private Node createSpacer ()
        {
            Region spacer = new Region ();
            HBox.setHgrow ( spacer, Priority.ALWAYS );
            return spacer;
        }
        protected void layoutChildren ()
        {
            double w = getWidth ();
            double h = getHeight ();
            layoutInArea ( browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER );
        }
        protected double computePrefWidth ( double height )
        {
            return 750;
        }
        protected double computePrefHeight ( double width )
        {
            return 500;
        }
    }
}
There was a good example of this technique in some Oracle docs but since last JavaFX and site updates i couldn't find it at all. Maybe anyone has the link to old docs...
Note: Also jewelsea offered a good way to make post-changes (when the page is loaded), but i need exactly "load-while" solution for my case, so that WebView won't do double job rendering page twice (before and after changes).
Add a listener to the WebEngine document property and when it changes:
Update
To intercept the html source in flight and potentially modify it before it reaches WebView, you can implement your own UrlConnection handler. This is something I have been able to successfully achieve in the past. See option 3 of my longish forum post under the id jsmith for some background info and pointers on how to do this. The key to doing this is setting URL.setURLStreamHandlerFactory(myHandlerFactory).
It is a little bit late but you may:
Than changed the content will appear and will start to be visible for user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With