View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript;
16  
17  import java.lang.ref.WeakReference;
18  
19  import org.htmlunit.Page;
20  
21  /**
22   * An action triggered by a script execution but that should be executed first when the script is finished.
23   * Example: when a script sets the source of an (i)frame, the request to the specified page will be first
24   * triggered after the script execution.
25   *
26   * @author Marc Guillemot
27   * @author Ronald Brill
28   */
29  public abstract class PostponedAction {
30  
31      private final WeakReference<Page> owningPageRef_; // as weak ref in case it may allow page to be GCed
32      private final String description_;
33  
34      /**
35       * C'tor.
36       * @param owningPage the page that initiates this action
37       * @param description information making debugging easier
38       */
39      public PostponedAction(final Page owningPage, final String description) {
40          owningPageRef_ = new WeakReference<>(owningPage);
41          description_ = description;
42      }
43  
44      /**
45       * Gets the owning page.
46       * @return the page that initiated this action or {@code null} if it has already been GCed
47       */
48      protected Page getOwningPage() {
49          return owningPageRef_.get();
50      }
51  
52      /**
53       * Execute the action.
54       * @throws Exception if it fails
55       */
56      public abstract void execute() throws Exception;
57  
58      /**
59       * Indicates if the action still needs to be executed.
60       * @return {@code true} if the action needs to be executed
61       */
62      public boolean isStillAlive() {
63          final Page owningPage = getOwningPage();
64          return owningPage != null
65                  && owningPage.getEnclosingWindow() != null
66                  && owningPage == owningPage.getEnclosingWindow().getEnclosedPage();
67      }
68  
69      @Override
70      public String toString() {
71          if (description_ == null) {
72              return super.toString();
73          }
74  
75          return "PostponedAction(" + description_ + ")";
76      }
77  }