Execute a task after the WebView is fully loaded

前端 未结 1 1461
北恋
北恋 2021-02-13 06:54

Is it possible to have a task automatically run after the WebEngine finishes loading? I know I can get a Worker from WebEngine to indicate

相关标签:
1条回答
  • 2021-02-13 07:28

    Sample based on the WebView documentation:

    webView.getEngine().getLoadWorker().stateProperty().addListener(
      new ChangeListener<Worker.State>() {
      @Override
      public void changed(
        ObservableValue<? extends Worker.State> observable,
        Worker.State oldValue, Worker.State newValue ) {
    
        if( newValue != Worker.State.SUCCEEDED ) {
          return;
        }
    
        // Your logic here
      }
    } );
    

    As a lambda expression:

    webView.getEngine().getLoadWorker().stateProperty().addListener(
      (ObservableValue<? extends Worker.State> observable,
        Worker.State oldValue,
        Worker.State newValue) -> {
        if( newValue != Worker.State.SUCCEEDED ) {
          return;
        }
    
        // Your logic here
      } );
    

    If you only want to listen to the next page load and not every subsequent page load, then stop listening after the page loaded.

    To do that, then you can remove the listener (in the listener code) once it has started to execute:

    webview.getEngine().getLoadWorker().stateProperty().addListener(
      new ChangeListener<Worker.State>() {
        @Override
        public void changed(
                    ObservableValue<? extends Worker.State> observable,
                    Worker.State oldValue, Worker.State newValue) {
          switch (newValue) {
            case SUCCEEDED:
            case FAILED:
            case CANCELLED:
              webview
                .getEngine()
                .getLoadWorker()
                .stateProperty()
                .removeListener(this);
          }
    
    
          if (newValue != Worker.State.SUCCEEDED) {
            return;
          }
    
          // Your logic here
          System.out.println("page loaded");
        }
      } );
    
    0 讨论(0)
提交回复
热议问题