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 java.io.PrintWriter;
18  import java.io.StringWriter;
19  import java.util.Map;
20  
21  import org.htmlunit.SgmlPage;
22  import org.htmlunit.javascript.AbstractJavaScriptEngine;
23  import org.htmlunit.javascript.PostponedAction;
24  import org.htmlunit.javascript.host.dom.Document;
25  
26  /**
27   * Wrapper for the HTML element "script".<br>
28   * When a script tag references an external script (with attribute src) it gets executed when the node
29   * is added to the DOM tree. When the script code is nested, it gets executed when the text node
30   * containing the script is added to the HtmlScript.<br>
31   * The ScriptFilter feature of NekoHtml can't be used because it doesn't allow immediate access to the DOM
32   * (i.e. <code>document.write("&lt;span id='mySpan'/&gt;"); document.getElementById("mySpan").tagName;</code>
33   * can't work with a filter).
34   *
35   * @author Mike Bowler
36   * @author Christian Sell
37   * @author Marc Guillemot
38   * @author David K. Taylor
39   * @author Ahmed Ashour
40   * @author Daniel Gredler
41   * @author Dmitri Zoubkov
42   * @author Sudhan Moghe
43   * @author Ronald Brill
44   * @author Daniel Wagner-Hall
45   * @author Frank Danek
46   * @see <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-81598695">DOM Level 1</a>
47   * @see <a href="http://www.w3.org/TR/2003/REC-DOM-Level-2-HTML-20030109/html.html#ID-81598695">DOM Level 2</a>
48   */
49  public class HtmlScript extends HtmlElement implements ScriptElement {
50  
51      /** The HTML tag represented by this element. */
52      public static final String TAG_NAME = "script";
53  
54      private boolean executed_;
55      private boolean createdByDomParser_;
56      private boolean parserInserted_;
57  
58      /**
59       * Creates an instance of HtmlScript.
60       *
61       * @param qualifiedName the qualified name of the element type to instantiate
62       * @param page the HtmlPage that contains this element
63       * @param attributes the initial attributes
64       */
65      HtmlScript(final String qualifiedName, final SgmlPage page,
66              final Map<String, DomAttr> attributes) {
67          super(qualifiedName, page, attributes);
68      }
69  
70      /**
71       * Returns the value of the attribute {@code charset}. Refer to the
72       * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
73       * documentation for details on the use of this attribute.
74       *
75       * @return the value of the attribute {@code charset}
76       *         or an empty string if that attribute isn't defined.
77       */
78      public final String getCharsetAttribute() {
79          return getAttributeDirect("charset");
80      }
81  
82      /**
83       * {@inheritDoc}
84       */
85      @Override
86      public final String getScriptCharset() {
87          return getAttributeDirect("charset");
88      }
89  
90      /**
91       * Returns the value of the attribute {@code type}. Refer to the
92       * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
93       * documentation for details on the use of this attribute.
94       *
95       * @return the value of the attribute {@code type}
96       *         or an empty string if that attribute isn't defined.
97       */
98      public final String getTypeAttribute() {
99          return getAttributeDirect(TYPE_ATTRIBUTE);
100     }
101 
102     /**
103      * Returns the value of the attribute {@code language}. Refer to the
104      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
105      * documentation for details on the use of this attribute.
106      *
107      * @return the value of the attribute {@code language}
108      *         or an empty string if that attribute isn't defined.
109      */
110     public final String getLanguageAttribute() {
111         return getAttributeDirect("language");
112     }
113 
114     /**
115      * Returns the value of the attribute {@code src}. Refer to the
116      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
117      * documentation for details on the use of this attribute.
118      *
119      * @return the value of the attribute {@code src}
120      *         or an empty string if that attribute isn't defined.
121      */
122     public final String getSrcAttribute() {
123         return getSrcAttributeNormalized();
124     }
125 
126     /**
127      * {@inheritDoc}
128      */
129     @Override
130     public final String getScriptSource() {
131         return getSrcAttributeNormalized();
132     }
133 
134     /**
135      * Returns the value of the attribute {@code event}.
136      * @return the value of the attribute {@code event}
137      */
138     public final String getEventAttribute() {
139         return getAttributeDirect("event");
140     }
141 
142     /**
143      * Returns the value of the attribute {@code for}.
144      * @return the value of the attribute {@code for}
145      */
146     public final String getHtmlForAttribute() {
147         return getAttributeDirect("for");
148     }
149 
150     /**
151      * Returns the value of the attribute {@code defer}. Refer to the
152      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
153      * documentation for details on the use of this attribute.
154      *
155      * @return the value of the attribute {@code defer}
156      *         or an empty string if that attribute isn't defined.
157      */
158     public final String getDeferAttribute() {
159         return getAttributeDirect("defer");
160     }
161 
162     /**
163      * {@inheritDoc}
164      */
165     @Override
166     public boolean isDeferred() {
167         return getDeferAttribute() != ATTRIBUTE_NOT_DEFINED;
168     }
169 
170     /**
171      * {@inheritDoc}
172      */
173     @Override
174     public boolean isCrossorigin() {
175         return hasAttribute("crossorigin");
176     }
177 
178     /**
179      * {@inheritDoc}
180      */
181     @Override
182     public boolean mayBeDisplayed() {
183         return false;
184     }
185 
186     /**
187      * If setting the <code>src</code> attribute, this method executes the new JavaScript if necessary
188      * (behavior varies by browser version). {@inheritDoc}
189      */
190     @Override
191     protected void setAttributeNS(final String namespaceURI, final String qualifiedName, final String attributeValue,
192             final boolean notifyAttributeChangeListeners, final boolean notifyMutationObservers) {
193         final String qualifiedNameLC = org.htmlunit.util.StringUtils.toRootLowerCase(qualifiedName);
194         // special additional processing for the 'src'
195         if (namespaceURI != null || !SRC_ATTRIBUTE.equals(qualifiedNameLC)) {
196             super.setAttributeNS(namespaceURI, qualifiedNameLC, attributeValue, notifyAttributeChangeListeners,
197                     notifyMutationObservers);
198             return;
199         }
200 
201         // namespaceURI is always null here - we can call getAttribute directly
202         final String oldValue = getAttribute(qualifiedNameLC);
203         super.setAttributeNS(null, qualifiedNameLC, attributeValue, notifyAttributeChangeListeners,
204                 notifyMutationObservers);
205 
206         if (isAttachedToPage() && oldValue.isEmpty() && getFirstChild() == null) {
207             final PostponedAction action = new PostponedAction(getPage(), "HtmlScript.setAttributeNS") {
208                 @Override
209                 public void execute() {
210                     ScriptElementSupport.executeScriptIfNeeded(HtmlScript.this, false, false);
211                 }
212             };
213             final AbstractJavaScriptEngine<?> engine = getPage().getWebClient().getJavaScriptEngine();
214             engine.addPostponedAction(action);
215         }
216     }
217 
218     /**
219      * Executes the <code>onreadystatechange</code> handler, as well as executing
220      * the script itself, if necessary.
221      * {@inheritDoc}
222      */
223     @Override
224     public void onAllChildrenAddedToPage(final boolean postponed) {
225         ScriptElementSupport.onAllChildrenAddedToPage(this, postponed);
226     }
227 
228     /**
229      * Gets the script held within the script tag.
230      */
231     private String getScriptCode() {
232         final Iterable<DomNode> textNodes = getChildren();
233         final StringBuilder scriptCode = new StringBuilder();
234         for (final DomNode node : textNodes) {
235             if (node instanceof DomText domText) {
236                 scriptCode.append(domText.getData());
237             }
238         }
239         return scriptCode.toString();
240     }
241 
242     /**
243      * {@inheritDoc}
244      */
245     @Override
246     protected boolean printChildrenAsXml(final String indent, final boolean tagBefore, final PrintWriter printWriter) {
247         final DomCharacterData textNode = (DomCharacterData) getFirstChild();
248         if (textNode == null) {
249             return tagBefore;
250         }
251 
252         final String data = textNode.getData();
253         printWriter.print("\r\n");
254         if (data.contains("//<![CDATA[")) {
255             printWriter.print(data);
256         }
257         else {
258             printWriter.print("//<![CDATA[");
259             printWriter.print("\r\n");
260             printWriter.print(data);
261             printWriter.print("\r\n");
262             printWriter.print("//]]>");
263         }
264         return true;
265     }
266 
267     /**
268      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
269      *
270      * Resets the executed flag.
271      * @see HtmlScript#processImportNode(Document)
272      */
273     public void resetExecuted() {
274         executed_ = false;
275     }
276 
277     @Override
278     public void processImportNode(final Document doc) {
279         super.processImportNode(doc);
280 
281         executed_ = true;
282     }
283 
284     /**
285      * Returns a string representation of this object.
286      * @return a string representation of this object
287      */
288     @Override
289     public String toString() {
290         final StringWriter writer = new StringWriter();
291         final PrintWriter printWriter = new PrintWriter(writer);
292 
293         printWriter.print(getClass().getSimpleName());
294         printWriter.print("[<");
295         printOpeningTagContentAsXml(printWriter);
296         printWriter.print(">");
297         printWriter.print(getScriptCode());
298         printWriter.print("]");
299         printWriter.flush();
300         return writer.toString();
301     }
302 
303     /**
304      * {@inheritDoc}
305      */
306     @Override
307     public DisplayStyle getDefaultStyleDisplay() {
308         return DisplayStyle.NONE;
309     }
310 
311     /**
312      * {@inheritDoc}
313      */
314     @Override
315     public void markAsCreatedByDomParser() {
316         createdByDomParser_ = true;
317     }
318 
319     /**
320      * {@inheritDoc}
321      */
322     @Override
323     public boolean wasCreatedByDomParser() {
324         return createdByDomParser_;
325     }
326 
327     /**
328      * {@inheritDoc}
329      */
330     @Override
331     public void markAsParserInserted() {
332         parserInserted_ = true;
333     }
334 
335     /**
336      * {@inheritDoc}
337      */
338     @Override
339     public boolean wasParserInserted() {
340         return parserInserted_;
341     }
342 
343     /**
344      * {@inheritDoc}
345      */
346     @Override
347     public boolean isExecuted() {
348         return executed_;
349     }
350 
351     /**
352      * {@inheritDoc}
353      */
354     @Override
355     public void setExecuted(final boolean executed) {
356         executed_ = executed;
357     }
358 }