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.IOException;
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  import java.nio.charset.Charset;
21  import java.util.HashSet;
22  import java.util.Map;
23  import java.util.Objects;
24  import java.util.Set;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.htmlunit.FailingHttpStatusCodeException;
29  import org.htmlunit.FrameContentHandler;
30  import org.htmlunit.Page;
31  import org.htmlunit.SgmlPage;
32  import org.htmlunit.WebClient;
33  import org.htmlunit.WebRequest;
34  import org.htmlunit.WebWindow;
35  import org.htmlunit.html.csp.ContentSecurityPolicy;
36  import org.htmlunit.javascript.AbstractJavaScriptEngine;
37  import org.htmlunit.javascript.PostponedAction;
38  import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
39  import org.htmlunit.util.UrlUtils;
40  import org.w3c.dom.Attr;
41  
42  /**
43   * Base class for frame and iframe.
44   *
45   * @author Mike Bowler
46   * @author David K. Taylor
47   * @author Christian Sell
48   * @author Marc Guillemot
49   * @author David D. Kilzer
50   * @author Stefan Anzinger
51   * @author Ahmed Ashour
52   * @author Dmitri Zoubkov
53   * @author Daniel Gredler
54   * @author Ronald Brill
55   * @author Frank Danek
56   * @author Lai Quang Duong
57   */
58  public abstract class BaseFrameElement extends HtmlElement {
59  
60      /** The 'srcdoc' attribute (iframe only); the content of the document of the frame. */
61      public static final String SRCDOC_ATTRIBUTE = "srcdoc";
62  
63      /** The 'sandbox' attribute (iframe only); the restrictions of the document of the frame. */
64      public static final String SANDBOX_ATTRIBUTE = "sandbox";
65  
66      private static final Log LOG = LogFactory.getLog(BaseFrameElement.class);
67      private FrameWindow enclosedWindow_;
68      private boolean contentLoaded_;
69      private boolean loadSrcWhenAddedToPage_;
70  
71      /**
72       * Creates an instance of BaseFrame.
73       *
74       * @param qualifiedName the qualified name of the element type to instantiate
75       * @param page the HtmlPage that contains this element
76       * @param attributes the initial attributes
77       */
78      protected BaseFrameElement(final String qualifiedName, final SgmlPage page,
79              final Map<String, DomAttr> attributes) {
80          super(qualifiedName, page, attributes);
81  
82          init();
83  
84          if (null != page && page.isHtmlPage() && ((HtmlPage) page).isParsingHtmlSnippet()) {
85              // if created by the HTMLParser the src attribute is not set via setAttribute() or some other method but is
86              // part of the given attributes already.
87              final String src = getSrcAttribute();
88  
89              // src-less IFrame or src='about:blank'
90              // these are loaded sync
91              if (hasSrcdocAttribute()
92                      || (ATTRIBUTE_NOT_DEFINED != src && !UrlUtils.ABOUT_BLANK.equals(src.trim()))) {
93                  loadSrcWhenAddedToPage_ = true;
94              }
95          }
96      }
97  
98      private void init() {
99          FrameWindow enclosedWindow = null;
100         try {
101             final HtmlPage htmlPage = getHtmlPageOrNull();
102             if (null != htmlPage) { // if loaded as part of XHR.responseXML, don't load content
103                 enclosedWindow = new FrameWindow(this);
104                 // put about:blank in the window to allow JS to run on this frame before the
105                 // real content is loaded
106                 final WebClient webClient = htmlPage.getWebClient();
107                 final HtmlPage temporaryPage = webClient.getPage(enclosedWindow, WebRequest.newAboutBlankRequest());
108                 temporaryPage.setReadyState(READY_STATE_LOADING);
109             }
110         }
111         catch (final FailingHttpStatusCodeException | IOException ignored) {
112             // should never occur
113         }
114         enclosedWindow_ = enclosedWindow;
115     }
116 
117     /**
118      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
119      *
120      * Called after the node for the {@code frame} or {@code iframe} has been added to the containing page.
121      * The node needs to be added first to allow JavaScript in the frame to see the frame in the parent.
122      * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
123      *      {@link org.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is
124      *      set to true
125      */
126 
127     public void loadInnerPage() throws FailingHttpStatusCodeException {
128         String source = getSrcAttribute();
129         if (source.isEmpty()) {
130             source = UrlUtils.ABOUT_BLANK;
131         }
132 
133         loadInnerPageIfPossible(source);
134 
135         final Page enclosedPage = getEnclosedPage();
136         if (enclosedPage != null && enclosedPage.isHtmlPage()) {
137             final HtmlPage htmlPage = (HtmlPage) enclosedPage;
138 
139             final AbstractJavaScriptEngine<?> jsEngine = htmlPage.getWebClient().getJavaScriptEngine();
140             if (jsEngine != null && jsEngine.isScriptRunning()) {
141                 final PostponedAction action = new PostponedAction(getPage(), "BaseFrame.loadInnerPage") {
142                     @Override
143                     public void execute() {
144                         htmlPage.setReadyState(READY_STATE_COMPLETE);
145                     }
146                 };
147                 jsEngine.addPostponedAction(action);
148             }
149             else {
150                 htmlPage.setReadyState(READY_STATE_COMPLETE);
151             }
152         }
153     }
154 
155     /**
156      * Indicates if the content specified by the {@code src} attribute has been loaded or not.
157      * The initial state of a frame contains an "about:blank" that is not loaded like
158      * something specified in {@code src} attribute.
159      * @return {@code false} if the frame is still in its initial state.
160      */
161     boolean isContentLoaded() {
162         return contentLoaded_;
163     }
164 
165     /**
166      * Changes the state of the {@code contentLoaded_} attribute to true.
167      * This is needed, if the content is set from javascript to avoid
168      * later overwriting from method org.htmlunit.html.HtmlPage.loadFrames().
169      */
170     void setContentLoaded() {
171         contentLoaded_ = true;
172     }
173 
174     private void loadInnerPageIfPossible(final String src) throws FailingHttpStatusCodeException {
175         setContentLoaded();
176 
177         String source = src;
178         final SgmlPage page = getPage();
179         final WebClient webClient = page.getWebClient();
180         final FrameContentHandler handler = webClient.getFrameContentHandler();
181         if (null != handler && !handler.loadFrameDocument(this)) {
182             source = UrlUtils.ABOUT_BLANK;
183         }
184         else if (hasSrcdocAttribute()) {
185             // the srcdoc attribute has precedence over the src attribute; the content
186             // of the attribute is loaded as about:srcdoc (see WebClient)
187             source = UrlUtils.ABOUT_SRCDOC;
188         }
189 
190         if (!source.isEmpty()) {
191             final URL url;
192             try {
193                 // upgrade-insecure-requests of the Content-Security-Policy (nested navigation)
194                 url = ContentSecurityPolicy.upgradeInsecureRequest((HtmlPage) page,
195                         ((HtmlPage) page).getFullyQualifiedUrl(source));
196             }
197             catch (final MalformedURLException e) {
198                 notifyIncorrectness("Invalid src attribute of " + getTagName() + ": url=[" + source + "]. Ignored.");
199                 return;
200             }
201 
202             final URL pageUrl = page.getUrl();
203 
204             // accessing to local resource is forbidden for security reason
205             if (!((HtmlPage) page).isLocalResourceAccessAllowed(url)) {
206                 notifyIncorrectness("Not allowed to load local resource: " + source);
207                 return;
208             }
209 
210             final Charset pageCharset = page.getCharset();
211 
212             if (!UrlUtils.ABOUT_SRCDOC.equals(source) && isAlreadyLoadedByAncestor(url, pageCharset)) {
213                 notifyIncorrectness("Recursive src attribute of " + getTagName() + ": url=[" + source + "]. Ignored.");
214                 return;
215             }
216 
217             final WebRequest webRequest = new WebRequest(url, webClient.getBrowserVersion().getHtmlAcceptHeader(),
218                                                             webClient.getBrowserVersion().getAcceptEncodingHeader());
219             webRequest.setCharset(pageCharset);
220             webRequest.setRefererHeader(pageUrl);
221             if (page instanceof HtmlPage containingPage) {
222                 webRequest.setReferrerPolicy(containingPage.getReferrerPolicy(this));
223             }
224 
225             // Use parent document's charset as container charset if same origin
226             // https://html.spec.whatwg.org/multipage/parsing.html#determining-the-character-encoding
227             if (Objects.equals(pageUrl.getProtocol(), url.getProtocol())
228                     && Objects.equals(pageUrl.getAuthority(), url.getAuthority())) {
229                 webRequest.setDefaultResponseContentCharset(pageCharset);
230             }
231 
232             // Sec-Fetch-* support (https://www.w3.org/TR/fetch-metadata/): a frame/iframe
233             // load is a navigation initiated by the containing page, but - unlike a click
234             // or form submission - never carries user activation, since there is no
235             // gesture involved in an automatic <iframe>/<frame> load.
236             final WebRequest.FetchDestination fetchDestination = this instanceof HtmlInlineFrame
237                     ? WebRequest.FetchDestination.IFRAME
238                     : WebRequest.FetchDestination.FRAME;
239             webRequest.markAsNavigation(fetchDestination, pageUrl, false);
240             // the site for cookies of a frame is the one of its container document
241             webRequest.setSiteForCookies(((HtmlPage) page).getSiteForCookiesUrl());
242 
243             // about:blank is not fetched and javascript: urls are checked against script-src;
244             // both are not checked against frame-src
245             final boolean[] redirectBlocked = {false};
246             final String protocol = url.getProtocol();
247             if (!"about".equals(protocol) && !"javascript".equals(protocol)) {
248                 final HtmlPage htmlPage = (HtmlPage) page;
249                 final boolean allowed = ContentSecurityPolicy.allowsFrame(htmlPage, url);
250                 // like the browsers, the violation event (also for report only policies)
251                 // is fired before the frame is loaded
252                 ContentSecurityPolicy.firePendingViolations();
253                 if (!allowed) {
254                     loadDeniedPage(webClient);
255                     return;
256                 }
257 
258                 // like the browsers, redirects are checked (and upgraded) also
259                 ContentSecurityPolicy.upgradeInsecureRedirects(htmlPage, webRequest);
260                 webRequest.setRedirectFilter(redirectUrl -> {
261                     if (ContentSecurityPolicy.allowsFrame(htmlPage, redirectUrl)) {
262                         return true;
263                     }
264                     redirectBlocked[0] = true;
265                     return false;
266                 });
267             }
268 
269             // the sandbox flags are determined when the frame starts loading
270             enclosedWindow_.setSandboxTokens(getEffectiveSandboxTokens((HtmlPage) page));
271 
272             try {
273                 webClient.getPage(enclosedWindow_, webRequest);
274             }
275             catch (final IOException e) {
276                 if (LOG.isErrorEnabled()) {
277                     LOG.error("IOException when getting content for " + getTagName() + ": url=[" + url + "]", e);
278                 }
279             }
280 
281             if (redirectBlocked[0]) {
282                 loadDeniedPage(webClient);
283             }
284         }
285     }
286 
287     /**
288      * Loads about:blank into the frame and marks the frame as denied by the
289      * Content-Security-Policy (like the error page shown by the browsers, the content
290      * of the frame is not accessible).
291      *
292      * @param webClient the web client
293      */
294     private void loadDeniedPage(final WebClient webClient) {
295         // like the browsers, the violation event is fired before the load event of the frame
296         ContentSecurityPolicy.firePendingViolations();
297         try {
298             webClient.loadDeniedPageInto(enclosedWindow_, FrameWindow.PageDenied.BY_CONTENT_SECURIRY_POLICY);
299         }
300         catch (final IOException e) {
301             if (LOG.isErrorEnabled()) {
302                 LOG.error("IOException when loading about:blank into " + getTagName(), e);
303             }
304         }
305     }
306 
307     /**
308      * Test if the provided URL is the one of the parents which would cause an infinite loop.
309      * @param url the URL to test
310      * @param charset the request charset
311      * @return {@code false} if no parent has already this URL
312      */
313     private boolean isAlreadyLoadedByAncestor(final URL url, final Charset charset) {
314         WebWindow window = getPage().getEnclosingWindow();
315         int nesting = 0;
316         while (window instanceof FrameWindow) {
317             nesting++;
318             if (nesting > 9) {
319                 return true;
320             }
321 
322             final URL encUrl = UrlUtils.encodeUrl(url, charset);
323             if (UrlUtils.sameFile(encUrl, window.getEnclosedPage().getUrl())) {
324                 return true;
325             }
326 
327             if (window == window.getParentWindow()) {
328                 // TODO: should getParentWindow() return null on top windows?
329                 window = null;
330             }
331             else {
332                 window = window.getParentWindow();
333             }
334         }
335         return false;
336     }
337 
338     /**
339      * Returns the value of the attribute {@code longdesc}. Refer to the
340      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
341      * documentation for details on the use of this attribute.
342      *
343      * @return the value of the attribute {@code longdesc} or an empty string if that attribute isn't defined
344      */
345     public final String getLongDescAttribute() {
346         return getAttributeDirect("longdesc");
347     }
348 
349     /**
350      * Returns the value of the attribute {@code name}. Refer to the
351      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
352      * documentation for details on the use of this attribute.
353      *
354      * @return the value of the attribute {@code name} or an empty string if that attribute isn't defined
355      */
356     public final String getNameAttribute() {
357         return getAttributeDirect(NAME_ATTRIBUTE);
358     }
359 
360     /**
361      * Sets the value of the {@code name} attribute.
362      *
363      * @param name the new window name
364      */
365     public final void setNameAttribute(final String name) {
366         setAttribute(NAME_ATTRIBUTE, name);
367     }
368 
369     /**
370      * Returns the value of the attribute {@code src}. Refer to the
371      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
372      * documentation for details on the use of this attribute.
373      *
374      * @return the value of the attribute {@code src} or an empty string if that attribute isn't defined
375      */
376     public final String getSrcAttribute() {
377         return getSrcAttributeNormalized();
378     }
379 
380     /**
381      * Returns the value of the attribute {@code frameborder}. Refer to the
382      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
383      * documentation for details on the use of this attribute.
384      *
385      * @return the value of the attribute {@code frameborder} or an empty string if that attribute isn't defined
386      */
387     public final String getFrameBorderAttribute() {
388         return getAttributeDirect("frameborder");
389     }
390 
391     /**
392      * Returns the value of the attribute {@code marginwidth}. Refer to the
393      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
394      * documentation for details on the use of this attribute.
395      *
396      * @return the value of the attribute {@code marginwidth} or an empty string if that attribute isn't defined
397      */
398     public final String getMarginWidthAttribute() {
399         return getAttributeDirect("marginwidth");
400     }
401 
402     /**
403      * Returns the value of the attribute {@code marginheight}. Refer to the
404      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
405      * documentation for details on the use of this attribute.
406      *
407      * @return the value of the attribute {@code marginheight} or an empty string if that attribute isn't defined
408      */
409     public final String getMarginHeightAttribute() {
410         return getAttributeDirect("marginheight");
411     }
412 
413     /**
414      * Returns the value of the attribute {@code noresize}. Refer to the
415      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
416      * documentation for details on the use of this attribute.
417      *
418      * @return the value of the attribute {@code noresize} or an empty string if that attribute isn't defined
419      */
420     public final String getNoResizeAttribute() {
421         return getAttributeDirect("noresize");
422     }
423 
424     /**
425      * Returns the value of the attribute {@code scrolling}. Refer to the
426      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
427      * documentation for details on the use of this attribute.
428      *
429      * @return the value of the attribute {@code scrolling} or an empty string if that attribute isn't defined
430      */
431     public final String getScrollingAttribute() {
432         return getAttributeDirect("scrolling");
433     }
434 
435     /**
436      * Returns the value of the attribute {@code onload}. This attribute is not
437      * actually supported by the HTML specification however it is supported
438      * by the popular browsers.
439      *
440      * @return the value of the attribute {@code onload} or an empty string if that attribute isn't defined
441      */
442     public final String getOnLoadAttribute() {
443         return getAttributeDirect("onload");
444     }
445 
446     /**
447      * Returns the currently loaded page in the enclosed window.
448      * This is a facility method for <code>getEnclosedWindow().getEnclosedPage()</code>.
449      * @see WebWindow#getEnclosedPage()
450      * @return the currently loaded page in the enclosed window, or {@code null} if no page has been loaded
451      */
452     public Page getEnclosedPage() {
453         return getEnclosedWindow().getEnclosedPage();
454     }
455 
456     /**
457      * Gets the window enclosed in this frame.
458      * @return the window enclosed in this frame
459      */
460     public FrameWindow getEnclosedWindow() {
461         return enclosedWindow_;
462     }
463 
464     /**
465      * Sets the value of the {@code src} attribute. Also loads the frame with the specified URL, if possible.
466      * @param attribute the new value of the {@code src} attribute
467      */
468     public final void setSrcAttribute(final String attribute) {
469         setAttribute(SRC_ATTRIBUTE, attribute);
470     }
471 
472     /**
473      * {@inheritDoc}
474      */
475     @Override
476     protected void setAttributeNS(final String namespaceURI, final String qualifiedName, final String attributeValue,
477             final boolean notifyAttributeChangeListeners, final boolean notifyMutationObserver) {
478         final String qualifiedNameLC = org.htmlunit.util.StringUtils.toRootLowerCase(qualifiedName);
479 
480         if (null != attributeValue && SRCDOC_ATTRIBUTE.equals(qualifiedNameLC) && this instanceof HtmlInlineFrame) {
481             super.setAttributeNS(namespaceURI, qualifiedNameLC, attributeValue, notifyAttributeChangeListeners,
482                     notifyMutationObserver);
483 
484             // setting the srcdoc attribute (also to the same value) loads the content
485             if (isAttachedToPage()) {
486                 loadSrcdoc();
487             }
488             else {
489                 loadSrcWhenAddedToPage_ = true;
490             }
491             return;
492         }
493 
494         if (null != attributeValue && SRC_ATTRIBUTE.equals(qualifiedNameLC)) {
495             final String attributeValueTrimmed = attributeValue.trim();
496 
497             super.setAttributeNS(namespaceURI, qualifiedNameLC, attributeValueTrimmed, notifyAttributeChangeListeners,
498                     notifyMutationObserver);
499 
500             // do not use equals() here
501             // see HTMLIFrameElement2Test.documentCreateElement_onLoad_srcAboutBlank()
502             if (UrlUtils.ABOUT_BLANK != attributeValueTrimmed) {
503                 if (isAttachedToPage()) {
504                     loadSrc();
505                 }
506                 else {
507                     loadSrcWhenAddedToPage_ = true;
508                 }
509             }
510 
511             return;
512         }
513 
514         super.setAttributeNS(namespaceURI, qualifiedNameLC, attributeValue, notifyAttributeChangeListeners,
515                 notifyMutationObserver);
516     }
517 
518     /**
519      * {@inheritDoc}
520      */
521     @Override
522     public Attr setAttributeNode(final Attr attribute) {
523         final String qualifiedName = attribute.getName();
524         String attributeValue = null;
525         if (SRC_ATTRIBUTE.equals(qualifiedName)) {
526             attributeValue = attribute.getValue().trim();
527         }
528 
529         final Attr result = super.setAttributeNode(attribute);
530 
531         if (SRC_ATTRIBUTE.equals(qualifiedName) && !UrlUtils.ABOUT_BLANK.equals(attributeValue)) {
532             if (isAttachedToPage()) {
533                 loadSrc();
534             }
535             else {
536                 loadSrcWhenAddedToPage_ = true;
537             }
538         }
539 
540         return result;
541     }
542 
543     private void loadSrc() {
544         loadSrcWhenAddedToPage_ = false;
545         final String src = getSrcAttribute();
546 
547         // recreate a window if the old one was closed
548         if (enclosedWindow_.isClosed()) {
549             init();
550         }
551 
552         final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
553         // When src is set from a script, loading is postponed until script finishes
554         // in fact this implementation is probably wrong: JavaScript URL should be
555         // first evaluated and only loading, when any, should be postponed.
556         if (jsEngine == null || !jsEngine.isScriptRunning()
557                 || src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
558             loadInnerPageIfPossible(src);
559         }
560         else {
561             final Page pageInFrame = getEnclosedPage();
562             final PostponedAction action = new PostponedAction(getPage(), "BaseFrame.loadSrc") {
563                 @Override
564                 public void execute() throws Exception {
565                     if (!src.isEmpty() && getSrcAttribute().equals(src)) {
566                         loadInnerPage();
567                     }
568                 }
569 
570                 @Override
571                 public boolean isStillAlive() {
572                     // skip if page in frame has already been changed
573                     return super.isStillAlive() && pageInFrame == getEnclosedPage();
574                 }
575             };
576             jsEngine.addPostponedAction(action);
577         }
578     }
579 
580     /**
581      * Loads the content of the srcdoc attribute into the frame; like loadSrc(), the loading is
582      * postponed if a script is running.
583      */
584     private void loadSrcdoc() {
585         loadSrcWhenAddedToPage_ = false;
586 
587         // recreate a window if the old one was closed
588         if (enclosedWindow_.isClosed()) {
589             init();
590         }
591 
592         final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
593         if (jsEngine == null || !jsEngine.isScriptRunning()) {
594             loadInnerPage();
595         }
596         else {
597             final Page pageInFrame = getEnclosedPage();
598             final PostponedAction action = new PostponedAction(getPage(), "BaseFrame.loadSrcdoc") {
599                 @Override
600                 public void execute() throws Exception {
601                     if (hasSrcdocAttribute()) {
602                         loadInnerPage();
603                     }
604                 }
605 
606                 @Override
607                 public boolean isStillAlive() {
608                     // skip if page in frame has already been changed
609                     return super.isStillAlive() && pageInFrame == getEnclosedPage();
610                 }
611             };
612             jsEngine.addPostponedAction(action);
613         }
614     }
615 
616     /**
617      * Returns the sandbox tokens for the document of this frame: the tokens of the sandbox attribute
618      * (iframe only) restricted by the sandbox of the containing document.
619      *
620      * @param containingPage the page containing this frame
621      * @return the allowed tokens or {@code null} if the document is not sandboxed
622      */
623     private Set<String> getEffectiveSandboxTokens(final HtmlPage containingPage) {
624         Set<String> tokens = null;
625         if (this instanceof HtmlInlineFrame) {
626             final String sandbox = getAttributeDirect(SANDBOX_ATTRIBUTE);
627             if (ATTRIBUTE_NOT_DEFINED != sandbox) {
628                 tokens = new HashSet<>();
629                 for (final String token : org.htmlunit.util.StringUtils.splitAtJavaWhitespace(sandbox)) {
630                     if (!token.isEmpty()) {
631                         tokens.add(org.htmlunit.util.StringUtils.toRootLowerCase(token));
632                     }
633                 }
634             }
635         }
636 
637         // a frame of a sandboxed document is sandboxed also
638         final Set<String> containingTokens = containingPage.getSandboxTokens();
639         if (containingTokens != null) {
640             if (tokens == null) {
641                 tokens = new HashSet<>(containingTokens);
642             }
643             else {
644                 tokens.retainAll(containingTokens);
645             }
646         }
647         return tokens;
648     }
649 
650     /**
651      * Returns whether this is an iframe with srcdoc attribute; the srcdoc attribute
652      * has precedence over the src attribute.
653      *
654      * @return true if the srcdoc attribute is defined
655      */
656     public boolean hasSrcdocAttribute() {
657         return this instanceof HtmlInlineFrame && ATTRIBUTE_NOT_DEFINED != getAttributeDirect(SRCDOC_ATTRIBUTE);
658     }
659 
660     /**
661      * Creates a new {@link WebWindow} for the new clone.
662      * {@inheritDoc}
663      */
664     @Override
665     public DomNode cloneNode(final boolean deep) {
666         final BaseFrameElement clone = (BaseFrameElement) super.cloneNode(deep);
667         clone.init();
668         return clone;
669     }
670 
671     @Override
672     protected void onAddedToPage() {
673         super.onAddedToPage();
674 
675         if (loadSrcWhenAddedToPage_) {
676             if (hasSrcdocAttribute()) {
677                 loadSrcdoc();
678             }
679             else {
680                 loadSrc();
681             }
682         }
683     }
684 
685     @Override
686     public void remove() {
687         super.remove();
688         loadSrcWhenAddedToPage_ = true;
689         getEnclosedWindow().close();
690     }
691 
692     @Override
693     public final void removeAttribute(final String attributeName) {
694         super.removeAttribute(attributeName);
695 
696         // TODO find a better implementation without all the code duplication
697         if (isAttachedToPage()) {
698             loadSrcWhenAddedToPage_ = false;
699             final String src = getSrcAttribute();
700 
701             final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
702             // When src is set from a script, loading is postponed until script finishes
703             // in fact this implementation is probably wrong: JavaScript URL should be
704             // first evaluated and only loading, when any, should be postponed.
705             if (jsEngine == null || !jsEngine.isScriptRunning()) {
706                 loadInnerPageIfPossible(src);
707             }
708             else {
709                 final Page pageInFrame = getEnclosedPage();
710                 final PostponedAction action = new PostponedAction(getPage(), "BaseFrame.removeAttribute") {
711                     @Override
712                     public void execute() throws Exception {
713                         loadInnerPage();
714                     }
715 
716                     @Override
717                     public boolean isStillAlive() {
718                         // skip if page in frame has already been changed
719                         return super.isStillAlive() && pageInFrame == getEnclosedPage();
720                     }
721                 };
722                 jsEngine.addPostponedAction(action);
723             }
724         }
725         else {
726             loadSrcWhenAddedToPage_ = true;
727         }
728     }
729 }