View Javadoc
1   /*
2    * Copyright (c) 2002-2026 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.html;
16  
17  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
18  
19  import java.net.MalformedURLException;
20  import java.net.URL;
21  import java.nio.charset.Charset;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.htmlunit.FailingHttpStatusCodeException;
26  import org.htmlunit.SgmlPage;
27  import org.htmlunit.WebClient;
28  import org.htmlunit.WebWindow;
29  import org.htmlunit.html.HtmlPage.JavaScriptLoadResult;
30  import org.htmlunit.html.csp.ContentSecurityPolicy;
31  import org.htmlunit.javascript.AbstractJavaScriptEngine;
32  import org.htmlunit.javascript.PostponedAction;
33  import org.htmlunit.javascript.host.Window;
34  import org.htmlunit.javascript.host.dom.Document;
35  import org.htmlunit.javascript.host.event.Event;
36  import org.htmlunit.javascript.host.event.EventTarget;
37  import org.htmlunit.javascript.host.html.HTMLDocument;
38  import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
39  import org.htmlunit.util.EncodingSniffer;
40  import org.htmlunit.util.MimeType;
41  import org.htmlunit.util.StringUtils;
42  import org.htmlunit.xml.XmlPage;
43  
44  /**
45   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
46   *
47   * A helper class to be used by elements which support {@link ScriptElement}.
48   *
49   * @author Ahmed Ashour
50   * @author Ronald Brill
51   * @author Ronny Shapiro
52   * @author Sven Strickroth
53   */
54  public final class ScriptElementSupport {
55  
56      private static final Log LOG = LogFactory.getLog(ScriptElementSupport.class);
57  
58      /** Invalid source attribute which should be ignored (used by JS libraries like jQuery). */
59      private static final String SLASH_SLASH_COLON = "//:";
60  
61      private ScriptElementSupport() {
62          // util class
63      }
64  
65      /**
66       * Support method that is called from the (html or svg) script and the link tag.
67       *
68       * @param script the ScriptElement to work for
69       * @param postponed whether to use {@link org.htmlunit.javascript.PostponedAction} or not
70       */
71      public static void onAllChildrenAddedToPage(final ScriptElement script, final boolean postponed) {
72          final DomElement element = (DomElement) script;
73          if (element.getOwnerDocument() instanceof XmlPage) {
74              return;
75          }
76          if (LOG.isDebugEnabled()) {
77              LOG.debug("Script node added: " + element.asXml());
78          }
79  
80          final SgmlPage page = element.getPage();
81          final WebClient webClient = page.getWebClient();
82          if (!webClient.isJavaScriptEngineEnabled()) {
83              LOG.debug("Script found but not executed because javascript engine is disabled");
84              return;
85          }
86  
87          final String srcAttrib = script.getScriptSource();
88          final boolean hasNoSrcAttrib = ATTRIBUTE_NOT_DEFINED == srcAttrib;
89          // the defer attribute has only an effect for parser-inserted scripts; scripts inserted
90          // by javascript (e.g. createElement() and appendChild()) ignore it (like the browsers)
91          if (!hasNoSrcAttrib && script.isDeferred() && script.wasParserInserted()) {
92              // HtmlPage.executeDeferredScriptsIfNeeded() will process these
93              // directly after the load
94              return;
95          }
96  
97          final WebWindow webWindow = page.getEnclosingWindow();
98          if (webWindow != null) {
99              final StringBuilder description = new StringBuilder()
100                     .append("Execution of ")
101                     .append(hasNoSrcAttrib ? "inline " : "external ")
102                     .append(element.getClass().getSimpleName());
103             if (!hasNoSrcAttrib) {
104                 description.append(" (").append(srcAttrib).append(')');
105             }
106 
107             final PostponedAction action = new PostponedAction(page, description.toString()) {
108                 @Override
109                 public void execute() {
110                     // see HTMLDocument.setExecutingDynamicExternalPosponed(boolean)
111                     HTMLDocument jsDoc = null;
112                     final Window window = webWindow.getScriptableObject();
113                     if (window != null) {
114                         jsDoc = (HTMLDocument) window.getDocument();
115                         jsDoc.setExecutingDynamicExternalPosponed(element.getStartLineNumber() == -1
116                                 && !hasNoSrcAttrib);
117                     }
118                     try {
119                         executeScriptIfNeeded(script, false, false);
120                     }
121                     finally {
122                         if (jsDoc != null) {
123                             jsDoc.setExecutingDynamicExternalPosponed(false);
124                         }
125                     }
126                 }
127             };
128 
129             final AbstractJavaScriptEngine<?> engine = webClient.getJavaScriptEngine();
130             if (element.hasAttribute("async") && !hasNoSrcAttrib) {
131                 engine.addPostponedAction(action);
132             }
133             else if (postponed && !hasNoSrcAttrib) {
134                 engine.addPostponedAction(action);
135             }
136             else {
137                 try {
138                     action.execute();
139                     if (engine != null) {
140                         engine.processPostponedActions();
141                     }
142                 }
143                 catch (final RuntimeException e) {
144                     throw e;
145                 }
146                 catch (final Exception e) {
147                     throw new RuntimeException(e);
148                 }
149             }
150         }
151     }
152 
153     /**
154      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
155      *
156      * Executes this script node if necessary and/or possible.
157      *
158      * @param script the ScriptElement to work for
159      * @param ignoreAttachedToPage don't do the isAttachedToPage check
160      * @param ignorePageIsAncestor don't do the element.getPage().isAncestorOf(element) check
161      */
162     public static void executeScriptIfNeeded(final ScriptElement script, final boolean ignoreAttachedToPage,
163             final boolean ignorePageIsAncestor) {
164         try {
165             doExecuteScriptIfNeeded(script, ignoreAttachedToPage, ignorePageIsAncestor);
166         }
167         finally {
168             // fire the securitypolicyviolation events after the script was processed;
169             // if a script is running, this is done at the end of the script execution
170             final AbstractJavaScriptEngine<?> engine =
171                     ((DomElement) script).getPage().getWebClient().getJavaScriptEngine();
172             if (engine == null || !engine.isScriptRunning()) {
173                 ContentSecurityPolicy.firePendingViolations();
174             }
175         }
176     }
177 
178     private static void doExecuteScriptIfNeeded(final ScriptElement script, final boolean ignoreAttachedToPage,
179             final boolean ignorePageIsAncestor) {
180         if (!isExecutionNeeded(script, ignoreAttachedToPage, ignorePageIsAncestor)) {
181             return;
182         }
183 
184         final String src = script.getScriptSource();
185         final DomElement element = (DomElement) script;
186         if (SLASH_SLASH_COLON.equals(src)) {
187             executeEvent(element, Event.TYPE_ERROR);
188             return;
189         }
190 
191         final HtmlPage page = (HtmlPage) element.getPage();
192         if (src != ATTRIBUTE_NOT_DEFINED) {
193             if (!src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
194                 // <script src="[url]"></script>
195                 if (LOG.isDebugEnabled()) {
196                     LOG.debug("Loading external JavaScript: " + src);
197                 }
198                 try {
199                     script.setExecuted(true);
200 
201                     String scriptSrc = src;
202                     if (page.getContentSecurityPolicy() != null) {
203                         URL scriptUrl = null;
204                         try {
205                             // upgrade-insecure-requests of the Content-Security-Policy
206                             final URL resolvedUrl = page.getFullyQualifiedUrl(src);
207                             scriptUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, resolvedUrl);
208                             if (scriptUrl != resolvedUrl) {
209                                 scriptSrc = scriptUrl.toExternalForm();
210                             }
211                         }
212                         catch (final MalformedURLException e) {
213                             // handled by loadExternalJavaScriptFile()
214                         }
215                         if (scriptUrl != null
216                                 && !ContentSecurityPolicy.allowsExternalScript(page, element, scriptUrl)) {
217                             executeEvent(element, Event.TYPE_ERROR);
218                             return;
219                         }
220                     }
221 
222                     Charset charset = EncodingSniffer.toCharset(script.getScriptCharset());
223                     if (charset == null) {
224                         charset = page.getCharset();
225                     }
226 
227                     final JavaScriptLoadResult result;
228                     final Window win = page.getEnclosingWindow().getScriptableObject();
229                     final Document doc = win.getDocument();
230                     try {
231                         doc.setCurrentScript(element.getScriptableObject());
232                         result = page.loadExternalJavaScriptFile(scriptSrc, charset, script.isCrossorigin(), element);
233                     }
234                     finally {
235                         doc.setCurrentScript(null);
236                     }
237 
238                     if (result == JavaScriptLoadResult.SUCCESS) {
239                         executeEvent(element, Event.TYPE_LOAD);
240                     }
241                     else if (result == JavaScriptLoadResult.DOWNLOAD_ERROR) {
242                         executeEvent(element, Event.TYPE_ERROR);
243                     }
244                     else if (result == JavaScriptLoadResult.NO_CONTENT) {
245                         executeEvent(element, Event.TYPE_LOAD);
246                     }
247                 }
248                 catch (final FailingHttpStatusCodeException e) {
249                     executeEvent(element, Event.TYPE_ERROR);
250                     throw e;
251                 }
252             }
253         }
254         else if (element.getFirstChild() != null) {
255             // <script>[code]</script>
256             final Window win = page.getEnclosingWindow().getScriptableObject();
257             final Document doc = win.getDocument();
258             try {
259                 doc.setCurrentScript(element.getScriptableObject());
260                 executeInlineScript(script);
261             }
262             finally {
263                 doc.setCurrentScript(null);
264             }
265         }
266     }
267 
268     /**
269      * Indicates if script execution is necessary and/or possible.
270      *
271      * @param script the ScriptElement to work for
272      * @param ignoreAttachedToPage don't do the isAttachedToPage check
273      * @param ignorePageIsAncestor don't do the element.getPage().isAncestorOf(element) check
274      * @return {@code true} if the script should be executed
275      */
276     private static boolean isExecutionNeeded(final ScriptElement script, final boolean ignoreAttachedToPage,
277             final boolean ignorePageIsAncestor) {
278         if (script.isExecuted() || script.wasCreatedByDomParser()) {
279             return false;
280         }
281 
282         final DomElement element = (DomElement) script;
283         if (!ignoreAttachedToPage && !element.isAttachedToPage()) {
284             return false;
285         }
286 
287         // If JavaScript is disabled, we don't need to execute.
288         final SgmlPage page = element.getPage();
289         if (!page.getWebClient().isJavaScriptEnabled()) {
290             return false;
291         }
292 
293         // If innerHTML or outerHTML is being parsed
294         final HtmlPage htmlPage = element.getHtmlPageOrNull();
295         if (htmlPage != null && htmlPage.isParsingHtmlSnippet()) {
296             return false;
297         }
298 
299         // If the script node is nested in an iframe, a noframes, or a noscript node, we don't need to execute.
300         for (DomNode o = element; o != null; o = o.getParentNode()) {
301             if (o instanceof HtmlInlineFrame || o instanceof HtmlNoFrames) {
302                 return false;
303             }
304         }
305 
306         // If the underlying page no longer owns its window, the client has moved on (possibly
307         // because another script set window.location.href), and we don't need to execute.
308         if (page.getEnclosingWindow() != null && page.getEnclosingWindow().getEnclosedPage() != page) {
309             return false;
310         }
311 
312         // If the script language is not JavaScript, we can't execute.
313         final String t = element.getAttributeDirect("type");
314         final String l = element.getAttributeDirect("language");
315         if (!isJavaScript(t, l)) {
316             // Was at warn level before 2.46 but other types or tricky implementations with unsupported types
317             // are common out there and too many peoples out there thinking the is the root of problems.
318             // Browsers are also not warning about this.
319             if (LOG.isDebugEnabled()) {
320                 LOG.debug("Script is not JavaScript (type: '" + t + "', language: '" + l + "'). Skipping execution.");
321             }
322             return false;
323         }
324 
325         // If the script's root ancestor node is not the page, then the script is not a part of the page.
326         // If it isn't yet part of the page, don't execute the script; it's probably just being cloned.
327         return ignorePageIsAncestor || element.getPage().isAncestorOf(element);
328     }
329 
330     /**
331      * Returns true if a script with the specified type and language attributes is actually JavaScript.
332      * According to <a href="http://www.w3.org/TR/REC-html40/types.html#h-6.7">W3C recommendation</a>
333      * are content types case insensitive.<br>
334      *
335      * @param typeAttribute the type attribute specified in the script tag
336      * @param languageAttribute the language attribute specified in the script tag
337      * @return true if the script is JavaScript
338      */
339     public static boolean isJavaScript(final String typeAttribute, final String languageAttribute) {
340         final String type = typeAttribute.trim();
341         if (!StringUtils.isEmptyOrNull(type)) {
342             return MimeType.isJavascriptMimeType(type);
343         }
344 
345         if (!StringUtils.isEmptyOrNull(languageAttribute)) {
346             return StringUtils.startsWithIgnoreCase(languageAttribute, "javascript");
347         }
348         return true;
349     }
350 
351     private static void executeEvent(final DomElement element, final String type) {
352         final EventTarget eventTarget = element.getScriptableObject();
353         final Event event = new Event(element, type);
354 
355         event.setParentScope(eventTarget.getParentScope());
356         event.setPrototype(eventTarget.getPrototype(event.getClass()));
357 
358         eventTarget.executeEventLocally(event);
359     }
360 
361     /**
362      * Executes this script node as inline script.
363      */
364     private static void executeInlineScript(final ScriptElement script) {
365         final DomElement element = (DomElement) script;
366         final String forr = element.getAttributeDirect("for");
367         String event = element.getAttributeDirect("event");
368         // The event name can be like "onload" or "onload()".
369         if (event.endsWith("()")) {
370             event = event.substring(0, event.length() - 2);
371         }
372 
373         final String scriptCode = getScriptCode(element);
374         if (forr == ATTRIBUTE_NOT_DEFINED || "onload".equals(event)) {
375             final HtmlPage page = (HtmlPage) element.getPage();
376             if (!ContentSecurityPolicy.allowsInlineScript(page, element, scriptCode)) {
377                 script.setExecuted(true);
378                 return;
379             }
380 
381             final String url = element.getPage().getUrl().toExternalForm();
382             final int line1 = element.getStartLineNumber();
383             final int line2 = element.getEndLineNumber();
384             final int col1 = element.getStartColumnNumber();
385             final int col2 = element.getEndColumnNumber();
386             final String desc = "script in " + url + " from (" + line1 + ", " + col1
387                 + ") to (" + line2 + ", " + col2 + ")";
388 
389             script.setExecuted(true);
390             page.executeJavaScript(scriptCode, desc, line1);
391         }
392     }
393 
394     /**
395      * Gets the script held within the script tag.
396      */
397     private static String getScriptCode(final DomElement element) {
398         final StringBuilder scriptCode = new StringBuilder();
399         for (final DomNode node : element.getChildren()) {
400             if (node instanceof DomText domText) {
401                 scriptCode.append(domText.getData());
402             }
403         }
404         return scriptCode.toString();
405     }
406 }