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.BrowserVersionFeatures.HTMLLINK_CHECK_RESPONSE_TYPE_FOR_STYLESHEET;
18  
19  import java.io.IOException;
20  import java.net.MalformedURLException;
21  import java.net.URL;
22  import java.util.Map;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.htmlunit.BrowserVersion;
27  import org.htmlunit.SgmlPage;
28  import org.htmlunit.WebClient;
29  import org.htmlunit.WebRequest;
30  import org.htmlunit.WebRequest.FetchMode;
31  import org.htmlunit.WebResponse;
32  import org.htmlunit.css.CssStyleSheet;
33  import org.htmlunit.cssparser.dom.MediaListImpl;
34  import org.htmlunit.html.csp.ContentSecurityPolicy;
35  import org.htmlunit.javascript.PostponedAction;
36  import org.htmlunit.javascript.host.event.Event;
37  import org.htmlunit.javascript.host.html.HTMLLinkElement;
38  import org.htmlunit.util.ArrayUtils;
39  import org.htmlunit.util.MimeType;
40  import org.htmlunit.util.StringUtils;
41  import org.htmlunit.xml.XmlPage;
42  
43  /**
44   * Wrapper for the HTML element "link". <b>Note:</b> This is not a clickable link,
45   * that one is an HtmlAnchor
46   *
47   * @author Mike Bowler
48   * @author David K. Taylor
49   * @author Christian Sell
50   * @author Ahmed Ashour
51   * @author Marc Guillemot
52   * @author Frank Danek
53   * @author Ronald Brill
54   */
55  public class HtmlLink extends HtmlElement {
56      private static final Log LOG = LogFactory.getLog(HtmlLink.class);
57  
58      /** The HTML tag represented by this element. */
59      public static final String TAG_NAME = "link";
60  
61      /**
62       * The associated style sheet (only valid for links of type
63       * <code>&lt;link rel="stylesheet" type="text/css" href="..." /&gt;</code>).
64       */
65      private CssStyleSheet sheet_;
66      // the load/error event of a stylesheet is fired after the stylesheet is stored
67      private String pendingStylesheetEvent_;
68  
69      /**
70       * Creates an instance of HtmlLink.
71       *
72       * @param qualifiedName the qualified name of the element type to instantiate
73       * @param page the HtmlPage that contains this element
74       * @param attributes the initial attributes
75       */
76      HtmlLink(final String qualifiedName, final SgmlPage page,
77              final Map<String, DomAttr> attributes) {
78          super(qualifiedName, page, attributes);
79      }
80  
81      /**
82       * Returns the value of the attribute {@code charset}. Refer to the
83       * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
84       * documentation for details on the use of this attribute.
85       *
86       * @return the value of the attribute {@code charset}
87       *         or an empty string if that attribute isn't defined.
88       */
89      public final String getCharsetAttribute() {
90          return getAttributeDirect("charset");
91      }
92  
93      /**
94       * Returns the value of the attribute {@code href}. Refer to the
95       * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
96       * documentation for details on the use of this attribute.
97       *
98       * @return the value of the attribute {@code href}
99       *         or an empty string if that attribute isn't defined.
100      */
101     public final String getHrefAttribute() {
102         return getAttributeDirect("href");
103     }
104 
105     /**
106      * Returns the value of the attribute {@code hreflang}. Refer to the
107      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
108      * documentation for details on the use of this attribute.
109      *
110      * @return the value of the attribute {@code hreflang}
111      *         or an empty string if that attribute isn't defined.
112      */
113     public final String getHrefLangAttribute() {
114         return getAttributeDirect("hreflang");
115     }
116 
117     /**
118      * Returns the value of the attribute {@code type}. Refer to the
119      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
120      * documentation for details on the use of this attribute.
121      *
122      * @return the value of the attribute {@code type}
123      *         or an empty string if that attribute isn't defined.
124      */
125     public final String getTypeAttribute() {
126         return getAttributeDirect(TYPE_ATTRIBUTE);
127     }
128 
129     /**
130      * Returns the value of the attribute {@code rel}. Refer to the
131      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
132      * documentation for details on the use of this attribute.
133      *
134      * @return the value of the attribute {@code rel}
135      *         or an empty string if that attribute isn't defined.
136      */
137     public final String getRelAttribute() {
138         return getAttributeDirect("rel");
139     }
140 
141     /**
142      * Returns the value of the attribute {@code rev}. Refer to the
143      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
144      * documentation for details on the use of this attribute.
145      *
146      * @return the value of the attribute {@code rev}
147      *         or an empty string if that attribute isn't defined.
148      */
149     public final String getRevAttribute() {
150         return getAttributeDirect("rev");
151     }
152 
153     /**
154      * Returns the value of the attribute {@code media}. Refer to the
155      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
156      * documentation for details on the use of this attribute.
157      *
158      * @return the value of the attribute {@code media}
159      *         or an empty string if that attribute isn't defined.
160      */
161     public final String getMediaAttribute() {
162         return getAttributeDirect("media");
163     }
164 
165     /**
166      * Returns the value of the attribute {@code target}. Refer to the
167      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
168      * documentation for details on the use of this attribute.
169      *
170      * @return the value of the attribute {@code target}
171      *         or an empty string if that attribute isn't defined.
172      */
173     public final String getTargetAttribute() {
174         return getAttributeDirect("target");
175     }
176 
177     /**
178      * <span style="color:red">POTENIAL PERFORMANCE KILLER - DOWNLOADS THE RESOURCE - USE AT YOUR OWN RISK.</span><br>
179      * If the linked content is not already downloaded it triggers a download. Then it stores the response
180      * for later use.<br>
181      *
182      * @param downloadIfNeeded indicates if a request should be performed this hasn't been done previously
183      * @return {@code null} if no download should be performed and when this wasn't already done; the response
184      *         received when performing a request for the content referenced by this tag otherwise
185      * @throws IOException if an error occurs while downloading the content
186      */
187     public WebResponse getWebResponse(final boolean downloadIfNeeded) throws IOException {
188         return getWebResponse(downloadIfNeeded, null, false, null);
189     }
190 
191     /**
192      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
193      *
194      * If the linked content is not already downloaded it triggers a download. Then it stores the response
195      * for later use.<br>
196      *
197      * @param downloadIfNeeded indicates if a request should be performed this hasn't been done previously
198      * @param webRequest the request; if null getWebRequest() is called to create one
199      * @param isStylesheetRequest true if this should return a stylesheet
200      * @param type the type definined for the stylesheet link
201      * @return {@code null} if no download should be performed and when this wasn't already done; the response
202      *         received when performing a request for the content referenced by this tag otherwise
203      * @throws IOException if an error occurs while downloading the content
204      */
205     public WebResponse getWebResponse(final boolean downloadIfNeeded, final WebRequest webRequest,
206             final boolean isStylesheetRequest, final String type) throws IOException {
207         final WebClient webClient = getPage().getWebClient();
208         final WebRequest request = webRequest == null ? getWebRequest() : webRequest;
209 
210         if (downloadIfNeeded) {
211             // like the browsers, a page not loaded from a file is not allowed to load a local file
212             if (getPage() instanceof HtmlPage htmlPage && !htmlPage.isLocalResourceAccessAllowed(request.getUrl())) {
213                 notifyIncorrectness("Not allowed to load local resource: " + request.getUrl());
214                 fireEvent(webClient, Event.TYPE_ERROR, isStylesheetRequest);
215                 return null;
216             }
217 
218             if (isStylesheetRequest && getPage() instanceof HtmlPage htmlPage
219                     && htmlPage.getContentSecurityPolicy() != null) {
220                 final URL styleUrl = request.getUrl();
221                 if (!ContentSecurityPolicy.allowsExternalStyle(htmlPage, this, styleUrl)) {
222                     fireEvent(webClient, Event.TYPE_ERROR, isStylesheetRequest);
223                     return null;
224                 }
225 
226                 // like the browsers, redirects are checked (and upgraded) also
227                 ContentSecurityPolicy.upgradeInsecureRedirects(htmlPage, request);
228                 request.setRedirectFilter(redirectUrl
229                         -> ContentSecurityPolicy.allowsExternalStyle(htmlPage, this, redirectUrl, styleUrl));
230             }
231 
232             try {
233                 final WebResponse response = webClient.loadWebResponse(request);
234                 if (response == null) {
235                     // redirect blocked by the Content-Security-Policy
236                     fireEvent(webClient, Event.TYPE_ERROR, isStylesheetRequest);
237                     return null;
238                 }
239                 if (response.isSuccess()) {
240                     if (isStylesheetRequest
241                             && webClient.getBrowserVersion()
242                                  .hasFeature(HTMLLINK_CHECK_RESPONSE_TYPE_FOR_STYLESHEET)) {
243 
244                         if (StringUtils.isNotBlank(type)
245                                 && !MimeType.TEXT_CSS.equals(type)) {
246                             return null;
247                         }
248 
249                         final String respType = response.getContentType();
250                         if (StringUtils.isNotBlank(respType)
251                                 && !MimeType.TEXT_CSS.equals(respType)) {
252                             fireEvent(webClient, Event.TYPE_ERROR, isStylesheetRequest);
253                             return response;
254                         }
255                     }
256                     fireEvent(webClient, Event.TYPE_LOAD, isStylesheetRequest);
257                     return response;
258                 }
259                 fireEvent(webClient, Event.TYPE_ERROR, isStylesheetRequest);
260                 return response;
261             }
262             catch (final IOException e) {
263                 fireEvent(webClient, Event.TYPE_ERROR, isStylesheetRequest);
264                 throw e;
265             }
266         }
267 
268         // retrieve the response, from the cache if available
269         return webClient.getCache().getCachedResponse(request);
270     }
271 
272     /**
273      * Returns the request which will allow us to retrieve the content referenced by the {@code href} attribute.
274      * @return the request which will allow us to retrieve the content referenced by the {@code href} attribute
275      * @throws MalformedURLException in case of problem resolving the URL
276      */
277     public WebRequest getWebRequest() throws MalformedURLException {
278         final HtmlPage page = (HtmlPage) getPage();
279         // upgrade-insecure-requests of the Content-Security-Policy
280         final URL url = ContentSecurityPolicy.upgradeInsecureRequest(page,
281                                 page.getFullyQualifiedUrl(getHrefAttribute()));
282 
283         final BrowserVersion browser = page.getWebClient().getBrowserVersion();
284         final WebRequest request = new WebRequest(url, browser.getCssAcceptHeader(), browser.getAcceptEncodingHeader());
285         // use the page encoding even if this is a GET requests
286         request.setCharset(page.getCharset());
287         request.setRefererHeader(page.getUrl());
288         request.setReferrerPolicy(page.getReferrerPolicy(this));
289 
290         request.setFetchDestination(WebRequest.FetchDestination.STYLE);
291         request.setFetchModeOverride(FetchMode.NO_CORS);
292         request.setRequestingUrl(page.getUrl());
293         request.setSiteForCookies(page.getSiteForCookiesUrl());
294 
295         return request;
296     }
297 
298     /**
299      * {@inheritDoc}
300      */
301     @Override
302     public DisplayStyle getDefaultStyleDisplay() {
303         return DisplayStyle.NONE;
304     }
305 
306     /**
307      * {@inheritDoc}
308      */
309     @Override
310     public boolean mayBeDisplayed() {
311         return false;
312     }
313 
314     /**
315      * Fires the event; for stylesheet requests the event is fired later by {@link #getSheet()}
316      * when the stylesheet is stored.
317      */
318     private void fireEvent(final WebClient webClient, final String type, final boolean isStylesheetRequest) {
319         if (isStylesheetRequest) {
320             pendingStylesheetEvent_ = type;
321             return;
322         }
323         executeEvent(webClient, type);
324     }
325 
326     private void executeEvent(final WebClient webClient, final String type) {
327         if (!webClient.isJavaScriptEngineEnabled()) {
328             return;
329         }
330 
331         final HTMLLinkElement link = getScriptableObject();
332         final Event event = new Event(this, type);
333         link.executeEventLocally(event);
334     }
335 
336     /**
337      * {@inheritDoc}
338      */
339     @Override
340     public void onAllChildrenAddedToPage(final boolean postponed) {
341         if (getOwnerDocument() instanceof XmlPage) {
342             return;
343         }
344         if (LOG.isDebugEnabled()) {
345             LOG.debug("Link node added: " + asXml());
346         }
347 
348         if (isStyleSheetLink()) {
349             final WebClient webClient = getPage().getWebClient();
350             if (!webClient.getOptions().isCssEnabled()) {
351                 if (LOG.isDebugEnabled()) {
352                     LOG.debug("Stylesheet Link found but ignored because css support is disabled ("
353                                 + asXml().replaceAll("[\\r\\n]", "") + ").");
354                 }
355                 return;
356             }
357 
358             if (!webClient.isJavaScriptEngineEnabled()) {
359                 if (LOG.isDebugEnabled()) {
360                     LOG.debug("Stylesheet Link found but ignored because javascript engine is disabled ("
361                                 + asXml().replaceAll("[\\r\\n]", "") + ").");
362                 }
363                 return;
364             }
365 
366             final PostponedAction action = new PostponedAction(getPage(), "Loading of link " + this) {
367                 @Override
368                 public void execute() {
369                     final HTMLLinkElement linkElem = HtmlLink.this.getScriptableObject();
370                     // force loading, caching inside the link
371                     linkElem.getSheet();
372                 }
373             };
374 
375             if (postponed) {
376                 webClient.getJavaScriptEngine().addPostponedAction(action);
377             }
378             else {
379                 try {
380                     action.execute();
381                 }
382                 catch (final RuntimeException e) {
383                     throw e;
384                 }
385                 catch (final Exception e) {
386                     throw new RuntimeException(e);
387                 }
388             }
389 
390             return;
391         }
392 
393         if (LOG.isDebugEnabled()) {
394             LOG.debug("Link type '" + getRelAttribute() + "' not supported ("
395                         + asXml().replaceAll("[\\r\\n]", "") + ").");
396         }
397     }
398 
399     /**
400      * Returns the associated style sheet (only valid for links of type
401      * <code>&lt;link rel="stylesheet" type="text/css" href="..." /&gt;</code>).
402      * @return the associated style sheet
403      */
404     public CssStyleSheet getSheet() {
405         if (sheet_ == null) {
406             sheet_ = CssStyleSheet.loadStylesheet(this, this, null);
407 
408             // fire the load/error event after the stylesheet is stored; otherwise
409             // an event handler accessing the styles would load the stylesheet again
410             String event = pendingStylesheetEvent_;
411             pendingStylesheetEvent_ = null;
412 
413             // like the browsers, the error event is fired if an @import is blocked by the
414             // Content-Security-Policy (the imports are loaded before the load event)
415             if (Event.TYPE_LOAD.equals(event) && sheet_ != null
416                     && getPage() instanceof HtmlPage htmlPage && htmlPage.getContentSecurityPolicy() != null
417                     && !sheet_.loadImports()) {
418                 event = Event.TYPE_ERROR;
419             }
420 
421             if (event != null) {
422                 executeEvent(getPage().getWebClient(), event);
423             }
424         }
425         return sheet_;
426     }
427 
428     /**
429      * Returns whether this link references a style sheet.
430      *
431      * @return {@code true} if the {@code rel} attribute contains
432      *         {@code stylesheet}
433      */
434     public boolean isStyleSheetLink() {
435         final String rel = getRelAttribute();
436         if (rel != null) {
437             return ArrayUtils.containsIgnoreCase(StringUtils.splitAtBlank(rel), "stylesheet");
438         }
439         return false;
440     }
441 
442     /**
443      * Returns whether this link references a module preload.
444      *
445      * @return {@code true} if the {@code rel} attribute contains
446      *         {@code modulepreload}
447      */
448     public boolean isModulePreloadLink() {
449         final String rel = getRelAttribute();
450         if (rel != null) {
451             return ArrayUtils.containsIgnoreCase(StringUtils.splitAtBlank(rel), "modulepreload");
452         }
453         return false;
454     }
455 
456     /**
457      * <p><span style="color:red">Experimental API: May be changed in next release
458      * and may not yet work perfectly!</span></p>
459      *
460      * Verifies if the provided node is a link node pointing to an active stylesheet.
461      *
462      * @return true if the provided node is a stylesheet link
463      */
464     public boolean isActiveStyleSheetLink() {
465         if (isStyleSheetLink()) {
466             final String media = getMediaAttribute();
467             if (StringUtils.isBlank(media)) {
468                 return true;
469             }
470 
471             final MediaListImpl mediaList =
472                     CssStyleSheet.parseMedia(media, getPage().getWebClient());
473             return CssStyleSheet.isActive(mediaList, getPage().getEnclosingWindow());
474         }
475         return false;
476     }
477 }