2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004-2020 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
9 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
12 * This library is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Library General Public
14 * License as published by the Free Software Foundation; either
15 * version 2 of the License, or (at your option) any later version.
17 * This library is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public License
23 * along with this library; see the file COPYING.LIB. If not, write to
24 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 * Boston, MA 02110-1301, USA.
31 #include "AXObjectCache.h"
33 #include "BeforeUnloadEvent.h"
34 #include "CDATASection.h"
35 #include "CSSAnimationController.h"
36 #include "CSSFontSelector.h"
37 #include "CSSStyleDeclaration.h"
38 #include "CSSStyleSheet.h"
39 #include "CachedCSSStyleSheet.h"
40 #include "CachedFrame.h"
41 #include "CachedResourceLoader.h"
42 #include "CanvasRenderingContext2D.h"
44 #include "ChromeClient.h"
47 #include "ComposedTreeIterator.h"
48 #include "CompositionEvent.h"
49 #include "ConstantPropertyMap.h"
50 #include "ContentSecurityPolicy.h"
51 #include "ContentfulPaintChecker.h"
52 #include "CookieJar.h"
53 #include "CustomElementReactionQueue.h"
54 #include "CustomElementRegistry.h"
55 #include "CustomEvent.h"
56 #include "DOMImplementation.h"
57 #include "DOMWindow.h"
58 #include "DateComponents.h"
59 #include "DebugPageOverlays.h"
60 #include "DeprecatedGlobalSettings.h"
61 #include "DocumentLoader.h"
62 #include "DocumentMarkerController.h"
63 #include "DocumentSharedObjectPool.h"
64 #include "DocumentTimeline.h"
65 #include "DocumentTimelinesController.h"
66 #include "DocumentType.h"
67 #include "DragEvent.h"
70 #include "ElementIterator.h"
71 #include "EventHandler.h"
72 #include "ExtensionStyleSheets.h"
73 #include "FocusController.h"
74 #include "FocusEvent.h"
75 #include "FontFaceSet.h"
76 #include "FormController.h"
78 #include "FrameLoader.h"
79 #include "FrameLoaderClient.h"
80 #include "FrameView.h"
81 #include "FullscreenManager.h"
82 #include "GCReachableRef.h"
83 #include "GenericCachedHTMLCollection.h"
84 #include "HTMLAllCollection.h"
85 #include "HTMLAnchorElement.h"
86 #include "HTMLAttachmentElement.h"
87 #include "HTMLBaseElement.h"
88 #include "HTMLBodyElement.h"
89 #include "HTMLCanvasElement.h"
90 #include "HTMLDocument.h"
91 #include "HTMLElementFactory.h"
92 #include "HTMLFormControlElement.h"
93 #include "HTMLFrameElement.h"
94 #include "HTMLFrameOwnerElement.h"
95 #include "HTMLFrameSetElement.h"
96 #include "HTMLHeadElement.h"
97 #include "HTMLHtmlElement.h"
98 #include "HTMLIFrameElement.h"
99 #include "HTMLImageElement.h"
100 #include "HTMLInputElement.h"
101 #include "HTMLLinkElement.h"
102 #include "HTMLMediaElement.h"
103 #include "HTMLNameCollection.h"
104 #include "HTMLParserIdioms.h"
105 #include "HTMLPictureElement.h"
106 #include "HTMLPlugInElement.h"
107 #include "HTMLScriptElement.h"
108 #include "HTMLStyleElement.h"
109 #include "HTMLTitleElement.h"
110 #include "HTMLUnknownElement.h"
111 #include "HTTPHeaderNames.h"
112 #include "HTTPParsers.h"
113 #include "HashChangeEvent.h"
114 #include "HighlightMap.h"
116 #include "HitTestResult.h"
117 #include "IdleCallbackController.h"
118 #include "ImageBitmapRenderingContext.h"
119 #include "ImageLoader.h"
120 #include "InspectorInstrumentation.h"
121 #include "IntersectionObserver.h"
122 #include "JSCustomElementInterface.h"
123 #include "JSLazyEventListener.h"
124 #include "KeyboardEvent.h"
125 #include "KeyframeEffect.h"
126 #include "LayoutDisallowedScope.h"
127 #include "LazyLoadImageObserver.h"
128 #include "LegacySchemeRegistry.h"
129 #include "LibWebRTCProvider.h"
130 #include "LoaderStrategy.h"
132 #include "MediaCanStartListener.h"
133 #include "MediaProducer.h"
134 #include "MediaQueryList.h"
135 #include "MediaQueryMatcher.h"
136 #include "MediaStream.h"
137 #include "MessageEvent.h"
138 #include "MouseEventWithHitTestResults.h"
139 #include "MutationEvent.h"
140 #include "NameNodeList.h"
141 #include "NavigationDisabler.h"
142 #include "NavigationScheduler.h"
143 #include "NestingLevelIncrementer.h"
144 #include "NodeIterator.h"
145 #include "NodeRareData.h"
146 #include "NodeWithIndex.h"
147 #include "OverflowEvent.h"
148 #include "PageConsoleClient.h"
149 #include "PageGroup.h"
150 #include "PageTransitionEvent.h"
151 #include "PaintWorkletGlobalScope.h"
152 #include "Performance.h"
153 #include "PlatformLocale.h"
154 #include "PlatformMediaSessionManager.h"
155 #include "PlatformScreen.h"
156 #include "PlatformStrategies.h"
157 #include "PlugInsResources.h"
158 #include "PluginDocument.h"
159 #include "PointerCaptureController.h"
160 #include "PointerLockController.h"
161 #include "PolicyChecker.h"
162 #include "PopStateEvent.h"
163 #include "ProcessingInstruction.h"
164 #include "PublicSuffix.h"
166 #include "RealtimeMediaSourceCenter.h"
167 #include "RenderChildIterator.h"
168 #include "RenderInline.h"
169 #include "RenderLayerCompositor.h"
170 #include "RenderLineBreak.h"
171 #include "RenderTreeUpdater.h"
172 #include "RenderView.h"
173 #include "RenderWidget.h"
174 #include "RequestAnimationFrameCallback.h"
175 #include "ResizeObserver.h"
176 #include "ResourceLoadObserver.h"
177 #include "RuntimeApplicationChecks.h"
178 #include "RuntimeEnabledFeatures.h"
179 #include "SVGDocumentExtensions.h"
180 #include "SVGElement.h"
181 #include "SVGElementFactory.h"
182 #include "SVGNames.h"
183 #include "SVGSVGElement.h"
184 #include "SVGTitleElement.h"
185 #include "SVGUseElement.h"
186 #include "SVGZoomEvent.h"
187 #include "SWClientConnection.h"
188 #include "ScopedEventQueue.h"
189 #include "ScriptController.h"
190 #include "ScriptDisallowedScope.h"
191 #include "ScriptModuleLoader.h"
192 #include "ScriptRunner.h"
193 #include "ScriptSourceCode.h"
194 #include "ScriptState.h"
195 #include "ScriptedAnimationController.h"
196 #include "ScrollbarTheme.h"
197 #include "ScrollingCoordinator.h"
198 #include "SecurityOrigin.h"
199 #include "SecurityOriginData.h"
200 #include "SecurityOriginPolicy.h"
201 #include "SecurityPolicy.h"
202 #include "SegmentedString.h"
203 #include "SelectorQuery.h"
204 #include "ServiceWorkerClientData.h"
205 #include "ServiceWorkerContainer.h"
206 #include "ServiceWorkerProvider.h"
207 #include "Settings.h"
208 #include "ShadowRoot.h"
209 #include "SocketProvider.h"
210 #include "StorageEvent.h"
211 #include "StringCallback.h"
212 #include "StyleAdjuster.h"
213 #include "StyleColor.h"
214 #include "StyleProperties.h"
215 #include "StyleResolveForDocument.h"
216 #include "StyleResolver.h"
217 #include "StyleScope.h"
218 #include "StyleSheetContents.h"
219 #include "StyleSheetList.h"
220 #include "StyleTreeResolver.h"
221 #include "SubresourceLoader.h"
222 #include "TextAutoSizing.h"
223 #include "TextEvent.h"
224 #include "TextManipulationController.h"
225 #include "TextNodeTraversal.h"
226 #include "TouchAction.h"
227 #include "TransformSource.h"
228 #include "TreeWalker.h"
229 #include "UndoManager.h"
230 #include "UserGestureIndicator.h"
231 #include "ValidationMessageClient.h"
232 #include "VisibilityChangeClient.h"
233 #include "VisitedLinkState.h"
234 #include "VisualViewport.h"
235 #include "WebAnimation.h"
236 #include "WebAnimationUtilities.h"
237 #include "WheelEvent.h"
238 #include "WindowEventLoop.h"
239 #include "WindowFeatures.h"
241 #include "XMLDocument.h"
242 #include "XMLDocumentParser.h"
243 #include "XMLNSNames.h"
244 #include "XMLNames.h"
245 #include "XPathEvaluator.h"
246 #include "XPathExpression.h"
247 #include "XPathNSResolver.h"
248 #include "XPathResult.h"
249 #include <JavaScriptCore/ConsoleMessage.h>
250 #include <JavaScriptCore/RegularExpression.h>
251 #include <JavaScriptCore/ScriptCallStack.h>
252 #include <JavaScriptCore/VM.h>
254 #include <wtf/IsoMallocInlines.h>
255 #include <wtf/Language.h>
256 #include <wtf/NeverDestroyed.h>
257 #include <wtf/SetForScope.h>
258 #include <wtf/SystemTracing.h>
259 #include <wtf/UUID.h>
260 #include <wtf/text/StringBuffer.h>
261 #include <wtf/text/TextStream.h>
263 #if ENABLE(DEVICE_ORIENTATION)
264 #include "DeviceMotionEvent.h"
265 #include "DeviceOrientationAndMotionAccessController.h"
266 #include "DeviceOrientationEvent.h"
269 #if ENABLE(FULLSCREEN_API)
270 #include "RenderFullScreen.h"
273 #if ENABLE(INDEXED_DATABASE)
274 #include "IDBConnectionProxy.h"
275 #include "IDBOpenDBRequest.h"
278 #if PLATFORM(IOS_FAMILY)
279 #include "ContentChangeObserver.h"
280 #include "CSSFontSelector.h"
281 #include "DOMTimerHoldingTank.h"
282 #include "DeviceMotionClientIOS.h"
283 #include "DeviceMotionController.h"
284 #include "DeviceOrientationClientIOS.h"
285 #include "DeviceOrientationController.h"
286 #include "Geolocation.h"
287 #include "Navigator.h"
288 #include "NavigatorGeolocation.h"
291 #if ENABLE(IOS_GESTURE_EVENTS)
292 #include "GestureEvent.h"
296 #include "MathMLElement.h"
297 #include "MathMLElementFactory.h"
298 #include "MathMLNames.h"
301 #if ENABLE(MEDIA_SESSION)
302 #include "MediaSession.h"
306 #include "QuickLook.h"
309 #if ENABLE(TOUCH_EVENTS)
310 #include "TouchEvent.h"
314 #include "CaptionUserPreferences.h"
317 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
318 #include "MediaPlaybackTargetClient.h"
322 #include "XSLTProcessor.h"
326 #include "WebGLRenderingContext.h"
329 #include "WebGL2RenderingContext.h"
332 #include "GPUCanvasContext.h"
335 #if ENABLE(PICTURE_IN_PICTURE_API)
336 #include "HTMLVideoElement.h"
339 #define RELEASE_LOG_IF_ALLOWED(channel, fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), channel, "%p - [pageID=%" PRIu64 ", frameID=%" PRIu64 ", main=%d] Document::" fmt, this, pageID().valueOr(PageIdentifier { }).toUInt64(), frameID().valueOr(FrameIdentifier { }).toUInt64(), this == &topDocument(), ##__VA_ARGS__)
340 #define RELEASE_LOG_ERROR_IF_ALLOWED(channel, fmt, ...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), channel, "%p - [pageID=%" PRIu64 ", frameID=%" PRIu64 ", main=%d] Document::" fmt, this, pageID().valueOr(PageIdentifier { }).toUInt64(), frameID().valueOr(FrameIdentifier { }).toUInt64(), this == &topDocument(), ##__VA_ARGS__)
344 WTF_MAKE_ISO_ALLOCATED_IMPL(Document);
346 using namespace HTMLNames;
348 using namespace WTF::Unicode;
350 static const unsigned cMaxWriteRecursionDepth = 21;
351 bool Document::hasEverCreatedAnAXObjectCache = false;
352 static const Seconds maxIntervalForUserGestureForwardingAfterMediaFinishesPlaying { 1_s };
354 struct FrameFlatteningLayoutDisallower {
355 FrameFlatteningLayoutDisallower(FrameView& frameView)
356 : m_frameView(frameView)
357 , m_disallowLayout(frameView.effectiveFrameFlattening() != FrameFlattening::Disabled)
359 if (m_disallowLayout)
360 m_frameView.startDisallowingLayout();
363 ~FrameFlatteningLayoutDisallower()
365 if (m_disallowLayout)
366 m_frameView.endDisallowingLayout();
370 FrameView& m_frameView;
371 bool m_disallowLayout { false };
374 // Defined here to avoid including GCReachableRef.h in Document.h
375 struct Document::PendingScrollEventTargetList {
376 WTF_MAKE_FAST_ALLOCATED;
379 Vector<GCReachableRef<ContainerNode>> targets;
382 #if ENABLE(INTERSECTION_OBSERVER)
383 static const Seconds intersectionObserversInitialUpdateDelay { 2000_ms };
386 // DOM Level 2 says (letters added):
388 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
389 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
390 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
391 // d) Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.
392 // e) The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
393 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
394 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
395 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
396 // i) Characters ':' and '_' are allowed as name-start characters.
397 // j) Characters '-' and '.' are allowed as name characters.
399 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
401 static inline bool isValidNameStart(UChar32 c)
404 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
408 if (c == ':' || c == '_')
411 // rules (a) and (f) above
412 if (!(U_GET_GC_MASK(c) & (U_GC_LL_MASK | U_GC_LU_MASK | U_GC_LO_MASK | U_GC_LT_MASK | U_GC_NL_MASK)))
416 if (c >= 0xF900 && c < 0xFFFE)
420 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
421 if (type == U_DT_FONT || type == U_DT_COMPAT)
427 static inline bool isValidNamePart(UChar32 c)
429 // rules (a), (e), and (i) above
430 if (isValidNameStart(c))
433 // rules (g) and (h) above
434 if (c == 0x00B7 || c == 0x0387)
438 if (c == '-' || c == '.')
441 // rules (b) and (f) above
442 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
446 if (c >= 0xF900 && c < 0xFFFE)
450 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
451 if (type == U_DT_FONT || type == U_DT_COMPAT)
457 static Widget* widgetForElement(Element* focusedElement)
461 auto* renderer = focusedElement->renderer();
462 if (!is<RenderWidget>(renderer))
464 return downcast<RenderWidget>(*renderer).widget();
467 static bool acceptsEditingFocus(const Element& element)
469 ASSERT(element.hasEditableStyle());
471 auto* root = element.rootEditableElement();
472 Frame* frame = element.document().frame();
476 return frame->editor().shouldBeginEditing(makeRangeSelectingNodeContents(*root));
479 static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
481 // targetFrame can be 0 when we're trying to navigate a top-level frame
482 // that has a 0 opener.
486 const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
487 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
488 Document* ancestorDocument = ancestorFrame->document();
489 // FIXME: Should be an ASSERT? Frames should alway have documents.
490 if (!ancestorDocument)
493 const SecurityOrigin& ancestorSecurityOrigin = ancestorDocument->securityOrigin();
494 if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
497 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
498 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
499 // something more general instead?
500 if (isLocalActiveOrigin && ancestorSecurityOrigin.isLocal())
507 static void printNavigationErrorMessage(Frame& frame, const URL& activeURL, const char* reason)
509 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
511 // FIXME: should we print to the console of the document performing the navigation instead?
512 frame.document()->domWindow()->printErrorMessage(message);
515 uint64_t Document::s_globalTreeVersion = 0;
517 auto Document::allDocumentsMap() -> DocumentsMap&
519 static NeverDestroyed<DocumentsMap> documents;
523 auto Document::allDocuments() -> DocumentsMap::ValuesIteratorRange
525 return allDocumentsMap().values();
528 static inline int currentOrientation(Frame* frame)
530 #if ENABLE(ORIENTATION_EVENTS)
532 return frame->orientation();
539 Document::Document(Frame* frame, const URL& url, DocumentClassFlags documentClasses, unsigned constructionFlags)
540 : ContainerNode(*this, CreateDocument)
542 , FrameDestructionObserver(frame)
543 , m_settings(frame ? Ref<Settings>(frame->settings()) : Settings::create(nullptr))
544 , m_quirks(makeUniqueRef<Quirks>(*this))
545 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
546 , m_domTreeVersion(++s_globalTreeVersion)
547 , m_styleScope(makeUnique<Style::Scope>(*this))
548 , m_extensionStyleSheets(makeUnique<ExtensionStyleSheets>(*this))
549 , m_visitedLinkState(makeUnique<VisitedLinkState>(*this))
550 , m_markers(makeUnique<DocumentMarkerController>(*this))
551 , m_styleRecalcTimer([this] { updateStyleIfNeeded(); })
553 , m_documentCreationTime(MonotonicTime::now())
555 , m_scriptRunner(makeUnique<ScriptRunner>(*this))
556 , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this))
558 , m_applyPendingXSLTransformsTimer(*this, &Document::applyPendingXSLTransformsTimerFired)
560 , m_xmlVersion("1.0"_s)
561 , m_constantPropertyMap(makeUnique<ConstantPropertyMap>(*this))
562 , m_documentClasses(documentClasses)
563 #if ENABLE(FULLSCREEN_API)
564 , m_fullscreenManager { makeUniqueRef<FullscreenManager>(*this) }
566 #if ENABLE(INTERSECTION_OBSERVER)
567 , m_intersectionObserversInitialUpdateTimer(*this, &Document::scheduleTimedRenderingUpdate)
569 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
570 #if PLATFORM(IOS_FAMILY) && ENABLE(DEVICE_ORIENTATION)
571 , m_deviceMotionClient(makeUnique<DeviceMotionClientIOS>(page() ? page()->deviceOrientationUpdateProvider() : nullptr))
572 , m_deviceMotionController(makeUnique<DeviceMotionController>(*m_deviceMotionClient))
573 , m_deviceOrientationClient(makeUnique<DeviceOrientationClientIOS>(page() ? page()->deviceOrientationUpdateProvider() : nullptr))
574 , m_deviceOrientationController(makeUnique<DeviceOrientationController>(*m_deviceOrientationClient))
576 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
577 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
578 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
579 , m_fontSelector(CSSFontSelector::create(*this))
580 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
581 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
582 , m_socketProvider(page() ? &page()->socketProvider() : nullptr)
583 , m_isSynthesized(constructionFlags & Synthesized)
584 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
585 , m_orientationNotifier(currentOrientation(frame))
586 , m_identifier(DocumentIdentifier::generate())
587 , m_undoManager(UndoManager::create(*this))
588 , m_editor(makeUniqueRef<Editor>(*this))
589 , m_selection(makeUniqueRef<FrameSelection>(this))
591 auto addResult = allDocumentsMap().add(m_identifier, this);
592 ASSERT_UNUSED(addResult, addResult.isNewEntry);
594 // We depend on the url getting immediately set in subframes, but we
595 // also depend on the url NOT getting immediately set in opened windows.
596 // See fast/dom/early-frame-url.html
597 // and fast/dom/location-new-window-no-crash.html, respectively.
598 // FIXME: Can/should we unify this behavior?
599 if ((frame && frame->ownerElement()) || !url.isEmpty())
602 m_cachedResourceLoader->setDocument(this);
605 resetVisitedLinkColor();
606 resetActiveLinkColor();
608 initSecurityContext();
611 m_fontSelector->registerForInvalidationCallbacks(*this);
613 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
614 nodeListAndCollectionCount = 0;
616 InspectorInstrumentation::addEventListenersToNode(*this);
617 #if ENABLE(MEDIA_STREAM)
618 m_settings->setLegacyGetUserMediaEnabled(quirks().shouldEnableLegacyGetUserMedia());
622 Ref<Document> Document::create(Document& contextDocument)
624 auto document = adoptRef(*new Document(nullptr, URL()));
625 document->setContextDocument(contextDocument);
626 document->setSecurityOriginPolicy(contextDocument.securityOriginPolicy());
630 Ref<Document> Document::createNonRenderedPlaceholder(Frame& frame, const URL& url)
632 return adoptRef(*new Document(&frame, url, DefaultDocumentClass, NonRenderedPlaceholder));
635 Document::~Document()
637 ASSERT(activeDOMObjectsAreStopped());
640 m_logger->removeObserver(*this);
642 #if ENABLE(INTERSECTION_OBSERVER)
643 if (m_intersectionObserverData) {
644 for (const auto& observer : m_intersectionObserverData->observers) {
646 observer->rootDestroyed();
648 m_intersectionObserverData->observers.clear();
649 // Document cannot be a target.
650 ASSERT(m_intersectionObserverData->registrations.isEmpty());
654 ASSERT(allDocumentsMap().contains(m_identifier));
655 allDocumentsMap().remove(m_identifier);
656 // We need to remove from the contexts map very early in the destructor so that calling postTask() on this Document from another thread is safe.
657 removeFromContextsMap();
659 ASSERT(!renderView());
660 ASSERT(m_backForwardCacheState != InBackForwardCache);
661 ASSERT(m_ranges.isEmpty());
662 ASSERT(!m_parentTreeScope);
663 ASSERT(!m_disabledFieldsetElementsCount);
664 ASSERT(m_inDocumentShadowRoots.isEmpty());
666 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
667 m_deviceMotionClient->deviceMotionControllerDestroyed();
668 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
671 if (m_templateDocument)
672 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
674 // FIXME: Should we reset m_domWindow when we detach from the Frame?
676 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
678 m_scriptRunner = nullptr;
679 m_moduleLoader = nullptr;
681 removeAllEventListeners();
683 // Currently we believe that Document can never outlive the parser.
684 // Although the Document may be replaced synchronously, DocumentParsers
685 // generally keep at least one reference to an Element which would in turn
686 // has a reference to the Document. If you hit this ASSERT, then that
687 // assumption is wrong. DocumentParser::detach() should ensure that even
688 // if the DocumentParser outlives the Document it won't cause badness.
689 ASSERT(!m_parser || m_parser->refCount() == 1);
692 if (this == &topDocument())
693 clearAXObjectCache();
697 if (m_styleSheetList)
698 m_styleSheetList->detach();
700 extensionStyleSheets().detachFromDocument();
702 styleScope().clearResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
703 m_fontSelector->clearDocument();
704 m_fontSelector->unregisterForInvalidationCallbacks(*this);
706 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
707 // load the initial empty document and the SVGDocument with the same DocumentLoader).
708 if (m_cachedResourceLoader->document() == this)
709 m_cachedResourceLoader->setDocument(nullptr);
712 stopAllMediaPlayback();
715 // We must call clearRareData() here since a Document class inherits TreeScope
716 // as well as Node. See a comment on TreeScope.h for the reason.
720 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_listsInvalidatedAtDocument.isEmpty());
721 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_collectionsInvalidatedAtDocument.isEmpty());
722 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(m_svgUseElements.isEmpty());
724 for (unsigned count : m_nodeListAndCollectionCounts)
725 ASSERT_UNUSED(count, !count);
728 void Document::removedLastRef()
730 ASSERT(!m_deletionHasBegun);
731 if (m_referencingNodeCount) {
732 // Node::removedLastRef doesn't set refCount() to zero because it's not observable.
733 // But we need to remember that our refCount reached zero in subsequent calls to decrementReferencingNodeCount().
734 m_refCountAndParentBit = 0;
736 // If removing a child removes the last node reference, we don't want the scope to be destroyed
737 // until after removeDetachedChildren returns, so we protect ourselves.
738 incrementReferencingNodeCount();
740 RELEASE_ASSERT(!hasLivingRenderTree());
741 // We must make sure not to be retaining any of our children through
742 // these extra pointers or we will create a reference cycle.
743 m_focusedElement = nullptr;
744 m_hoveredElement = nullptr;
745 m_activeElement = nullptr;
746 m_titleElement = nullptr;
747 m_documentElement = nullptr;
748 m_focusNavigationStartingNode = nullptr;
749 m_userActionElements.clear();
750 #if ENABLE(FULLSCREEN_API)
751 m_fullscreenManager->clear();
753 m_associatedFormControls.clear();
755 m_fontSelector->clearDocument();
756 m_fontSelector->unregisterForInvalidationCallbacks(*this);
760 // removeDetachedChildren() doesn't always unregister IDs,
761 // so tear down scope information up front to avoid having
762 // stale references in the map.
764 destroyTreeScopeData();
765 removeDetachedChildren();
766 m_formController = nullptr;
770 m_cssCanvasElements.clear();
775 // We need to do this right now since selfOnlyDeref() can delete this.
776 m_inRemovedLastRefFunction = false;
778 decrementReferencingNodeCount();
782 m_inRemovedLastRefFunction = false;
783 m_deletionHasBegun = true;
789 void Document::commonTeardown()
791 stopActiveDOMObjects();
793 #if ENABLE(FULLSCREEN_API)
794 m_fullscreenManager->emptyEventQueue();
798 accessSVGExtensions().pauseAnimations();
800 clearScriptedAnimationController();
803 m_highlightMap->clear();
805 m_pendingScrollEventTargetList = nullptr;
807 if (m_timelinesController)
808 m_timelinesController->detachFromDocument();
810 m_timeline = nullptr;
813 Element* Document::elementForAccessKey(const String& key)
817 if (!m_accessKeyCache)
818 buildAccessKeyCache();
819 return m_accessKeyCache->get(key);
822 void Document::buildAccessKeyCache()
824 m_accessKeyCache = makeUnique<HashMap<String, Element*, ASCIICaseInsensitiveHash>>([this] {
825 HashMap<String, Element*, ASCIICaseInsensitiveHash> map;
826 for (auto& node : composedTreeDescendants(*this)) {
827 if (!is<Element>(node))
829 auto& element = downcast<Element>(node);
830 auto& key = element.attributeWithoutSynchronization(accesskeyAttr);
833 map.add(key, &element);
839 void Document::invalidateAccessKeyCacheSlowCase()
841 m_accessKeyCache = nullptr;
844 ExceptionOr<SelectorQuery&> Document::selectorQueryForString(const String& selectorString)
846 if (selectorString.isEmpty())
847 return Exception { SyntaxError };
848 if (!m_selectorQueryCache)
849 m_selectorQueryCache = makeUnique<SelectorQueryCache>();
850 return m_selectorQueryCache->add(selectorString, *this);
853 void Document::clearSelectorQueryCache()
855 m_selectorQueryCache = nullptr;
858 void Document::setReferrerPolicy(ReferrerPolicy referrerPolicy)
860 // Do not override existing referrer policy with the "empty string" one as the "empty string" means we should use
861 // the policy defined elsewhere.
862 if (m_referrerPolicy && referrerPolicy == ReferrerPolicy::EmptyString)
865 m_referrerPolicy = referrerPolicy;
868 MediaQueryMatcher& Document::mediaQueryMatcher()
870 if (!m_mediaQueryMatcher)
871 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
872 return *m_mediaQueryMatcher;
875 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
877 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
879 bool wasInQuirksMode = inQuirksMode();
880 m_compatibilityMode = mode;
882 clearSelectorQueryCache();
884 if (inQuirksMode() != wasInQuirksMode) {
885 // All user stylesheets have to reparse using the different mode.
886 extensionStyleSheets().clearPageUserSheet();
887 extensionStyleSheets().invalidateInjectedStyleSheetCache();
891 String Document::compatMode() const
893 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
896 void Document::resetLinkColor()
898 m_linkColor = StyleColor::colorFromKeyword(CSSValueWebkitLink, styleColorOptions(nullptr));
901 void Document::resetVisitedLinkColor()
903 m_visitedLinkColor = StyleColor::colorFromKeyword(CSSValueWebkitLink, styleColorOptions(nullptr) | StyleColor::Options::ForVisitedLink);
906 void Document::resetActiveLinkColor()
908 m_activeLinkColor = StyleColor::colorFromKeyword(CSSValueWebkitActivelink, styleColorOptions(nullptr));
911 DOMImplementation& Document::implementation()
913 if (!m_implementation)
914 m_implementation = makeUnique<DOMImplementation>(*this);
915 return *m_implementation;
918 bool Document::hasManifest() const
920 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttributeWithoutSynchronization(manifestAttr);
923 DocumentType* Document::doctype() const
925 for (Node* node = firstChild(); node; node = node->nextSibling()) {
926 if (is<DocumentType>(node))
927 return downcast<DocumentType>(node);
932 void Document::childrenChanged(const ChildChange& change)
934 ContainerNode::childrenChanged(change);
936 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
937 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
938 // otherwise, we need to detect the doc type changes before updating the viewport.
939 if (Page* page = this->page())
940 page->chrome().didReceiveDocType(*frame());
942 Element* newDocumentElement = childrenOfType<Element>(*this).first();
943 if (newDocumentElement == m_documentElement)
945 m_documentElement = newDocumentElement;
946 // The root style used for media query matching depends on the document element.
947 styleScope().clearResolver();
950 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const QualifiedName& name)
952 if (!RuntimeEnabledFeatures::sharedFeatures().customElementsEnabled()
953 || Document::validateCustomElementName(name.localName()) != CustomElementNameValidationStatus::Valid)
954 return HTMLUnknownElement::create(name, document);
956 auto element = HTMLElement::create(name, document);
957 element->setIsCustomElementUpgradeCandidate();
961 static ALWAYS_INLINE Ref<HTMLElement> createUpgradeCandidateElement(Document& document, const AtomString& localName)
963 return createUpgradeCandidateElement(document, QualifiedName { nullAtom(), localName, xhtmlNamespaceURI });
966 static inline bool isValidHTMLElementName(const AtomString& localName)
968 return Document::isValidName(localName);
971 static inline bool isValidHTMLElementName(const QualifiedName& name)
973 return Document::isValidName(name.localName());
976 template<typename NameType>
977 static ExceptionOr<Ref<Element>> createHTMLElementWithNameValidation(Document& document, const NameType& name)
979 auto element = HTMLElementFactory::createKnownElement(name, document);
981 return Ref<Element> { element.releaseNonNull() };
983 if (auto* window = document.domWindow()) {
984 auto* registry = window->customElementRegistry();
985 if (UNLIKELY(registry)) {
986 if (auto* elementInterface = registry->findInterface(name))
987 return elementInterface->constructElementWithFallback(document, name);
991 if (UNLIKELY(!isValidHTMLElementName(name)))
992 return Exception { InvalidCharacterError };
994 return Ref<Element> { createUpgradeCandidateElement(document, name) };
997 ExceptionOr<Ref<Element>> Document::createElementForBindings(const AtomString& name)
999 if (isHTMLDocument())
1000 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase());
1002 if (isXHTMLDocument())
1003 return createHTMLElementWithNameValidation(*this, name);
1005 if (!isValidName(name))
1006 return Exception { InvalidCharacterError };
1008 return createElement(QualifiedName(nullAtom(), name, nullAtom()), false);
1011 Ref<DocumentFragment> Document::createDocumentFragment()
1013 return DocumentFragment::create(document());
1016 Ref<Text> Document::createTextNode(const String& data)
1018 return Text::create(*this, data);
1021 Ref<Comment> Document::createComment(const String& data)
1023 return Comment::create(*this, data);
1026 ExceptionOr<Ref<CDATASection>> Document::createCDATASection(const String& data)
1028 if (isHTMLDocument())
1029 return Exception { NotSupportedError };
1031 if (data.contains("]]>"))
1032 return Exception { InvalidCharacterError };
1034 return CDATASection::create(*this, data);
1037 ExceptionOr<Ref<ProcessingInstruction>> Document::createProcessingInstruction(const String& target, const String& data)
1039 if (!isValidName(target))
1040 return Exception { InvalidCharacterError };
1042 if (data.contains("?>"))
1043 return Exception { InvalidCharacterError };
1045 return ProcessingInstruction::create(*this, target, data);
1048 Ref<Text> Document::createEditingTextNode(const String& text)
1050 return Text::createEditingText(*this, text);
1053 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
1055 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
1056 return propertySet->ensureCSSStyleDeclaration();
1059 ExceptionOr<Ref<Node>> Document::importNode(Node& nodeToImport, bool deep)
1061 switch (nodeToImport.nodeType()) {
1062 case DOCUMENT_FRAGMENT_NODE:
1063 if (nodeToImport.isShadowRoot())
1068 case CDATA_SECTION_NODE:
1069 case PROCESSING_INSTRUCTION_NODE:
1071 return nodeToImport.cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
1073 case ATTRIBUTE_NODE: {
1074 auto& attribute = downcast<Attr>(nodeToImport);
1075 return Ref<Node> { Attr::create(*this, attribute.qualifiedName(), attribute.value()) };
1077 case DOCUMENT_NODE: // Can't import a document into another document.
1078 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
1082 return Exception { NotSupportedError };
1086 ExceptionOr<Ref<Node>> Document::adoptNode(Node& source)
1088 EventQueueScope scope;
1090 switch (source.nodeType()) {
1092 return Exception { NotSupportedError };
1093 case ATTRIBUTE_NODE: {
1094 auto& attr = downcast<Attr>(source);
1095 if (auto* element = attr.ownerElement()) {
1096 auto result = element->removeAttributeNode(attr);
1097 if (result.hasException())
1098 return result.releaseException();
1103 if (source.isShadowRoot()) {
1104 // ShadowRoot cannot disconnect itself from the host node.
1105 return Exception { HierarchyRequestError };
1107 if (is<HTMLFrameOwnerElement>(source)) {
1108 auto& frameOwnerElement = downcast<HTMLFrameOwnerElement>(source);
1109 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame()))
1110 return Exception { HierarchyRequestError };
1112 auto result = source.remove();
1113 if (result.hasException())
1114 return result.releaseException();
1115 RELEASE_ASSERT(!source.isConnected());
1116 RELEASE_ASSERT(!source.parentNode());
1119 source.setTreeScopeRecursively(*this);
1121 return Ref<Node> { source };
1124 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1126 // These checks are from DOM Core Level 2, createElementNS
1127 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1128 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1130 if (qName.prefix() == xmlAtom() && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1133 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1134 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1135 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1136 if (qName.prefix() == xmlnsAtom() || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom()))
1137 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1138 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1141 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1143 return hasValidNamespaceForElements(qName);
1146 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1148 if (auto* window = document.domWindow()) {
1149 auto* registry = window->customElementRegistry();
1150 if (UNLIKELY(registry)) {
1151 if (auto* elementInterface = registry->findInterface(name)) {
1152 auto element = HTMLElement::create(name, document);
1153 element->enqueueToUpgrade(*elementInterface);
1158 // FIXME: Should we also check the equality of prefix between the custom element and name?
1159 return createUpgradeCandidateElement(document, name);
1162 // FIXME: This should really be in a possible ElementFactory class.
1163 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1165 RefPtr<Element> element;
1167 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1168 if (name.namespaceURI() == xhtmlNamespaceURI) {
1169 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1170 if (UNLIKELY(!element))
1171 element = createFallbackHTMLElement(*this, name);
1172 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1173 element = SVGElementFactory::createElement(name, *this, createdByParser);
1175 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1176 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1180 m_sawElementsInKnownNamespaces = true;
1182 element = Element::create(name, document());
1184 // <image> uses imgTag so we need a special rule.
1185 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1187 return element.releaseNonNull();
1190 // https://html.spec.whatwg.org/#valid-custom-element-name
1192 struct UnicodeCodePointRange {
1199 static inline bool operator<(const UnicodeCodePointRange& a, const UnicodeCodePointRange& b)
1201 ASSERT(a.minimum <= a.maximum);
1202 ASSERT(b.minimum <= b.maximum);
1203 return a.maximum < b.minimum;
1206 #endif // ASSERT_ENABLED
1208 static inline bool operator<(const UnicodeCodePointRange& a, UChar32 b)
1210 ASSERT(a.minimum <= a.maximum);
1211 return a.maximum < b;
1214 static inline bool operator<(UChar32 a, const UnicodeCodePointRange& b)
1216 ASSERT(b.minimum <= b.maximum);
1217 return a < b.minimum;
1220 static inline bool isPotentialCustomElementNameCharacter(UChar32 character)
1222 static const UnicodeCodePointRange ranges[] = {
1239 { 0x10000, 0xEFFFF },
1242 ASSERT(std::is_sorted(std::begin(ranges), std::end(ranges)));
1243 return std::binary_search(std::begin(ranges), std::end(ranges), character);
1246 CustomElementNameValidationStatus Document::validateCustomElementName(const AtomString& localName)
1248 if (!isASCIILower(localName[0]))
1249 return CustomElementNameValidationStatus::FirstCharacterIsNotLowercaseASCIILetter;
1251 bool containsHyphen = false;
1252 for (auto character : StringView(localName).codePoints()) {
1253 if (isASCIIUpper(character))
1254 return CustomElementNameValidationStatus::ContainsUppercaseASCIILetter;
1255 if (!isPotentialCustomElementNameCharacter(character))
1256 return CustomElementNameValidationStatus::ContainsDisallowedCharacter;
1257 if (character == '-')
1258 containsHyphen = true;
1261 if (!containsHyphen)
1262 return CustomElementNameValidationStatus::ContainsNoHyphen;
1265 const auto& annotationXmlLocalName = MathMLNames::annotation_xmlTag->localName();
1267 static MainThreadNeverDestroyed<const AtomString> annotationXmlLocalName("annotation-xml", AtomString::ConstructFromLiteral);
1270 if (localName == SVGNames::color_profileTag->localName()
1271 || localName == SVGNames::font_faceTag->localName()
1272 || localName == SVGNames::font_face_formatTag->localName()
1273 || localName == SVGNames::font_face_nameTag->localName()
1274 || localName == SVGNames::font_face_srcTag->localName()
1275 || localName == SVGNames::font_face_uriTag->localName()
1276 || localName == SVGNames::missing_glyphTag->localName()
1277 || localName == annotationXmlLocalName)
1278 return CustomElementNameValidationStatus::ConflictsWithStandardElementName;
1280 return CustomElementNameValidationStatus::Valid;
1283 ExceptionOr<Ref<Element>> Document::createElementNS(const AtomString& namespaceURI, const String& qualifiedName)
1285 auto parseResult = parseQualifiedName(namespaceURI, qualifiedName);
1286 if (parseResult.hasException())
1287 return parseResult.releaseException();
1288 QualifiedName parsedName { parseResult.releaseReturnValue() };
1289 if (!hasValidNamespaceForElements(parsedName))
1290 return Exception { NamespaceError };
1292 if (parsedName.namespaceURI() == xhtmlNamespaceURI)
1293 return createHTMLElementWithNameValidation(*this, parsedName);
1295 return createElement(parsedName, false);
1298 void Document::setReadyState(ReadyState readyState)
1300 if (readyState == m_readyState)
1303 switch (readyState) {
1305 if (!m_documentTiming.domLoading)
1306 m_documentTiming.domLoading = MonotonicTime::now();
1309 if (!m_documentTiming.domInteractive)
1310 m_documentTiming.domInteractive = MonotonicTime::now();
1313 if (!m_documentTiming.domComplete)
1314 m_documentTiming.domComplete = MonotonicTime::now();
1318 m_readyState = readyState;
1319 dispatchEvent(Event::create(eventNames().readystatechangeEvent, Event::CanBubble::No, Event::IsCancelable::No));
1321 if (settings().suppressesIncrementalRendering())
1322 setVisualUpdatesAllowed(readyState);
1325 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1327 ASSERT(settings().suppressesIncrementalRendering());
1328 switch (readyState) {
1330 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1331 ASSERT(m_visualUpdatesAllowed);
1332 setVisualUpdatesAllowed(false);
1335 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1338 if (m_visualUpdatesSuppressionTimer.isActive()) {
1339 ASSERT(!m_visualUpdatesAllowed);
1341 if (view() && !view()->visualUpdatesAllowedByClient())
1344 setVisualUpdatesAllowed(true);
1346 ASSERT(m_visualUpdatesAllowed);
1351 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1353 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1356 m_visualUpdatesAllowed = visualUpdatesAllowed;
1358 if (visualUpdatesAllowed)
1359 m_visualUpdatesSuppressionTimer.stop();
1361 m_visualUpdatesSuppressionTimer.startOneShot(1_s * settings().incrementalRenderingSuppressionTimeoutInSeconds());
1363 if (!visualUpdatesAllowed)
1366 RefPtr<FrameView> frameView = view();
1367 bool needsLayout = frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout());
1371 if (Page* page = this->page()) {
1372 if (frame()->isMainFrame()) {
1373 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1374 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1375 frame()->loader().didReachLayoutMilestone(DidFirstLayoutAfterSuppressedIncrementalRendering);
1380 frameView->updateCompositingLayersAfterLayout();
1382 if (RenderView* renderView = this->renderView())
1383 renderView->repaintViewAndCompositedLayers();
1385 if (Frame* frame = this->frame())
1386 frame->loader().completePageTransitionIfNeeded();
1389 void Document::visualUpdatesSuppressionTimerFired()
1391 ASSERT(!m_visualUpdatesAllowed);
1393 // If the client is extending the visual update suppression period explicitly, the
1394 // watchdog should not re-enable visual updates itself, but should wait for the client.
1395 if (view() && !view()->visualUpdatesAllowedByClient())
1398 setVisualUpdatesAllowed(true);
1401 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1403 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1404 // both of which we can determine by looking at the timer.
1406 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1407 setVisualUpdatesAllowed(true);
1410 String Document::characterSetWithUTF8Fallback() const
1412 AtomString name = encoding();
1415 return UTF8Encoding().domName();
1418 String Document::defaultCharsetForLegacyBindings() const
1421 UTF8Encoding().domName();
1422 return settings().defaultTextEncodingName();
1425 void Document::setCharset(const String& charset)
1429 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1432 void Document::setContentLanguage(const String& language)
1434 if (m_contentLanguage == language)
1436 m_contentLanguage = language;
1438 // Recalculate style so language is used when selecting the initial font.
1439 m_styleScope->didChangeStyleSheetEnvironment();
1442 ExceptionOr<void> Document::setXMLVersion(const String& version)
1444 if (!XMLDocumentParser::supportsXMLVersion(version))
1445 return Exception { NotSupportedError };
1447 m_xmlVersion = version;
1451 void Document::setXMLStandalone(bool standalone)
1453 m_xmlStandalone = standalone ? StandaloneStatus::Standalone : StandaloneStatus::NotStandalone;
1456 void Document::setDocumentURI(const String& uri)
1458 // This property is read-only from JavaScript, but writable from Objective-C.
1459 m_documentURI = uri;
1463 void Document::setContent(const String& content)
1466 // FIXME: This should probably use insert(), but that's (intentionally)
1467 // not implemented for the XML parser as it's normally synonymous with
1468 // document.write(). append() will end up yielding, but close() will
1469 // pump the tokenizer syncrhonously and finish the parse.
1470 m_parser->append(content.impl());
1474 String Document::suggestedMIMEType() const
1476 if (isXHTMLDocument())
1477 return "application/xhtml+xml"_s;
1478 if (isSVGDocument())
1479 return "image/svg+xml"_s;
1480 if (xmlStandalone())
1481 return "text/xml"_s;
1482 if (isHTMLDocument())
1483 return "text/html"_s;
1484 if (DocumentLoader* loader = this->loader())
1485 return loader->responseMIMEType();
1489 void Document::overrideMIMEType(const String& mimeType)
1491 m_overriddenMIMEType = mimeType;
1494 String Document::contentType() const
1496 if (!m_overriddenMIMEType.isNull())
1497 return m_overriddenMIMEType;
1499 if (DocumentLoader* documentLoader = loader())
1500 return documentLoader->currentContentType();
1502 String mimeType = suggestedMIMEType();
1503 if (!mimeType.isNull())
1506 return "application/xml"_s;
1509 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1511 auto boundary = caretPositionFromPoint(LayoutPoint(x, y));
1514 return createLiveRange({ *boundary, *boundary });
1517 Optional<BoundaryPoint> Document::caretPositionFromPoint(const LayoutPoint& clientPoint)
1519 if (!hasLivingRenderTree())
1520 return WTF::nullopt;
1522 LayoutPoint localPoint;
1523 auto node = nodeFromPoint(clientPoint, &localPoint);
1525 return WTF::nullopt;
1527 auto* renderer = node->renderer();
1529 return WTF::nullopt;
1530 auto rangeCompliantPosition = renderer->positionForPoint(localPoint).parentAnchoredEquivalent();
1531 if (rangeCompliantPosition.isNull())
1532 return WTF::nullopt;
1534 unsigned offset = rangeCompliantPosition.offsetInContainerNode();
1535 node = retargetToScope(*rangeCompliantPosition.containerNode());
1536 if (node != rangeCompliantPosition.containerNode())
1539 return { { *node, offset } };
1542 bool Document::isBodyPotentiallyScrollable(HTMLBodyElement& body)
1544 // See https://www.w3.org/TR/cssom-view-1/#potentially-scrollable.
1545 // An element is potentially scrollable if all of the following conditions are true:
1546 // - The element has an associated CSS layout box.
1547 // - The element is not the HTML body element, or it is and the root element's used value of the
1548 // overflow-x or overflow-y properties is not visible.
1549 // - The element's used value of the overflow-x or overflow-y properties is not visible.
1551 // FIXME: We should use RenderObject::hasOverflowClip() instead of Element::computedStyle() but
1552 // the used values are currently not correctly updated. See https://webkit.org/b/182292.
1553 return body.renderer()
1554 && documentElement()->computedStyle()
1555 && !documentElement()->computedStyle()->isOverflowVisible()
1556 && body.computedStyle()
1557 && !body.computedStyle()->isOverflowVisible();
1560 Element* Document::scrollingElementForAPI()
1562 if (inQuirksMode() && settings().CSSOMViewScrollingAPIEnabled())
1563 updateLayoutIgnorePendingStylesheets();
1564 return scrollingElement();
1567 Element* Document::scrollingElement()
1569 if (settings().CSSOMViewScrollingAPIEnabled()) {
1570 // See https://drafts.csswg.org/cssom-view/#dom-document-scrollingelement.
1571 // The scrollingElement attribute, on getting, must run these steps:
1572 // 1. If the Document is in quirks mode, follow these substeps:
1573 if (inQuirksMode()) {
1574 auto* firstBody = body();
1575 // 1. If the HTML body element exists, and it is not potentially scrollable, return the
1576 // HTML body element and abort these steps.
1577 if (firstBody && !isBodyPotentiallyScrollable(*firstBody))
1580 // 2. Return null and abort these steps.
1584 // 2. If there is a root element, return the root element and abort these steps.
1586 return documentElement();
1592 static String canonicalizedTitle(Document& document, const String& title)
1594 // Collapse runs of HTML spaces into single space characters.
1595 // Strip leading and trailing spaces.
1596 // Replace backslashes with currency symbols.
1598 StringBuilder builder;
1600 auto* decoder = document.decoder();
1601 auto backslashAsCurrencySymbol = decoder ? decoder->encoding().backslashAsCurrencySymbol() : '\\';
1603 bool previousCharacterWasHTMLSpace = false;
1604 for (auto character : StringView { title }.codeUnits()) {
1605 if (isHTMLSpace(character))
1606 previousCharacterWasHTMLSpace = true;
1608 if (character == '\\')
1609 character = backslashAsCurrencySymbol;
1610 if (previousCharacterWasHTMLSpace && !builder.isEmpty())
1611 builder.append(' ');
1612 builder.append(character);
1613 previousCharacterWasHTMLSpace = false;
1617 return builder == title ? title : builder.toString();
1620 void Document::updateTitle(const StringWithDirection& title)
1622 if (m_rawTitle == title)
1627 m_title.string = canonicalizedTitle(*this, title.string);
1628 m_title.direction = title.direction;
1630 if (auto* loader = this->loader())
1631 loader->setTitle(m_title);
1634 void Document::updateTitleFromTitleElement()
1636 if (!m_titleElement) {
1641 if (is<HTMLTitleElement>(*m_titleElement))
1642 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1643 else if (is<SVGTitleElement>(*m_titleElement)) {
1644 // FIXME: Does the SVG title element have a text direction?
1645 updateTitle({ downcast<SVGTitleElement>(*m_titleElement).textContent(), TextDirection::LTR });
1649 void Document::setTitle(const String& title)
1651 auto* element = documentElement();
1652 if (is<SVGSVGElement>(element)) {
1653 if (!m_titleElement) {
1654 m_titleElement = SVGTitleElement::create(SVGNames::titleTag, *this);
1655 element->insertBefore(*m_titleElement, element->firstChild());
1657 // insertBefore above may have ran scripts which removed m_titleElement.
1659 m_titleElement->setTextContent(title);
1660 } else if (is<HTMLElement>(element)) {
1661 if (!m_titleElement) {
1662 auto* headElement = head();
1665 m_titleElement = HTMLTitleElement::create(HTMLNames::titleTag, *this);
1666 headElement->appendChild(*m_titleElement);
1668 // appendChild above may have ran scripts which removed m_titleElement.
1670 m_titleElement->setTextContent(title);
1674 template<typename> struct TitleTraits;
1676 template<> struct TitleTraits<HTMLTitleElement> {
1677 static bool isInEligibleLocation(HTMLTitleElement& element) { return element.isConnected() && !element.isInShadowTree(); }
1678 static HTMLTitleElement* findTitleElement(Document& document) { return descendantsOfType<HTMLTitleElement>(document).first(); }
1681 template<> struct TitleTraits<SVGTitleElement> {
1682 static bool isInEligibleLocation(SVGTitleElement& element) { return element.parentNode() == element.document().documentElement(); }
1683 static SVGTitleElement* findTitleElement(Document& document) { return childrenOfType<SVGTitleElement>(*document.documentElement()).first(); }
1686 template<typename TitleElement> Element* selectNewTitleElement(Document& document, Element* oldTitleElement, Element& changingTitleElement)
1688 using Traits = TitleTraits<TitleElement>;
1690 if (!is<TitleElement>(changingTitleElement)) {
1691 ASSERT(oldTitleElement == Traits::findTitleElement(document));
1692 return oldTitleElement;
1695 if (oldTitleElement)
1696 return Traits::findTitleElement(document);
1698 // Optimized common case: We have no title element yet.
1699 // We can figure out which title element should be used without searching.
1700 bool isEligible = Traits::isInEligibleLocation(downcast<TitleElement>(changingTitleElement));
1701 auto* newTitleElement = isEligible ? &changingTitleElement : nullptr;
1702 ASSERT(newTitleElement == Traits::findTitleElement(document));
1703 return newTitleElement;
1706 void Document::updateTitleElement(Element& changingTitleElement)
1708 // Most documents use HTML title rules.
1709 // Documents with SVG document elements use SVG title rules.
1710 auto selectTitleElement = is<SVGSVGElement>(documentElement())
1711 ? selectNewTitleElement<SVGTitleElement> : selectNewTitleElement<HTMLTitleElement>;
1712 auto newTitleElement = selectTitleElement(*this, m_titleElement.get(), changingTitleElement);
1713 if (m_titleElement == newTitleElement)
1715 m_titleElement = newTitleElement;
1716 updateTitleFromTitleElement();
1719 void Document::titleElementAdded(Element& titleElement)
1721 if (m_titleElement == &titleElement)
1724 updateTitleElement(titleElement);
1727 void Document::titleElementRemoved(Element& titleElement)
1729 if (m_titleElement != &titleElement)
1732 updateTitleElement(titleElement);
1735 void Document::titleElementTextChanged(Element& titleElement)
1737 if (m_titleElement != &titleElement)
1740 updateTitleFromTitleElement();
1743 void Document::registerForVisibilityStateChangedCallbacks(VisibilityChangeClient& client)
1745 m_visibilityStateCallbackClients.add(&client);
1748 void Document::unregisterForVisibilityStateChangedCallbacks(VisibilityChangeClient& client)
1750 m_visibilityStateCallbackClients.remove(&client);
1753 void Document::visibilityStateChanged()
1755 // https://w3c.github.io/page-visibility/#reacting-to-visibilitychange-changes
1756 queueTaskToDispatchEvent(TaskSource::UserInteraction, Event::create(eventNames().visibilitychangeEvent, Event::CanBubble::Yes, Event::IsCancelable::No));
1757 for (auto* client : m_visibilityStateCallbackClients)
1758 client->visibilityStateChanged();
1760 #if ENABLE(MEDIA_STREAM) && PLATFORM(IOS_FAMILY)
1761 if (auto mediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists()) {
1762 if (!mediaSessionManager->isInterrupted())
1763 MediaStreamTrack::updateCaptureAccordingToMutedState(*this);
1768 VisibilityState Document::visibilityState() const
1770 // The visibility of the document is inherited from the visibility of the
1771 // page. If there is no page associated with the document, we will assume
1772 // that the page is hidden, as specified by the spec:
1773 // https://w3c.github.io/page-visibility/#visibilitystate-attribute
1774 if (!m_frame || !m_frame->page())
1775 return VisibilityState::Hidden;
1776 return m_frame->page()->visibilityState();
1779 bool Document::hidden() const
1781 return visibilityState() != VisibilityState::Visible;
1786 void Document::registerMediaElement(HTMLMediaElement& element)
1788 m_mediaElements.add(&element);
1791 void Document::unregisterMediaElement(HTMLMediaElement& element)
1793 m_mediaElements.remove(&element);
1796 void Document::forEachMediaElement(const Function<void(HTMLMediaElement&)>& function)
1798 Vector<Ref<HTMLMediaElement>> elements;
1799 for (auto* element : m_mediaElements)
1800 elements.append(*element);
1801 for (auto& element : elements)
1805 void Document::stopAllMediaPlayback()
1807 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1808 platformMediaSessionManager->stopAllMediaPlaybackForDocument(identifier());
1811 void Document::suspendAllMediaPlayback()
1813 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1814 platformMediaSessionManager->suspendAllMediaPlaybackForDocument(identifier());
1817 void Document::resumeAllMediaPlayback()
1819 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1820 platformMediaSessionManager->resumeAllMediaPlaybackForDocument(identifier());
1823 void Document::suspendAllMediaBuffering()
1825 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1826 platformMediaSessionManager->suspendAllMediaBufferingForDocument(identifier());
1829 void Document::resumeAllMediaBuffering()
1831 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
1832 platformMediaSessionManager->resumeAllMediaBufferingForDocument(identifier());
1837 String Document::nodeName() const
1839 return "#document"_s;
1842 Node::NodeType Document::nodeType() const
1844 return DOCUMENT_NODE;
1847 FormController& Document::formController()
1849 if (!m_formController)
1850 m_formController = makeUnique<FormController>();
1851 return *m_formController;
1854 Vector<String> Document::formElementsState() const
1856 if (!m_formController)
1857 return Vector<String>();
1858 return m_formController->formElementsState();
1861 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1863 if (!stateVector.size() && !m_formController)
1865 formController().setStateForNewFormElements(stateVector);
1868 FrameView* Document::view() const
1870 return m_frame ? m_frame->view() : nullptr;
1873 Page* Document::page() const
1875 return m_frame ? m_frame->page() : nullptr;
1878 Ref<Range> Document::createRange()
1880 return Range::create(*this);
1883 Ref<NodeIterator> Document::createNodeIterator(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1885 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1888 Ref<TreeWalker> Document::createTreeWalker(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1890 return TreeWalker::create(root, whatToShow, WTFMove(filter));
1893 void Document::scheduleFullStyleRebuild()
1895 m_needsFullStyleRebuild = true;
1896 scheduleStyleRecalc();
1899 void Document::scheduleStyleRecalc()
1901 ASSERT(!m_renderView || !inHitTesting());
1903 if (m_styleRecalcTimer.isActive() || backForwardCacheState() != NotInBackForwardCache)
1906 ASSERT(childNeedsStyleRecalc() || m_needsFullStyleRebuild);
1908 m_styleRecalcTimer.startOneShot(0_s);
1910 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1913 void Document::unscheduleStyleRecalc()
1915 ASSERT(!childNeedsStyleRecalc());
1917 m_styleRecalcTimer.stop();
1918 m_needsFullStyleRebuild = false;
1921 bool Document::hasPendingStyleRecalc() const
1923 return needsStyleRecalc() && !m_inStyleRecalc;
1926 bool Document::hasPendingFullStyleRebuild() const
1928 return hasPendingStyleRecalc() && m_needsFullStyleRebuild;
1931 void Document::updateRenderTree(std::unique_ptr<const Style::Update> styleUpdate)
1933 ASSERT(!inRenderTreeUpdate());
1935 Style::PostResolutionCallbackDisabler callbackDisabler(*this);
1937 SetForScope<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1939 RenderTreeUpdater updater(*this, callbackDisabler);
1940 updater.commit(WTFMove(styleUpdate));
1945 void Document::resolveStyle(ResolveStyleType type)
1947 ASSERT(!view() || !view()->isPainting());
1949 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1953 FrameView& frameView = m_renderView->frameView();
1954 Ref<FrameView> protect(frameView);
1955 if (frameView.isPainting())
1958 if (m_inStyleRecalc)
1959 return; // Guard against re-entrancy. -dwh
1961 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1963 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1964 AnimationUpdateBlock animationUpdateBlock(&m_frame->legacyAnimation());
1966 // FIXME: Do this update per tree scope.
1968 auto elements = copyToVectorOf<RefPtr<SVGUseElement>>(m_svgUseElements);
1969 // We can't clear m_svgUseElements here because updateShadowTree may end up executing arbitrary scripts
1970 // which may insert new SVG use elements or remove existing ones inside sync IPC via ImageLoader::updateFromElement.
1971 for (auto& element : elements)
1972 element->updateShadowTree();
1975 // FIXME: We should update style on our ancestor chain before proceeding, however doing so at
1976 // the time this comment was originally written caused several tests to crash.
1979 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
1980 styleScope().flushPendingUpdate();
1981 frameView.willRecalcStyle();
1984 InspectorInstrumentation::willRecalculateStyle(*this);
1986 bool updatedCompositingLayers = false;
1988 Style::PostResolutionCallbackDisabler disabler(*this);
1989 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1990 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
1992 m_inStyleRecalc = true;
1994 if (m_needsFullStyleRebuild)
1995 type = ResolveStyleType::Rebuild;
1997 if (type == ResolveStyleType::Rebuild) {
1998 // This may get set again during style resolve.
1999 m_hasNodesWithNonFinalStyle = false;
2000 m_hasNodesWithMissingStyle = false;
2002 auto documentStyle = Style::resolveForDocument(*this);
2004 // Inserting the pictograph font at the end of the font fallback list is done by the
2005 // font selector, so set a font selector if needed.
2006 if (settings().fontFallbackPrefersPictographs())
2007 documentStyle.fontCascade().update(&fontSelector());
2009 auto documentChange = Style::determineChange(documentStyle, m_renderView->style());
2010 if (documentChange != Style::NoChange)
2011 renderView()->setStyle(WTFMove(documentStyle));
2013 if (auto* documentElement = this->documentElement())
2014 documentElement->invalidateStyleForSubtree();
2017 Style::TreeResolver resolver(*this);
2018 auto styleUpdate = resolver.resolve();
2020 m_lastStyleUpdateSizeForTesting = styleUpdate ? styleUpdate->size() : 0;
2023 clearChildNeedsStyleRecalc();
2024 unscheduleStyleRecalc();
2026 m_inStyleRecalc = false;
2029 updateRenderTree(WTFMove(styleUpdate));
2030 frameView.styleAndRenderTreeDidChange();
2033 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
2035 if (m_renderView->needsLayout())
2036 frameView.layoutContext().scheduleLayout();
2038 // Usually this is handled by post-layout.
2039 if (!frameView.needsLayout())
2040 frameView.frame().selection().scheduleAppearanceUpdateAfterStyleChange();
2042 // As a result of the style recalculation, the currently hovered element might have been
2043 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
2044 // to check if any other elements ended up under the mouse pointer due to re-layout.
2045 if (m_hoveredElement && !m_hoveredElement->renderer())
2046 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
2048 ++m_styleRecalcCount;
2049 // FIXME: Assert ASSERT(!needsStyleRecalc()) here. Do we still have some cases where it's not true?
2052 InspectorInstrumentation::didRecalculateStyle(*this);
2054 // Some animated images may now be inside the viewport due to style recalc,
2055 // resume them if necessary if there is no layout pending. Otherwise, we'll
2056 // check if they need to be resumed after layout.
2057 if (updatedCompositingLayers && !frameView.needsLayout())
2058 frameView.viewportContentsChanged();
2061 void Document::updateTextRenderer(Text& text, unsigned offsetOfReplacedText, unsigned lengthOfReplacedText)
2063 auto textUpdate = makeUnique<Style::Update>(*this);
2064 textUpdate->addText(text, { offsetOfReplacedText, lengthOfReplacedText, WTF::nullopt });
2066 updateRenderTree(WTFMove(textUpdate));
2069 bool Document::needsStyleRecalc() const
2071 if (backForwardCacheState() != NotInBackForwardCache)
2074 if (m_needsFullStyleRebuild)
2077 if (childNeedsStyleRecalc())
2080 if (styleScope().hasPendingUpdate())
2086 static bool isSafeToUpdateStyleOrLayout(const Document& document)
2088 bool isSafeToExecuteScript = ScriptDisallowedScope::InMainThread::isScriptAllowed();
2089 auto* frameView = document.view();
2090 bool isInFrameFlattening = frameView && frameView->isInChildFrameWithFrameFlattening();
2091 return isSafeToExecuteScript || isInFrameFlattening || !isInWebProcess();
2094 bool Document::updateStyleIfNeeded()
2096 RefPtr<FrameView> frameView = view();
2098 ScriptDisallowedScope::InMainThread scriptDisallowedScope;
2099 ASSERT(isMainThread());
2100 ASSERT(!frameView || !frameView->isPainting());
2102 if (!frameView || frameView->layoutContext().isInRenderTreeLayout())
2105 styleScope().flushPendingUpdate();
2107 if (!needsStyleRecalc())
2111 #if PLATFORM(IOS_FAMILY)
2112 ContentChangeObserver::StyleRecalcScope observingScope(*this);
2114 // The early exit above for !needsStyleRecalc() is needed when updateWidgetPositions() is called in runOrScheduleAsynchronousTasks().
2115 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isSafeToUpdateStyleOrLayout(*this));
2120 void Document::updateLayout()
2122 ASSERT(isMainThread());
2124 RefPtr<FrameView> frameView = view();
2125 if (frameView && frameView->layoutContext().isInRenderTreeLayout()) {
2126 // View layout should not be re-entrant.
2127 ASSERT_NOT_REACHED();
2130 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isSafeToUpdateStyleOrLayout(*this));
2132 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2134 if (HTMLFrameOwnerElement* owner = ownerElement())
2135 owner->document().updateLayout();
2137 updateStyleIfNeeded();
2139 StackStats::LayoutCheckPoint layoutCheckPoint;
2141 // Only do a layout if changes have occurred that make it necessary.
2142 if (frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout()))
2143 frameView->layoutContext().layout();
2146 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
2148 bool oldIgnore = m_ignorePendingStylesheets;
2150 if (!haveStylesheetsLoaded()) {
2151 m_ignorePendingStylesheets = true;
2152 // FIXME: This should just invalidate elements with missing styles.
2153 if (m_hasNodesWithMissingStyle)
2154 scheduleFullStyleRebuild();
2159 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
2160 view()->flushAnyPendingPostLayoutTasks();
2162 m_ignorePendingStylesheets = oldIgnore;
2165 std::unique_ptr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, const RenderStyle* parentStyle, PseudoId pseudoElementSpecifier)
2167 ASSERT(&element.document() == this);
2168 ASSERT(!element.isPseudoElement() || pseudoElementSpecifier == PseudoId::None);
2169 ASSERT(pseudoElementSpecifier == PseudoId::None || parentStyle);
2171 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
2172 Style::PostResolutionCallbackDisabler disabler(*this, Style::PostResolutionCallbackDisabler::DrainCallbacks::No);
2174 SetForScope<bool> change(m_ignorePendingStylesheets, true);
2175 auto& resolver = element.styleResolver();
2177 if (pseudoElementSpecifier != PseudoId::None)
2178 return resolver.pseudoStyleForElement(element, { pseudoElementSpecifier }, *parentStyle);
2180 auto elementStyle = resolver.styleForElement(element, parentStyle);
2181 if (elementStyle.relations) {
2182 Style::Update emptyUpdate(*this);
2183 Style::commitRelations(WTFMove(elementStyle.relations), emptyUpdate);
2186 return WTFMove(elementStyle.renderStyle);
2189 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
2191 ASSERT(isMainThread());
2193 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
2194 if (!haveStylesheetsLoaded()) {
2195 updateLayoutIgnorePendingStylesheets();
2199 // Check for re-entrancy and assert (same code that is in updateLayout()).
2200 RefPtr<FrameView> frameView = view();
2201 if (frameView && frameView->layoutContext().isInRenderTreeLayout()) {
2202 // View layout should not be re-entrant.
2203 ASSERT_NOT_REACHED();
2207 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
2209 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
2211 bool requireFullLayout = false;
2212 if (HTMLFrameOwnerElement* owner = ownerElement()) {
2213 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
2214 requireFullLayout = true;
2217 updateStyleIfNeeded();
2219 RenderObject* renderer = element.renderer();
2220 if (!renderer || renderer->needsLayout()) {
2221 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2222 requireFullLayout = true;
2225 // Turn off this optimization for input elements with shadow content.
2226 if (is<HTMLInputElement>(element))
2227 requireFullLayout = true;
2229 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2230 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2231 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2232 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2234 if (!requireFullLayout) {
2235 RenderBox* previousBox = nullptr;
2236 RenderBox* currentBox = nullptr;
2238 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2239 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2241 // Require the entire container chain to be boxes.
2242 if (!is<RenderBox>(currRenderer)) {
2243 requireFullLayout = true;
2247 previousBox = currentBox;
2248 currentBox = downcast<RenderBox>(currRenderer);
2250 // If a box needs layout for itself or if a box has changed children and sizes its width to
2251 // its content, then require a full layout.
2252 if (currentBox->selfNeedsLayout() ||
2253 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2254 requireFullLayout = true;
2258 // If a block contains floats and the child's height isn't specified, then
2259 // give up also, since our height could end up being influenced by the floats.
2260 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2261 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2262 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2263 requireFullLayout = true;
2268 if (!currentBox->isRenderBlockFlow() || currentBox->enclosingFragmentedFlow() || currentBox->isWritingModeRoot()) {
2269 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2270 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2271 // Disallow columns from having the optimization.
2272 // Give up if the writing mode changes at all in the containing block chain.
2273 requireFullLayout = true;
2277 if (currRenderer == frameView->layoutContext().subtreeLayoutRoot())
2282 StackStats::LayoutCheckPoint layoutCheckPoint;
2284 // Only do a layout if changes have occurred that make it necessary.
2285 if (requireFullLayout && frameView && renderView() && (frameView->layoutContext().isLayoutPending() || renderView()->needsLayout()))
2286 frameView->layoutContext().layout();
2288 return requireFullLayout;
2291 bool Document::isPageBoxVisible(int pageIndex)
2293 updateStyleIfNeeded();
2294 std::unique_ptr<RenderStyle> pageStyle(styleScope().resolver().styleForPage(pageIndex));
2295 return pageStyle->visibility() != Visibility::Hidden; // display property doesn't apply to @page.
2298 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2300 updateStyleIfNeeded();
2301 auto style = styleScope().resolver().styleForPage(pageIndex);
2303 int width = pageSize.width();
2304 int height = pageSize.height();
2305 switch (style->pageSizeType()) {
2306 case PAGE_SIZE_AUTO:
2308 case PAGE_SIZE_AUTO_LANDSCAPE:
2310 std::swap(width, height);
2312 case PAGE_SIZE_AUTO_PORTRAIT:
2314 std::swap(width, height);
2316 case PAGE_SIZE_RESOLVED: {
2317 auto& size = style->pageSize();
2318 ASSERT(size.width.isFixed());
2319 ASSERT(size.height.isFixed());
2320 width = valueForLength(size.width, 0);
2321 height = valueForLength(size.height, 0);
2325 ASSERT_NOT_REACHED();
2327 pageSize = IntSize(width, height);
2329 // The percentage is calculated with respect to the width even for margin top and bottom.
2330 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2331 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2332 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2333 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2334 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2337 Style::Resolver& Document::userAgentShadowTreeStyleResolver()
2339 if (!m_userAgentShadowTreeStyleResolver)
2340 m_userAgentShadowTreeStyleResolver = makeUnique<Style::Resolver>(*this);
2341 return *m_userAgentShadowTreeStyleResolver;
2344 void Document::fontsNeedUpdate(FontSelector&)
2346 invalidateMatchedPropertiesCacheAndForceStyleRecalc();
2349 void Document::invalidateMatchedPropertiesCacheAndForceStyleRecalc()
2351 styleScope().invalidateMatchedDeclarationsCache();
2353 if (backForwardCacheState() != NotInBackForwardCache || !renderView())
2355 scheduleFullStyleRebuild();
2358 void Document::didClearStyleResolver()
2360 m_userAgentShadowTreeStyleResolver = nullptr;
2363 void Document::setIsResolvingTreeStyle(bool value)
2365 RELEASE_ASSERT(value != m_isResolvingTreeStyle);
2366 m_isResolvingTreeStyle = value;
2369 void Document::createRenderTree()
2371 ASSERT(!renderView());
2372 ASSERT(m_backForwardCacheState != InBackForwardCache);
2373 ASSERT(!m_axObjectCache || this != &topDocument());
2375 if (m_isNonRenderedPlaceholder)
2378 // FIXME: It would be better if we could pass the resolved document style directly here.
2379 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2380 Node::setRenderer(m_renderView.get());
2382 renderView()->setIsInWindow(true);
2384 resolveStyle(ResolveStyleType::Rebuild);
2387 void Document::didBecomeCurrentDocumentInFrame()
2389 m_frame->script().updateDocument();
2391 // Many of these functions have event handlers which can detach the frame synchronously, so we must check repeatedly in this function.
2395 if (!hasLivingRenderTree())
2400 dispatchDisabledAdaptationsDidChangeForMainFrame();
2404 updateViewportArguments();
2408 // FIXME: Doing this only for the main frame is insufficient.
2409 // Changing a subframe can also change the wheel event handler count.
2410 // FIXME: Doing this only when a document goes into the frame is insufficient.
2411 // Removing a document can also change the wheel event handler count.
2412 // FIXME: Doing this every time is a waste. If the current document and its
2413 // subframes' documents have no wheel event handlers, then the count did not change,
2414 // unless the documents they are replacing had wheel event handlers.
2415 if (page() && m_frame->isMainFrame())
2416 wheelEventHandlersChanged();
2420 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2421 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2422 // back/forward cache, or simply newly created).
2423 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2424 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
2425 if (m_timelinesController)
2426 m_timelinesController->suspendAnimations();
2428 m_frame->legacyAnimation().suspendAnimationsForDocument(this);
2429 suspendScheduledTasks(ReasonForSuspension::PageWillBeSuspended);
2431 resumeScheduledTasks(ReasonForSuspension::PageWillBeSuspended);
2432 if (RuntimeEnabledFeatures::sharedFeatures().webAnimationsCSSIntegrationEnabled()) {
2433 if (m_timelinesController)
2434 m_timelinesController->resumeAnimations();
2436 m_frame->legacyAnimation().resumeAnimationsForDocument(this);
2440 void Document::frameDestroyed()
2442 // detachFromFrame() must be called before destroying the Frame.
2443 RELEASE_ASSERT(!m_frame);
2445 if (auto* window = domWindow())
2446 window->frameDestroyed();
2448 FrameDestructionObserver::frameDestroyed();
2451 void Document::willDetachPage()
2453 FrameDestructionObserver::willDetachPage();
2454 #if PLATFORM(IOS_FAMILY)
2455 contentChangeObserver().willDetachPage();
2457 if (domWindow() && frame())
2458 InspectorInstrumentation::frameWindowDiscarded(*frame(), domWindow());
2461 void Document::attachToCachedFrame(CachedFrameBase& cachedFrame)
2463 RELEASE_ASSERT(cachedFrame.document() == this);
2464 ASSERT(cachedFrame.view());
2465 ASSERT(m_backForwardCacheState == Document::InBackForwardCache);
2466 observeFrame(&cachedFrame.view()->frame());
2469 void Document::detachFromCachedFrame(CachedFrameBase& cachedFrame)
2471 ASSERT_UNUSED(cachedFrame, cachedFrame.view());
2472 RELEASE_ASSERT(cachedFrame.document() == this);
2473 ASSERT(m_frame == &cachedFrame.view()->frame());
2474 ASSERT(m_backForwardCacheState == Document::InBackForwardCache);
2478 void Document::destroyRenderTree()
2480 ASSERT(hasLivingRenderTree());
2482 ASSERT(frame()->document() == this);
2485 // Prevent Widget tree changes from committing until the RenderView is dead and gone.
2486 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
2488 SetForScope<bool> change(m_renderTreeBeingDestroyed, true);
2490 if (this == &topDocument())
2491 clearAXObjectCache();
2493 documentWillBecomeInactive();
2496 view()->willDestroyRenderTree();
2498 if (m_documentElement)
2499 RenderTreeUpdater::tearDownRenderers(*m_documentElement);
2501 clearChildNeedsStyleRecalc();
2503 unscheduleStyleRecalc();
2505 // FIXME: RenderObject::view() uses m_renderView and we can't null it before destruction is completed
2507 RenderTreeBuilder builder(*m_renderView);
2508 // FIXME: This is a workaround for leftover content (see webkit.org/b/182547).
2509 while (m_renderView->firstChild())
2510 builder.destroy(*m_renderView->firstChild());
2511 m_renderView->destroy();
2513 m_renderView.release();
2515 Node::setRenderer(nullptr);
2517 #if ENABLE(TEXT_AUTOSIZING)
2518 m_textAutoSizing = nullptr;
2522 view()->didDestroyRenderTree();
2525 void Document::willBeRemovedFromFrame()
2527 if (m_hasPreparedForDestruction)
2531 m_frame->legacyAnimation().detachFromDocument(this);
2534 // FIXME: This should be moved to Modules/mediastream.
2535 if (LibWebRTCProvider::webRTCAvailable()) {
2536 if (auto* page = this->page())
2537 page->libWebRTCProvider().unregisterMDNSNames(identifier());
2541 #if ENABLE(SERVICE_WORKER)
2542 setActiveServiceWorker(nullptr);
2543 setServiceWorkerConnection(nullptr);
2546 #if ENABLE(IOS_TOUCH_EVENTS)
2547 clearTouchEventHandlersAndListeners();
2550 m_undoManager->removeAllItems();
2552 m_textManipulationController = nullptr; // Free nodes kept alive by TextManipulationController.
2554 #if ENABLE(ACCESSIBILITY)
2555 if (this != &topDocument()) {
2556 // Let the ax cache know that this subframe goes out of scope.
2557 if (auto* cache = existingAXObjectCache())
2558 cache->prepareForDocumentDestruction(*this);
2563 NavigationDisabler navigationDisabler(m_frame);
2564 disconnectDescendantFrames();
2566 RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(!m_frame || !m_frame->tree().childCount());
2568 if (m_domWindow && m_frame)
2569 m_domWindow->willDetachDocumentFromFrame();
2571 styleScope().clearResolver();
2573 if (hasLivingRenderTree())
2574 destroyRenderTree();
2576 if (is<PluginDocument>(*this))
2577 downcast<PluginDocument>(*this).detachFromPluginElement();
2579 #if ENABLE(POINTER_LOCK)
2581 page()->pointerLockController().documentDetached(*this);
2584 if (auto* page = this->page()) {
2585 if (auto* validationMessageClient = page->validationMessageClient())
2586 validationMessageClient->documentDetached(*this);
2589 InspectorInstrumentation::documentDetached(*this);
2593 #if ENABLE(TOUCH_EVENTS)
2594 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2595 parentDocument()->didRemoveEventTargetNode(*this);
2598 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2599 parentDocument()->didRemoveEventTargetNode(*this);
2601 if (m_mediaQueryMatcher)
2602 m_mediaQueryMatcher->documentDestroyed();
2604 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2605 if (!m_clientToIDMap.isEmpty() && page()) {
2606 for (auto* client : copyToVector(m_clientToIDMap.keys()))
2607 removePlaybackTargetPickerClient(*client);
2611 m_cachedResourceLoader->stopUnusedPreloadsTimer();
2613 if (page() && m_mediaState != MediaProducer::IsNotPlaying) {
2614 m_mediaState = MediaProducer::IsNotPlaying;
2615 page()->updateIsPlayingMedia(HTMLMediaElementInvalidID);
2618 selection().willBeRemovedFromFrame();
2622 #if ENABLE(CSS_PAINTING_API)
2623 for (auto& scope : m_paintWorkletGlobalScopes.values())
2624 scope->prepareForDestruction();
2625 m_paintWorkletGlobalScopes.clear();
2628 m_hasPreparedForDestruction = true;
2630 // Note that m_backForwardCacheState can be Document::AboutToEnterBackForwardCache if our frame
2631 // was removed in an onpagehide event handler fired when the top-level frame is
2632 // about to enter the back/forward cache.
2633 RELEASE_ASSERT(m_backForwardCacheState != Document::InBackForwardCache);
2636 void Document::removeAllEventListeners()
2638 EventTarget::removeAllEventListeners();
2641 m_domWindow->removeAllEventListeners();
2643 #if ENABLE(IOS_TOUCH_EVENTS)
2644 clearTouchEventHandlersAndListeners();
2646 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2647 node->removeAllEventListeners();
2649 #if ENABLE(TOUCH_EVENTS)
2650 m_touchEventTargets = nullptr;
2652 m_wheelEventTargets = nullptr;
2655 void Document::suspendDeviceMotionAndOrientationUpdates()
2657 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2659 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2660 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
2661 if (m_deviceMotionController)
2662 m_deviceMotionController->suspendUpdates();
2663 if (m_deviceOrientationController)
2664 m_deviceOrientationController->suspendUpdates();
2668 void Document::resumeDeviceMotionAndOrientationUpdates()
2670 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2672 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2673 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS_FAMILY)
2674 if (m_deviceMotionController)
2675 m_deviceMotionController->resumeUpdates();
2676 if (m_deviceOrientationController)
2677 m_deviceOrientationController->resumeUpdates();
2681 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2683 // Bypass this policy when the world is known, and it not the normal world.
2684 JSC::VM& vm = commonVM();
2685 auto& callFrame = *vm.topCallFrame;
2686 return &callFrame != JSC::CallFrame::noCaller() && !currentWorld(*callFrame.lexicalGlobalObject(vm)).isNormal();
2689 void Document::platformSuspendOrStopActiveDOMObjects()
2691 #if PLATFORM(IOS_FAMILY)
2692 contentChangeObserver().didSuspendActiveDOMObjects();
2696 void Document::suspendActiveDOMObjects(ReasonForSuspension why)
2698 if (m_documentTaskGroup)
2699 m_documentTaskGroup->suspend();
2700 ScriptExecutionContext::suspendActiveDOMObjects(why);
2701 suspendDeviceMotionAndOrientationUpdates();
2702 platformSuspendOrStopActiveDOMObjects();
2705 void Document::resumeActiveDOMObjects(ReasonForSuspension why)
2707 if (m_documentTaskGroup)
2708 m_documentTaskGroup->resume();
2709 ScriptExecutionContext::resumeActiveDOMObjects(why);
2710 resumeDeviceMotionAndOrientationUpdates();
2711 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2714 void Document::stopActiveDOMObjects()
2716 if (m_documentTaskGroup)
2717 m_documentTaskGroup->stopAndDiscardAllTasks();
2718 ScriptExecutionContext::stopActiveDOMObjects();
2719 platformSuspendOrStopActiveDOMObjects();
2722 void Document::clearAXObjectCache()
2724 ASSERT(&topDocument() == this);
2725 // Clear the cache member variable before calling delete because attempts
2726 // are made to access it during destruction.
2727 m_axObjectCache = nullptr;
2730 AXObjectCache* Document::existingAXObjectCacheSlow() const
2732 ASSERT(hasEverCreatedAnAXObjectCache);
2733 return topDocument().m_axObjectCache.get();
2736 AXObjectCache* Document::axObjectCache() const
2738 if (!AXObjectCache::accessibilityEnabled())
2741 // The only document that actually has a AXObjectCache is the top-level
2742 // document. This is because we need to be able to get from any WebCoreAXObject
2743 // to any other WebCoreAXObject on the same page. Using a single cache allows
2744 // lookups across nested webareas (i.e. multiple documents).
2745 Document& topDocument = this->topDocument();
2747 // If the document has already been detached, do not make a new axObjectCache.
2748 if (!topDocument.hasLivingRenderTree())
2751 ASSERT(&topDocument == this || !m_axObjectCache);
2752 if (!topDocument.m_axObjectCache) {
2753 topDocument.m_axObjectCache = makeUnique<AXObjectCache>(topDocument);
2754 hasEverCreatedAnAXObjectCache = true;
2756 return topDocument.m_axObjectCache.get();
2759 void Document::setVisuallyOrdered()
2761 m_visuallyOrdered = true;
2763 renderView()->mutableStyle().setRTLOrdering(Order::Visual);
2766 Ref<DocumentParser> Document::createParser()
2768 // FIXME: this should probably pass the frame instead
2769 return XMLDocumentParser::create(*this, view());
2772 HighlightMap& Document::highlightMap()
2774 if (!m_highlightMap)
2775 m_highlightMap = HighlightMap::create();
2776 return *m_highlightMap;
2779 void Document::updateHighlightPositions()
2781 Vector<WeakPtr<HighlightRangeData>> rangesData;
2782 if (m_highlightMap) {
2783 for (auto& highlight : m_highlightMap->map()) {
2784 for (auto& rangeData : highlight.value->rangesData()) {
2785 if (rangeData->startPosition && rangeData->endPosition)
2787 if (&rangeData->range->startContainer().treeScope() != &rangeData->range->endContainer().treeScope())
2789 rangesData.append(makeWeakPtr(rangeData.ptr()));
2794 for (auto& weakRangeData : rangesData) {
2795 if (auto* rangeData = weakRangeData.get()) {
2796 VisibleSelection visibleSelection(rangeData->range);
2797 Position startPosition;
2798 Position endPosition;
2799 if (!rangeData->startPosition.hasValue())
2800 startPosition = visibleSelection.visibleStart().deepEquivalent();
2801 if (!rangeData->endPosition.hasValue())
2802 endPosition = visibleSelection.visibleEnd().deepEquivalent(); // <MMG> switch to END
2803 if (!weakRangeData.get())
2806 rangeData->startPosition = startPosition;
2807 rangeData->endPosition = endPosition;
2812 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2814 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2817 ExceptionOr<RefPtr<WindowProxy>> Document::openForBindings(DOMWindow& activeWindow, DOMWindow& firstWindow, const String& url, const AtomString& name, const String& features)
2820 return Exception { InvalidAccessError };
2822 return m_domWindow->open(activeWindow, firstWindow, url, name, features);
2825 ExceptionOr<Document&> Document::openForBindings(Document* responsibleDocument, const String&, const String&)
2827 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
2828 return Exception { InvalidStateError };
2830 auto result = open(responsibleDocument);
2831 if (UNLIKELY(result.hasException()))
2832 return result.releaseException();
2837 ExceptionOr<void> Document::open(Document* responsibleDocument)
2839 if (responsibleDocument && !responsibleDocument->securityOrigin().isSameOriginAs(securityOrigin()))
2840 return Exception { SecurityError };
2842 if (m_ignoreOpensDuringUnloadCount)
2845 if (m_activeParserWasAborted)
2849 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2850 if (parser->isParsing()) {
2851 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2852 if (parser->isExecutingScript())
2855 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2860 if (m_frame->loader().policyChecker().delegateIsDecidingNavigationPolicy())
2861 m_frame->loader().policyChecker().stopCheck();
2862 if (m_frame && m_frame->loader().state() == FrameStateProvisional)
2863 m_frame->loader().stopAllLoaders();
2866 removeAllEventListeners();
2868 if (responsibleDocument && isFullyActive()) {
2869 auto newURL = responsibleDocument->url();
2870 if (responsibleDocument != this)
2871 newURL.removeFragmentIdentifier();
2873 auto newCookieURL = responsibleDocument->cookieURL();
2874 if (responsibleDocument != this)
2875 newCookieURL.removeFragmentIdentifier();
2876 setCookieURL(newCookieURL);
2877 setSecurityOriginPolicy(responsibleDocument->securityOriginPolicy());
2881 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2882 parser->setWasCreatedByScript(true);
2885 m_frame->loader().didExplicitOpen();
2890 // https://html.spec.whatwg.org/#fully-active
2891 bool Document::isFullyActive() const
2893 auto* frame = this->frame();
2894 if (!frame || frame->document() != this)
2897 if (frame->isMainFrame())
2900 auto* parentFrame = frame->tree().parent();
2901 return parentFrame && parentFrame->document() && parentFrame->document()->isFullyActive();
2904 void Document::detachParser()
2912 void Document::cancelParsing()
2917 if (m_parser->processingData())
2918 m_activeParserWasAborted = true;
2920 // We have to clear the parser to avoid possibly triggering
2921 // the onload handler when closing as a side effect of a cancel-style
2922 // change, such as opening a new document or closing the window while
2928 void Document::implicitOpen()
2932 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2935 m_parser = createParser();
2937 if (hasActiveParserYieldToken())
2938 m_parser->didBeginYieldingParser();
2941 setReadyState(Loading);
2944 HTMLBodyElement* Document::body() const
2946 auto* element = documentElement();
2947 if (!is<HTMLHtmlElement>(element))
2949 return childrenOfType<HTMLBodyElement>(*element).first();
2952 HTMLElement* Document::bodyOrFrameset() const
2954 // Return the first body or frameset child of the html element.
2955 auto* element = documentElement();
2956 if (!is<HTMLHtmlElement>(element))
2958 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2959 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2965 ExceptionOr<void> Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody)
2967 if (!is<HTMLBodyElement>(newBody) && !is<HTMLFrameSetElement>(newBody))
2968 return Exception { HierarchyRequestError };
2970 auto* currentBody = bodyOrFrameset();
2971 if (newBody == currentBody)
2974 if (!m_documentElement)
2975 return Exception { HierarchyRequestError };
2978 return m_documentElement->replaceChild(*newBody, *currentBody);
2979 return m_documentElement->appendChild(*newBody);
2982 Location* Document::location() const
2984 auto* window = domWindow();
2985 return window ? &window->location() : nullptr;
2988 HTMLHeadElement* Document::head()
2990 if (auto element = documentElement())
2991 return childrenOfType<HTMLHeadElement>(*element).first();
2995 ExceptionOr<void> Document::closeForBindings()
2997 // FIXME: We should follow the specification more closely:
2998 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
3000 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
3001 return Exception { InvalidStateError };
3007 void Document::close()
3009 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
3015 void Document::explicitClose()
3017 if (RefPtr<DocumentParser> parser = m_parser)
3021 // Because we have no frame, we don't know if all loading has completed,
3022 // so we just call implicitClose() immediately. FIXME: This might fire
3023 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
3031 void Document::implicitClose()
3033 RELEASE_ASSERT(!m_inStyleRecalc);
3034 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
3035 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
3040 // Call to dispatchWindowLoadEvent can blow us from underneath.
3041 Ref<Document> protectedThis(*this);
3043 m_processingLoadEvent = true;
3045 ScriptableDocumentParser* parser = scriptableDocumentParser();
3046 m_wellFormed = parser && parser->wellFormed();
3048 // We have to clear the parser, in case someone document.write()s from the
3049 // onLoad event handler, as in Radar 3206524.
3052 // FIXME: We kick off the icon loader when the Document is done parsing.
3053 // There are earlier opportunities we could start it:
3054 // -When the <head> finishes parsing
3055 // -When any new HTMLLinkElement is inserted into the document
3056 // But those add a dynamic component to the favicon that has UI
3057 // ramifications, and we need to decide what is the Right Thing To Do(tm)
3058 RefPtr<Frame> f = frame();
3061 // Apply XSL transforms before load events so that event handlers can access the transformed DOM tree.
3062 applyPendingXSLTransformsNowIfScheduled();
3065 if (auto* documentLoader = loader())
3066 documentLoader->startIconLoading();
3068 f->legacyAnimation().startAnimationsIfNotSuspended(this);
3070 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
3071 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
3072 // below SVG font parsing, for example. <https://webkit.org/b/136269>
3073 if (auto* currentPage = page()) {
3074 ImageLoader::dispatchPendingBeforeLoadEvents(currentPage);
3075 ImageLoader::dispatchPendingLoadEvents(currentPage);
3076 ImageLoader::dispatchPendingErrorEvents(currentPage);
3077 HTMLLinkElement::dispatchPendingLoadEvents(currentPage);
3078 HTMLStyleElement::dispatchPendingLoadEvents(currentPage);
3081 if (svgExtensions())
3082 accessSVGExtensions().dispatchLoadEventToOutermostSVGElements();
3085 dispatchWindowLoadEvent();
3086 dispatchPageshowEvent(PageshowEventNotPersisted);
3087 if (m_pendingStateObject)
3088 dispatchPopstateEvent(WTFMove(m_pendingStateObject));
3091 f->loader().dispatchOnloadEvents();
3093 // An event handler may have removed the frame
3095 m_processingLoadEvent = false;
3099 frame()->loader().checkCallImplicitClose();
3101 // We used to force a synchronous display and flush here. This really isn't
3102 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
3103 // (if your platform is syncing flushes and limiting them to 60fps).
3104 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
3105 updateStyleIfNeeded();
3107 // Always do a layout after loading if needed.
3108 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
3109 view()->layoutContext().layout();
3112 m_processingLoadEvent = false;
3114 if (auto fontFaceSet = makeRefPtr(fontSelector().fontFaceSetIfExists()))
3115 fontFaceSet->documentDidFinishLoading();
3117 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK)
3118 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
3119 // The AX cache may have been cleared at this point, but we need to make sure it contains an
3120 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
3121 // exists in the cache (we ignore the return value because we don't need it here). This is
3122 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
3124 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
3125 // catch new AND page history loads, and that uses AXLoadComplete
3127 axObjectCache()->getOrCreate(renderView());
3128 if (this == &topDocument())
3129 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
3131 // AXLoadComplete can only be posted on the top document, so if it's a document
3132 // in an iframe that just finished loading, post AXLayoutComplete instead.
3133 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
3138 if (svgExtensions())
3139 accessSVGExtensions().startAnimations();
3142 void Document::setParsing(bool b)
3146 if (m_bParsing && !m_sharedObjectPool)
3147 m_sharedObjectPool = makeUnique<DocumentSharedObjectPool>();
3149 if (!m_bParsing && view() && !view()->needsLayout())
3150 view()->fireLayoutRelatedMilestonesIfNeeded();
3153 bool Document::shouldScheduleLayout() const
3155 if (!documentElement())
3157 if (!is<HTMLHtmlElement>(*documentElement()))
3159 if (!bodyOrFrameset())
3161 if (styleScope().hasPendingSheetsBeforeBody())
3163 if (view() && !view()->isVisuallyNonEmpty())
3168 bool Document::isLayoutTimerActive() const
3170 return view() && view()->layoutContext().isLayoutPending();
3173 bool Document::supportsPaintTiming() const
3175 return RuntimeEnabledFeatures::sharedFeatures().paintTimingEnabled() && securityOrigin().canAccess(topOrigin());
3178 // https://w3c.github.io/paint-timing/#ref-for-mark-paint-timing
3179 void Document::enqueuePaintTimingEntryIfNeeded()
3181 if (m_didEnqueueFirstContentfulPaint)
3184 if (!supportsPaintTiming())
3187 if (!domWindow() || !view())
3190 // To make sure we don't report paint while the layer tree is still frozen.
3191 if (!view()->isVisuallyNonEmpty() || view()->needsLayout())
3194 if (!ContentfulPaintChecker::qualifiesForContentfulPaint(*view()))
3197 domWindow()->performance().reportFirstContentfulPaint();
3198 m_didEnqueueFirstContentfulPaint = true;
3201 ExceptionOr<void> Document::write(Document* responsibleDocument, SegmentedString&& text)
3203 if (m_activeParserWasAborted)
3206 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
3208 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
3209 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
3211 if (m_writeRecursionIsTooDeep)
3214 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
3215 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
3218 if (!hasInsertionPoint) {
3219 auto result = open(responsibleDocument);
3220 if (UNLIKELY(result.hasException()))
3221 return result.releaseException();
3225 m_parser->insert(WTFMove(text));
3229 ExceptionOr<void> Document::write(Document* responsibleDocument, Vector<String>&& strings)
3231 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
3232 return Exception { InvalidStateError };
3234 SegmentedString text;
3235 for (auto& string : strings)
3236 text.append(WTFMove(string));
3238 return write(responsibleDocument, WTFMove(text));
3241 ExceptionOr<void> Document::writeln(Document* responsibleDocument, Vector<String>&& strings)
3243 if (!isHTMLDocument() || m_throwOnDynamicMarkupInsertionCount)
3244 return Exception { InvalidStateError };
3246 SegmentedString text;
3247 for (auto& string : strings)
3248 text.append(WTFMove(string));
3250 text.append("\n"_s);
3251 return write(responsibleDocument, WTFMove(text));
3254 Seconds Document::minimumDOMTimerInterval() const
3256 auto* page = this->page();
3258 return ScriptExecutionContext::minimumDOMTimerInterval();
3259 return page->settings().minimumDOMTimerInterval();
3262 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
3264 if (m_isTimerThrottlingEnabled == shouldThrottle)
3267 m_isTimerThrottlingEnabled = shouldThrottle;
3268 didChangeTimerAlignmentInterval();
3271 Seconds Document::domTimerAlignmentInterval(bool hasReachedMaxNestingLevel) const
3273 auto alignmentInterval = ScriptExecutionContext::domTimerAlignmentInterval(hasReachedMaxNestingLevel);
3274 if (!hasReachedMaxNestingLevel)
3275 return alignmentInterval;
3277 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
3278 if (m_isTimerThrottlingEnabled)
3279 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
3281 if (Page* page = this->page())
3282 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
3284 if (!topOrigin().canAccess(securityOrigin()) && !hasHadUserInteraction())
3285 alignmentInterval = std::max(alignmentInterval, DOMTimer::nonInteractedCrossOriginFrameAlignmentInterval());
3287 return alignmentInterval;
3290 EventTarget* Document::errorEventTarget()
3292 return m_domWindow.get();
3295 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
3297 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
3300 void Document::setURL(const URL& url)
3302 const URL& newURL = url.isEmpty() ? aboutBlankURL() : url;
3303 if (newURL == m_url)
3307 if (SecurityOrigin::shouldIgnoreHost(m_url))
3308 m_url.setHostAndPort({ });
3310 m_documentURI = m_url.string();
3314 void Document::updateBaseURL()
3316 URL oldBaseURL = m_baseURL;
3317 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
3318 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
3319 // from the Document interface otherwise.
3320 if (!m_baseElementURL.isEmpty())
3321 m_baseURL = m_baseElementURL;
3322 else if (!m_baseURLOverride.isEmpty())
3323 m_baseURL = m_baseURLOverride;
3325 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
3326 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
3327 // and DOM 3 Core does not specify how it should be resolved.
3328 m_baseURL = URL({ }, documentURI());
3331 clearSelectorQueryCache();
3333 if (!m_baseURL.isValid())
3337 void Document::setBaseURLOverride(const URL& url)
3339 m_baseURLOverride = url;
3343 void Document::processBaseElement()
3345 // Find the first href attribute in a base element and the first target attribute in a base element.
3346 const AtomString* href = nullptr;
3347 const AtomString* target = nullptr;
3348 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
3349 for (auto& base : baseDescendants) {
3351 const AtomString& value = base.attributeWithoutSynchronization(hrefAttr);
3352 if (!value.isNull()) {
3359 const AtomString& value = base.attributeWithoutSynchronization(targetAttr);
3360 if (!value.isNull()) {
3368 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
3371 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
3372 if (!strippedHref.isEmpty())
3373 baseElementURL = URL(url(), strippedHref);
3375 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
3376 if (settings().shouldRestrictBaseURLSchemes() && !SecurityPolicy::isBaseURLSchemeAllowed(baseElementURL))
3377 addConsoleMessage(MessageSource::Security, MessageLevel::Error, "Blocked setting " + baseElementURL.stringCenterEllipsizedToLength() + " as the base URL because it does not have an allowed scheme.");
3379 m_baseElementURL = baseElementURL;
3384 m_baseTarget = target ? *target : nullAtom();
3387 String Document::userAgent(const URL& url) const
3389 return frame() ? frame()->loader().userAgent(url) : String();
3392 void Document::disableEval(const String& errorMessage)
3397 frame()->script().disableEval(errorMessage);
3400 void Document::disableWebAssembly(const String& errorMessage)
3405 frame()->script().disableWebAssembly(errorMessage);
3408 #if ENABLE(INDEXED_DATABASE)
3409 IDBClient::IDBConnectionProxy* Document::idbConnectionProxy()
3411 if (!m_idbConnectionProxy) {
3412 Page* currentPage = page();
3415 m_idbConnectionProxy = ¤tPage->idbConnection().proxy();
3417 return m_idbConnectionProxy.get();
3421 SocketProvider* Document::socketProvider()
3423 return m_socketProvider.get();
3426 bool Document::canNavigate(Frame* targetFrame, const URL& destinationURL)
3431 // FIXME: We shouldn't call this function without a target frame, but
3432 // fast/forms/submit-to-blank-multiple-times.html depends on this function
3433 // returning true when supplied with a 0 targetFrame.
3437 if (!canNavigateInternal(*targetFrame))
3440 if (isNavigationBlockedByThirdPartyIFrameRedirectBlocking(*targetFrame, destinationURL)) {
3441 printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation of the top-level window is cross-origin or untrusted and the user has never interacted with the frame."_s);
3442 RELEASE_LOG_ERROR_IF_ALLOWED(Loading, "Navigation was prevented because it was triggered by a cross-origin or untrusted iframe");
3449 bool Document::canNavigateInternal(Frame& targetFrame)
3453 // Cases (i), (ii) and (iii) pass the tests from the specifications but might not pass the "security origin" tests.
3455 // i. A frame can navigate its top ancestor when its 'allow-top-navigation' flag is set (sometimes known as 'frame-busting').
3456 if (!isSandboxed(SandboxTopNavigation) && &targetFrame == &m_frame->tree().top())
3459 // ii. A frame can navigate its top ancestor when its 'allow-top-navigation-by-user-activation' flag is set and navigation is triggered by user activation.
3460 if (!isSandboxed(SandboxTopNavigationByUserActivation) && UserGestureIndicator::processingUserGesture() && &targetFrame == &m_frame->tree().top())
3463 // iii. A sandboxed frame can always navigate its descendants.
3464 if (isSandboxed(SandboxNavigation) && targetFrame.tree().isDescendantOf(m_frame))
3467 // From https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate.
3468 // 1. If A is not the same browsing context as B, and A is not one of the ancestor browsing contexts of B, and B is not a top-level browsing context, and A's active document's active sandboxing
3469 // flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.
3470 if (m_frame != &targetFrame && isSandboxed(SandboxNavigation) && targetFrame.tree().parent() && !targetFrame.tree().isDescendantOf(m_frame)) {
3471 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors."_s);
3475 // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
3476 if (m_frame != &targetFrame && &targetFrame == &m_frame->tree().top()) {
3477 bool triggeredByUserActivation = UserGestureIndicator::processingUserGesture();
3478 // 1. If this algorithm is triggered by user activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set, then abort these steps negatively.
3479 if (triggeredByUserActivation && isSandboxed(SandboxTopNavigationByUserActivation)) {
3480 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation-by-user-activation' flag is not set and navigation is not triggered by user activation."_s);
3483 // 2. Otherwise, If this algorithm is not triggered by user activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set, then abort these steps negatively.
3484 if (!triggeredByUserActivation && isSandboxed(SandboxTopNavigation)) {
3485 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set."_s);
3490 // 3. Otherwise, if B is a top-level browsing context, and is neither A nor one of the ancestor browsing contexts of A, and A's Document's active sandboxing flag set has its
3491 // sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.
3492 if (!targetFrame.tree().parent() && m_frame != &targetFrame && &targetFrame != &m_frame->tree().top() && isSandboxed(SandboxNavigation) && targetFrame.loader().opener() != m_frame) {
3493 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is sandboxed, and is not allowed to navigate this popup."_s);
3497 // 4. Otherwise, terminate positively!
3499 // This is the normal case. A document can navigate its descendant frames,
3500 // or, more generally, a document can navigate a frame if the document is
3501 // in the same origin as any of that frame's ancestors (in the frame
3504 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3505 // historical information about this security check.
3506 if (canAccessAncestor(securityOrigin(), &targetFrame))
3509 // Top-level frames are easier to navigate than other frames because they
3510 // display their URLs in the address bar (in most browsers). However, there
3511 // are still some restrictions on navigation to avoid nuisance attacks.
3512 // Specifically, a document can navigate a top-level frame if that frame
3513 // opened the document or if the document is the same-origin with any of
3514 // the top-level frame's opener's ancestors (in the frame hierarchy).
3516 // In both of these cases, the document performing the navigation is in
3517 // some way related to the frame being navigate (e.g., by the "opener"
3518 // and/or "parent" relation). Requiring some sort of relation prevents a
3519 // document from navigating arbitrary, unrelated top-level frames.
3520 if (!targetFrame.tree().parent()) {
3521 if (&targetFrame == m_frame->loader().opener())
3524 if (canAccessAncestor(securityOrigin(), targetFrame.loader().opener()))
3528 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3532 void Document::willLoadScriptElement(const URL& scriptURL)
3534 m_hasLoadedThirdPartyScript = m_hasLoadedThirdPartyScript || !securityOrigin().isSameOriginAs(SecurityOrigin::create(scriptURL));
3537 void Document::willLoadFrameElement(const URL& frameURL)
3539 m_hasLoadedThirdPartyFrame = m_hasLoadedThirdPartyFrame || !securityOrigin().isSameOriginAs(SecurityOrigin::create(frameURL));
3542 // Prevent cross-site top-level redirects from third-party iframes unless the user has ever interacted with the frame.
3543 bool Document::isNavigationBlockedByThirdPartyIFrameRedirectBlocking(Frame& targetFrame, const URL& destinationURL)
3545 if (!settings().thirdPartyIframeRedirectBlockingEnabled())
3548 // Only prevent top frame navigations by subframes.
3549 if (m_frame == &targetFrame || &targetFrame != &m_frame->tree().top())
3552 // Only prevent navigations by subframes that the user has not interacted with.
3553 if (m_frame->hasHadUserInteraction())
3556 // Only prevent navigations by unsandboxed iframes. Such navigations by unsandboxed iframes would have already been blocked unless
3557 // "allow-top-navigation" / "allow-top-navigation-by-user-activation" was explicitly specified.
3558 if (sandboxFlags() != SandboxNone)
3561 // Only prevent navigations by third-party iframes or untrusted first-party iframes.
3562 bool isUntrustedIframe = m_hasLoadedThirdPartyScript && m_hasLoadedThirdPartyFrame;
3563 if (canAccessAncestor(securityOrigin(), &targetFrame) && !isUntrustedIframe)
3566 // Only prevent cross-site navigations.
3567 auto* targetDocument = targetFrame.document();
3568 if (targetDocument && (targetDocument->securityOrigin().canAccess(SecurityOrigin::create(destinationURL)) || areRegistrableDomainsEqual(targetDocument->url(), destinationURL)))
3574 void Document::didRemoveAllPendingStylesheet()
3576 if (auto* parser = scriptableDocumentParser())
3577 parser->executeScriptsWaitingForStylesheetsSoon();
3579 if (m_gotoAnchorNeededAfterStylesheetsLoad) {
3580 // https://html.spec.whatwg.org/multipage/browsing-the-web.html#try-to-scroll-to-the-fragment
3581 eventLoop().queueTask(TaskSource::Networking, [protectedThis = makeRef(*this), this] {
3582 auto frameView = makeRefPtr(view());
3585 if (!haveStylesheetsLoaded()) {
3586 m_gotoAnchorNeededAfterStylesheetsLoad = true;
3589 frameView->scrollToFragment(m_url);
3594 bool Document::usesStyleBasedEditability() const
3596 if (m_hasElementUsingStyleBasedEditability)
3599 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3600 ASSERT(!m_inStyleRecalc);
3602 auto& styleScope = const_cast<Style::Scope&>(this->styleScope());
3603 styleScope.flushPendingUpdate();
3604 return styleScope.usesStyleBasedEditability();
3607 void Document::setHasElementUsingStyleBasedEditability()
3609 m_hasElementUsingStyleBasedEditability = true;
3612 void Document::processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead)
3614 ASSERT(!equiv.isNull());
3615 ASSERT(!content.isNull());
3617 HttpEquivPolicy policy = httpEquivPolicy();
3618 if (policy != HttpEquivPolicy::Enabled) {
3621 case HttpEquivPolicy::Enabled:
3622 ASSERT_NOT_REACHED();
3624 case HttpEquivPolicy::DisabledBySettings:
3625 reason = "by the embedder.";
3627 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3628 reason = "for documents with Content-Disposition: attachment.";
3631 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3632 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3636 Frame* frame = this->frame();
3637 auto* documentLoader = frame ? frame->loader().documentLoader() : nullptr;
3638 auto httpStatusCode = documentLoader ? documentLoader->response().httpStatusCode() : 0;
3640 HTTPHeaderName headerName;
3641 if (!findHTTPHeaderName(equiv, headerName))