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-2016 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"
32 #include "AnimationController.h"
34 #include "CDATASection.h"
35 #include "CSSFontSelector.h"
36 #include "CSSStyleDeclaration.h"
37 #include "CSSStyleSheet.h"
38 #include "CachedCSSStyleSheet.h"
39 #include "CachedResourceLoader.h"
41 #include "ChromeClient.h"
43 #include "CompositionEvent.h"
44 #include "ContentSecurityPolicy.h"
45 #include "CookieJar.h"
46 #include "CustomElementReactionQueue.h"
47 #include "CustomElementRegistry.h"
48 #include "CustomEvent.h"
49 #include "DOMImplementation.h"
50 #include "DOMNamedFlowCollection.h"
51 #include "DOMWindow.h"
52 #include "DateComponents.h"
53 #include "DebugPageOverlays.h"
54 #include "Dictionary.h"
55 #include "DocumentLoader.h"
56 #include "DocumentMarkerController.h"
57 #include "DocumentSharedObjectPool.h"
58 #include "DocumentType.h"
60 #include "ElementIterator.h"
61 #include "EventHandler.h"
62 #include "ExtensionStyleSheets.h"
63 #include "FocusController.h"
64 #include "FontFaceSet.h"
65 #include "FormController.h"
66 #include "FrameLoader.h"
67 #include "FrameLoaderClient.h"
68 #include "FrameView.h"
69 #include "GenericCachedHTMLCollection.h"
70 #include "HTMLAllCollection.h"
71 #include "HTMLAnchorElement.h"
72 #include "HTMLBaseElement.h"
73 #include "HTMLBodyElement.h"
74 #include "HTMLCanvasElement.h"
75 #include "HTMLDocument.h"
76 #include "HTMLElementFactory.h"
77 #include "HTMLFormControlElement.h"
78 #include "HTMLFrameOwnerElement.h"
79 #include "HTMLFrameSetElement.h"
80 #include "HTMLHeadElement.h"
81 #include "HTMLHtmlElement.h"
82 #include "HTMLImageElement.h"
83 #include "HTMLInputElement.h"
84 #include "HTMLLinkElement.h"
85 #include "HTMLMediaElement.h"
86 #include "HTMLNameCollection.h"
87 #include "HTMLParserIdioms.h"
88 #include "HTMLPictureElement.h"
89 #include "HTMLPlugInElement.h"
90 #include "HTMLScriptElement.h"
91 #include "HTMLStyleElement.h"
92 #include "HTMLTitleElement.h"
93 #include "HTMLUnknownElement.h"
94 #include "HTTPHeaderNames.h"
95 #include "HTTPParsers.h"
96 #include "HashChangeEvent.h"
98 #include "HitTestResult.h"
99 #include "IconController.h"
100 #include "ImageLoader.h"
101 #include "InspectorInstrumentation.h"
102 #include "JSCustomElementInterface.h"
103 #include "JSLazyEventListener.h"
104 #include "KeyboardEvent.h"
105 #include "Language.h"
106 #include "LoaderStrategy.h"
108 #include "MainFrame.h"
109 #include "MediaCanStartListener.h"
110 #include "MediaProducer.h"
111 #include "MediaQueryList.h"
112 #include "MediaQueryMatcher.h"
113 #include "MessageEvent.h"
114 #include "MouseEventWithHitTestResults.h"
115 #include "MutationEvent.h"
116 #include "NameNodeList.h"
117 #include "NestingLevelIncrementer.h"
118 #include "NoEventDispatchAssertion.h"
119 #include "NodeIterator.h"
120 #include "NodeRareData.h"
121 #include "NodeWithIndex.h"
122 #include "OriginAccessEntry.h"
123 #include "OverflowEvent.h"
124 #include "PageConsoleClient.h"
125 #include "PageGroup.h"
126 #include "PageTransitionEvent.h"
127 #include "PlatformLocale.h"
128 #include "PlatformMediaSessionManager.h"
129 #include "PlatformScreen.h"
130 #include "PlatformStrategies.h"
131 #include "PlugInsResources.h"
132 #include "PluginDocument.h"
133 #include "PointerLockController.h"
134 #include "PopStateEvent.h"
135 #include "ProcessingInstruction.h"
136 #include "RenderChildIterator.h"
137 #include "RenderLayerCompositor.h"
138 #include "RenderTreeUpdater.h"
139 #include "RenderView.h"
140 #include "RenderWidget.h"
141 #include "ResourceLoadObserver.h"
142 #include "RuntimeEnabledFeatures.h"
143 #include "SVGDocumentExtensions.h"
144 #include "SVGElement.h"
145 #include "SVGElementFactory.h"
146 #include "SVGNames.h"
147 #include "SVGSVGElement.h"
148 #include "SVGTitleElement.h"
149 #include "SVGZoomEvent.h"
150 #include "SchemeRegistry.h"
151 #include "ScopedEventQueue.h"
152 #include "ScriptController.h"
153 #include "ScriptModuleLoader.h"
154 #include "ScriptRunner.h"
155 #include "ScriptSourceCode.h"
156 #include "ScrollingCoordinator.h"
157 #include "SecurityOrigin.h"
158 #include "SecurityOriginPolicy.h"
159 #include "SecurityPolicy.h"
160 #include "SegmentedString.h"
161 #include "SelectorQuery.h"
162 #include "Settings.h"
163 #include "ShadowRoot.h"
164 #include "SocketProvider.h"
165 #include "StorageEvent.h"
166 #include "StyleProperties.h"
167 #include "StyleResolveForDocument.h"
168 #include "StyleResolver.h"
169 #include "StyleScope.h"
170 #include "StyleSheetContents.h"
171 #include "StyleSheetList.h"
172 #include "StyleTreeResolver.h"
173 #include "SubresourceLoader.h"
174 #include "TextAutoSizing.h"
175 #include "TextEvent.h"
176 #include "TextNodeTraversal.h"
177 #include "TransformSource.h"
178 #include "TreeWalker.h"
179 #include "VisitedLinkState.h"
180 #include "WheelEvent.h"
181 #include "WindowFeatures.h"
182 #include "XMLDocument.h"
183 #include "XMLDocumentParser.h"
184 #include "XMLNSNames.h"
185 #include "XMLNames.h"
186 #include "XPathEvaluator.h"
187 #include "XPathExpression.h"
188 #include "XPathNSResolver.h"
189 #include "XPathResult.h"
190 #include "htmlediting.h"
192 #include <inspector/ScriptCallStack.h>
193 #include <wtf/CurrentTime.h>
194 #include <wtf/NeverDestroyed.h>
195 #include <wtf/SystemTracing.h>
196 #include <wtf/TemporaryChange.h>
197 #include <wtf/text/StringBuffer.h>
198 #include <yarr/RegularExpression.h>
200 #if ENABLE(DEVICE_ORIENTATION)
201 #include "DeviceMotionEvent.h"
202 #include "DeviceOrientationEvent.h"
205 #if ENABLE(FULLSCREEN_API)
206 #include "RenderFullScreen.h"
209 #if ENABLE(INDEXED_DATABASE)
210 #include "IDBConnectionProxy.h"
211 #include "IDBOpenDBRequest.h"
215 #include "CSSFontSelector.h"
216 #include "DeviceMotionClientIOS.h"
217 #include "DeviceMotionController.h"
218 #include "DeviceOrientationClientIOS.h"
219 #include "DeviceOrientationController.h"
220 #include "Geolocation.h"
221 #include "Navigator.h"
222 #include "NavigatorGeolocation.h"
223 #include "WKContentObservation.h"
224 #include "WebCoreSystemInterface.h"
227 #if ENABLE(IOS_GESTURE_EVENTS)
228 #include "GestureEvent.h"
232 #include "MathMLElement.h"
233 #include "MathMLElementFactory.h"
234 #include "MathMLNames.h"
237 #if ENABLE(MEDIA_SESSION)
238 #include "MediaSession.h"
241 #if ENABLE(REQUEST_ANIMATION_FRAME)
242 #include "RequestAnimationFrameCallback.h"
243 #include "ScriptedAnimationController.h"
246 #if ENABLE(TOUCH_EVENTS)
247 #include "TouchEvent.h"
248 #include "TouchList.h"
251 #if ENABLE(VIDEO_TRACK)
252 #include "CaptionUserPreferences.h"
255 #if ENABLE(WEB_REPLAY)
256 #include "WebReplayInputs.h"
257 #include <replay/EmptyInputCursor.h>
258 #include <replay/InputCursor.h>
261 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
262 #include "MediaPlaybackTargetClient.h"
266 #include "XSLTProcessor.h"
270 using namespace Unicode;
274 using namespace HTMLNames;
276 static const unsigned cMaxWriteRecursionDepth = 21;
278 // DOM Level 2 says (letters added):
280 // a) Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.
281 // b) Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.
282 // c) Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.
283 // 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.
284 // 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.
285 // f) Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).
286 // g) Character #x00B7 is classified as an extender, because the property list so identifies it.
287 // h) Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.
288 // i) Characters ':' and '_' are allowed as name-start characters.
289 // j) Characters '-' and '.' are allowed as name characters.
291 // It also contains complete tables. If we decide it's better, we could include those instead of the following code.
293 static inline bool isValidNameStart(UChar32 c)
296 if ((c >= 0x02BB && c <= 0x02C1) || c == 0x559 || c == 0x6E5 || c == 0x6E6)
300 if (c == ':' || c == '_')
303 // rules (a) and (f) above
304 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)))
308 if (c >= 0xF900 && c < 0xFFFE)
312 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
313 if (type == U_DT_FONT || type == U_DT_COMPAT)
319 static inline bool isValidNamePart(UChar32 c)
321 // rules (a), (e), and (i) above
322 if (isValidNameStart(c))
325 // rules (g) and (h) above
326 if (c == 0x00B7 || c == 0x0387)
330 if (c == '-' || c == '.')
333 // rules (b) and (f) above
334 if (!(U_GET_GC_MASK(c) & (U_GC_M_MASK | U_GC_LM_MASK | U_GC_ND_MASK)))
338 if (c >= 0xF900 && c < 0xFFFE)
342 int type = u_getIntPropertyValue(c, UCHAR_DECOMPOSITION_TYPE);
343 if (type == U_DT_FONT || type == U_DT_COMPAT)
349 static Widget* widgetForElement(Element* focusedElement)
353 auto* renderer = focusedElement->renderer();
354 if (!is<RenderWidget>(renderer))
356 return downcast<RenderWidget>(*renderer).widget();
359 static bool acceptsEditingFocus(Node* node)
362 ASSERT(node->hasEditableStyle());
364 Node* root = node->rootEditableElement();
365 Frame* frame = node->document().frame();
369 return frame->editor().shouldBeginEditing(rangeOfContents(*root).ptr());
372 static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
374 // targetFrame can be 0 when we're trying to navigate a top-level frame
375 // that has a 0 opener.
379 const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
380 for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
381 Document* ancestorDocument = ancestorFrame->document();
382 // FIXME: Should be an ASSERT? Frames should alway have documents.
383 if (!ancestorDocument)
386 const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
387 if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
390 // Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
391 // FIXME: It's a bit strange to special-case local origins here. Should we be doing
392 // something more general instead?
393 if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal())
400 static void printNavigationErrorMessage(Frame* frame, const URL& activeURL, const char* reason)
402 String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
404 // FIXME: should we print to the console of the document performing the navigation instead?
405 frame->document()->domWindow()->printErrorMessage(message);
408 #if ENABLE(TEXT_AUTOSIZING)
410 void TextAutoSizingTraits::constructDeletedValue(TextAutoSizingKey& slot)
412 new (NotNull, &slot) TextAutoSizingKey(TextAutoSizingKey::Deleted);
415 bool TextAutoSizingTraits::isDeletedValue(const TextAutoSizingKey& value)
417 return value.isDeleted();
422 uint64_t Document::s_globalTreeVersion = 0;
424 HashSet<Document*>& Document::allDocuments()
426 static NeverDestroyed<HashSet<Document*>> documents;
430 Document::Document(Frame* frame, const URL& url, unsigned documentClasses, unsigned constructionFlags)
431 : ContainerNode(*this, CreateDocument)
433 #if ENABLE(IOS_TOUCH_EVENTS)
434 , m_touchEventsChangedTimer(*this, &Document::touchEventsChangedTimerFired)
436 , m_referencingNodeCount(0)
437 , m_hasNodesWithPlaceholderStyle(false)
438 , m_needsNotifyRemoveAllPendingStylesheet(false)
439 , m_ignorePendingStylesheets(false)
440 , m_pendingSheetLayout(NoLayoutWithPendingSheets)
442 , m_cachedResourceLoader(m_frame ? Ref<CachedResourceLoader>(m_frame->loader().activeDocumentLoader()->cachedResourceLoader()) : CachedResourceLoader::create(nullptr))
443 , m_activeParserCount(0)
444 , m_wellFormed(false)
446 , m_paginatedForScreen(false)
447 , m_compatibilityMode(DocumentCompatibilityMode::NoQuirksMode)
448 , m_compatibilityModeLocked(false)
449 , m_textColor(Color::black)
450 , m_domTreeVersion(++s_globalTreeVersion)
452 , m_mutationObserverTypes(0)
453 , m_styleScope(std::make_unique<Style::Scope>(*this))
454 , m_extensionStyleSheets(std::make_unique<ExtensionStyleSheets>(*this))
455 , m_visitedLinkState(std::make_unique<VisitedLinkState>(*this))
456 , m_visuallyOrdered(false)
457 , m_readyState(Complete)
459 , m_styleRecalcTimer(*this, &Document::updateStyleIfNeeded)
460 , m_pendingStyleRecalcShouldForce(false)
461 , m_inStyleRecalc(false)
462 , m_closeAfterStyleRecalc(false)
463 , m_gotoAnchorNeededAfterStylesheetsLoad(false)
464 , m_frameElementsShouldIgnoreScrolling(false)
465 , m_updateFocusAppearanceRestoresSelection(SelectionRestorationMode::SetDefault)
466 , m_markers(std::make_unique<DocumentMarkerController>(*this))
467 , m_updateFocusAppearanceTimer(*this, &Document::updateFocusAppearanceTimerFired)
468 , m_cssTarget(nullptr)
469 , m_processingLoadEvent(false)
470 , m_loadEventFinished(false)
471 , m_startTime(std::chrono::steady_clock::now())
472 , m_overMinimumLayoutThreshold(false)
473 , m_scriptRunner(std::make_unique<ScriptRunner>(*this))
474 , m_moduleLoader(std::make_unique<ScriptModuleLoader>(*this))
475 , m_xmlVersion(ASCIILiteral("1.0"))
476 , m_xmlStandalone(StandaloneUnspecified)
477 , m_hasXMLDeclaration(false)
478 , m_designMode(inherit)
479 #if ENABLE(DASHBOARD_SUPPORT)
480 , m_hasAnnotatedRegions(false)
481 , m_annotatedRegionsDirty(false)
483 , m_createRenderers(true)
484 , m_accessKeyMapValid(false)
485 , m_documentClasses(documentClasses)
486 , m_isSynthesized(constructionFlags & Synthesized)
487 , m_isNonRenderedPlaceholder(constructionFlags & NonRenderedPlaceholder)
488 , m_sawElementsInKnownNamespaces(false)
489 , m_isSrcdocDocument(false)
490 , m_eventQueue(*this)
491 , m_weakFactory(this)
492 #if ENABLE(FULLSCREEN_API)
493 , m_areKeysEnabledInFullScreen(0)
494 , m_fullScreenRenderer(nullptr)
495 , m_fullScreenChangeDelayTimer(*this, &Document::fullScreenChangeDelayTimerFired)
496 , m_isAnimatingFullScreen(false)
498 , m_loadEventDelayCount(0)
499 , m_loadEventDelayTimer(*this, &Document::loadEventDelayTimerFired)
500 , m_referrerPolicy(ReferrerPolicy::Default)
501 , m_writeRecursionIsTooDeep(false)
502 , m_writeRecursionDepth(0)
503 , m_lastHandledUserGestureTimestamp(0)
505 #if ENABLE(DEVICE_ORIENTATION)
506 , m_deviceMotionClient(std::make_unique<DeviceMotionClientIOS>())
507 , m_deviceMotionController(std::make_unique<DeviceMotionController>(m_deviceMotionClient.get()))
508 , m_deviceOrientationClient(std::make_unique<DeviceOrientationClientIOS>())
509 , m_deviceOrientationController(std::make_unique<DeviceOrientationController>(m_deviceOrientationClient.get()))
512 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
513 , m_isTelephoneNumberParsingAllowed(true)
515 , m_pendingTasksTimer(*this, &Document::pendingTasksTimerFired)
516 , m_scheduledTasksAreSuspended(false)
517 , m_visualUpdatesAllowed(true)
518 , m_visualUpdatesSuppressionTimer(*this, &Document::visualUpdatesSuppressionTimerFired)
519 , m_sharedObjectPoolClearTimer(*this, &Document::clearSharedObjectPool)
521 , m_didDispatchViewportPropertiesChanged(false)
523 , m_templateDocumentHost(nullptr)
524 , m_fontSelector(CSSFontSelector::create(*this))
525 #if ENABLE(WEB_REPLAY)
526 , m_inputCursor(EmptyInputCursor::create())
528 , m_didAssociateFormControlsTimer(*this, &Document::didAssociateFormControlsTimerFired)
529 , m_cookieCacheExpiryTimer(*this, &Document::invalidateDOMCookieCache)
530 , m_disabledFieldsetElementsCount(0)
531 , m_hasInjectedPlugInsScript(false)
532 , m_hasStyleWithViewportUnits(false)
533 #if ENABLE(WEB_SOCKETS)
534 , m_socketProvider(page() ? &page()->socketProvider() : nullptr)
537 allDocuments().add(this);
539 // We depend on the url getting immediately set in subframes, but we
540 // also depend on the url NOT getting immediately set in opened windows.
541 // See fast/dom/early-frame-url.html
542 // and fast/dom/location-new-window-no-crash.html, respectively.
543 // FIXME: Can/should we unify this behavior?
544 if ((frame && frame->ownerElement()) || !url.isEmpty())
547 m_cachedResourceLoader->setDocument(this);
550 resetVisitedLinkColor();
551 resetActiveLinkColor();
553 initSecurityContext();
556 m_fontSelector->registerForInvalidationCallbacks(*this);
558 for (auto& nodeListAndCollectionCount : m_nodeListAndCollectionCounts)
559 nodeListAndCollectionCount = 0;
562 #if ENABLE(FULLSCREEN_API)
564 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
569 if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
571 } while ((owner = owner->document().ownerElement()));
577 Ref<Document> Document::create(Document& contextDocument)
579 auto document = adoptRef(*new Document(nullptr, URL()));
580 document->setContextDocument(contextDocument);
581 document->setSecurityOriginPolicy(contextDocument.securityOriginPolicy());
585 Document::~Document()
587 allDocuments().remove(this);
589 ASSERT(!renderView());
590 ASSERT(m_pageCacheState != InPageCache);
591 ASSERT(m_ranges.isEmpty());
592 ASSERT(!m_parentTreeScope);
593 ASSERT(!m_disabledFieldsetElementsCount);
594 ASSERT(m_inDocumentShadowRoots.isEmpty());
596 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
597 m_deviceMotionClient->deviceMotionControllerDestroyed();
598 m_deviceOrientationClient->deviceOrientationControllerDestroyed();
601 if (m_templateDocument)
602 m_templateDocument->setTemplateDocumentHost(nullptr); // balanced in templateDocument().
604 // FIXME: Should we reset m_domWindow when we detach from the Frame?
606 m_domWindow->resetUnlessSuspendedForDocumentSuspension();
608 m_scriptRunner = nullptr;
609 m_moduleLoader = nullptr;
611 removeAllEventListeners();
613 // Currently we believe that Document can never outlive the parser.
614 // Although the Document may be replaced synchronously, DocumentParsers
615 // generally keep at least one reference to an Element which would in turn
616 // has a reference to the Document. If you hit this ASSERT, then that
617 // assumption is wrong. DocumentParser::detach() should ensure that even
618 // if the DocumentParser outlives the Document it won't cause badness.
619 ASSERT(!m_parser || m_parser->refCount() == 1);
622 if (this == &topDocument())
623 clearAXObjectCache();
627 if (m_styleSheetList)
628 m_styleSheetList->detachFromDocument();
630 extensionStyleSheets().detachFromDocument();
632 styleScope().clearResolver(); // We need to destroy CSSFontSelector before destroying m_cachedResourceLoader.
633 m_fontSelector->clearDocument();
634 m_fontSelector->unregisterForInvalidationCallbacks(*this);
636 // It's possible for multiple Documents to end up referencing the same CachedResourceLoader (e.g., SVGImages
637 // load the initial empty document and the SVGDocument with the same DocumentLoader).
638 if (m_cachedResourceLoader->document() == this)
639 m_cachedResourceLoader->setDocument(nullptr);
642 if (auto* platformMediaSessionManager = PlatformMediaSessionManager::sharedManagerIfExists())
643 platformMediaSessionManager->stopAllMediaPlaybackForDocument(this);
646 // We must call clearRareData() here since a Document class inherits TreeScope
647 // as well as Node. See a comment on TreeScope.h for the reason.
651 ASSERT(!m_listsInvalidatedAtDocument.size());
652 ASSERT(!m_collectionsInvalidatedAtDocument.size());
654 for (unsigned i = 0; i < WTF_ARRAY_LENGTH(m_nodeListAndCollectionCounts); ++i)
655 ASSERT(!m_nodeListAndCollectionCounts[i]);
658 void Document::removedLastRef()
660 ASSERT(!m_deletionHasBegun);
661 if (m_referencingNodeCount) {
662 // If removing a child removes the last node reference, we don't want the scope to be destroyed
663 // until after removeDetachedChildren returns, so we protect ourselves.
664 incrementReferencingNodeCount();
666 RELEASE_ASSERT(!hasLivingRenderTree());
667 // We must make sure not to be retaining any of our children through
668 // these extra pointers or we will create a reference cycle.
669 m_focusedElement = nullptr;
670 m_hoveredElement = nullptr;
671 m_activeElement = nullptr;
672 m_titleElement = nullptr;
673 m_documentElement = nullptr;
674 m_focusNavigationStartingNode = nullptr;
675 m_userActionElements.documentDidRemoveLastRef();
676 #if ENABLE(FULLSCREEN_API)
677 m_fullScreenElement = nullptr;
678 m_fullScreenElementStack.clear();
683 // removeDetachedChildren() doesn't always unregister IDs,
684 // so tear down scope information up front to avoid having
685 // stale references in the map.
687 destroyTreeScopeData();
688 removeDetachedChildren();
689 m_formController = nullptr;
693 m_cssCanvasElements.clear();
698 // We need to do this right now since selfOnlyDeref() can delete this.
699 m_inRemovedLastRefFunction = false;
701 decrementReferencingNodeCount();
704 m_inRemovedLastRefFunction = false;
705 m_deletionHasBegun = true;
711 void Document::commonTeardown()
714 accessSVGExtensions().pauseAnimations();
716 #if ENABLE(REQUEST_ANIMATION_FRAME)
717 clearScriptedAnimationController();
721 Element* Document::getElementByAccessKey(const String& key)
725 if (!m_accessKeyMapValid) {
726 buildAccessKeyMap(this);
727 m_accessKeyMapValid = true;
729 return m_elementsByAccessKey.get(key.impl());
732 void Document::buildAccessKeyMap(TreeScope* scope)
735 for (auto& element : descendantsOfType<Element>(scope->rootNode())) {
736 const AtomicString& accessKey = element.attributeWithoutSynchronization(accesskeyAttr);
737 if (!accessKey.isEmpty())
738 m_elementsByAccessKey.set(accessKey.impl(), &element);
740 if (ShadowRoot* root = element.shadowRoot())
741 buildAccessKeyMap(root);
745 void Document::invalidateAccessKeyMap()
747 m_accessKeyMapValid = false;
748 m_elementsByAccessKey.clear();
751 void Document::addImageElementByCaseFoldedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
753 return m_imagesByUsemap.add(name, element, *this);
756 void Document::removeImageElementByCaseFoldedUsemap(const AtomicStringImpl& name, HTMLImageElement& element)
758 return m_imagesByUsemap.remove(name, element);
761 HTMLImageElement* Document::imageElementByCaseFoldedUsemap(const AtomicStringImpl& name) const
763 return m_imagesByUsemap.getElementByCaseFoldedUsemap(name, *this);
766 ExceptionOr<SelectorQuery&> Document::selectorQueryForString(const String& selectorString)
768 if (selectorString.isEmpty())
769 return Exception { SYNTAX_ERR };
770 if (!m_selectorQueryCache)
771 m_selectorQueryCache = std::make_unique<SelectorQueryCache>();
772 return m_selectorQueryCache->add(selectorString, *this);
775 void Document::clearSelectorQueryCache()
777 m_selectorQueryCache = nullptr;
780 MediaQueryMatcher& Document::mediaQueryMatcher()
782 if (!m_mediaQueryMatcher)
783 m_mediaQueryMatcher = MediaQueryMatcher::create(*this);
784 return *m_mediaQueryMatcher;
787 void Document::setCompatibilityMode(DocumentCompatibilityMode mode)
789 if (m_compatibilityModeLocked || mode == m_compatibilityMode)
791 bool wasInQuirksMode = inQuirksMode();
792 m_compatibilityMode = mode;
794 clearSelectorQueryCache();
796 if (inQuirksMode() != wasInQuirksMode) {
797 // All user stylesheets have to reparse using the different mode.
798 extensionStyleSheets().clearPageUserSheet();
799 extensionStyleSheets().invalidateInjectedStyleSheetCache();
803 String Document::compatMode() const
805 return inQuirksMode() ? "BackCompat" : "CSS1Compat";
808 void Document::resetLinkColor()
810 m_linkColor = Color(0, 0, 238);
813 void Document::resetVisitedLinkColor()
815 m_visitedLinkColor = Color(85, 26, 139);
818 void Document::resetActiveLinkColor()
820 m_activeLinkColor = Color(255, 0, 0);
823 DOMImplementation& Document::implementation()
825 if (!m_implementation)
826 m_implementation = std::make_unique<DOMImplementation>(*this);
827 return *m_implementation;
830 bool Document::hasManifest() const
832 return documentElement() && documentElement()->hasTagName(htmlTag) && documentElement()->hasAttributeWithoutSynchronization(manifestAttr);
835 DocumentType* Document::doctype() const
837 for (Node* node = firstChild(); node; node = node->nextSibling()) {
838 if (node->isDocumentTypeNode())
839 return static_cast<DocumentType*>(node);
844 void Document::childrenChanged(const ChildChange& change)
846 ContainerNode::childrenChanged(change);
849 // FIXME: Chrome::didReceiveDocType() used to be called only when the doctype changed. We need to check the
850 // impact of calling this systematically. If the overhead is negligible, we need to rename didReceiveDocType,
851 // otherwise, we need to detect the doc type changes before updating the viewport.
852 if (Page* page = this->page())
853 page->chrome().didReceiveDocType(frame());
856 Element* newDocumentElement = childrenOfType<Element>(*this).first();
857 if (newDocumentElement == m_documentElement)
859 m_documentElement = newDocumentElement;
860 // The root style used for media query matching depends on the document element.
861 styleScope().clearResolver();
864 static ALWAYS_INLINE RefPtr<HTMLElement> createUpgradeCandidateElement(Document& document, const QualifiedName& name)
866 if (!RuntimeEnabledFeatures::sharedFeatures().customElementsEnabled())
869 if (Document::validateCustomElementName(name.localName()) != CustomElementNameValidationStatus::Valid)
872 auto element = HTMLElement::create(name, document);
873 element->setIsCustomElementUpgradeCandidate();
874 return WTFMove(element);
877 static ExceptionOr<Ref<Element>> createHTMLElementWithNameValidation(Document& document, const AtomicString& localName)
879 auto element = HTMLElementFactory::createKnownElement(localName, document);
881 return Ref<Element> { element.releaseNonNull() };
883 if (auto* window = document.domWindow()) {
884 auto* registry = window->customElementRegistry();
885 if (UNLIKELY(registry)) {
886 if (auto* elementInterface = registry->findInterface(localName))
887 return elementInterface->constructElementWithFallback(document, localName);
891 if (UNLIKELY(!Document::isValidName(localName)))
892 return Exception { INVALID_CHARACTER_ERR };
894 QualifiedName qualifiedName { nullAtom, localName, xhtmlNamespaceURI };
896 if (auto element = createUpgradeCandidateElement(document, qualifiedName))
897 return Ref<Element> { element.releaseNonNull() };
899 return Ref<Element> { HTMLUnknownElement::create(qualifiedName, document) };
902 ExceptionOr<Ref<Element>> Document::createElementForBindings(const AtomicString& name)
904 if (isHTMLDocument())
905 return createHTMLElementWithNameValidation(*this, name.convertToASCIILowercase());
907 if (isXHTMLDocument())
908 return createHTMLElementWithNameValidation(*this, name);
910 if (!isValidName(name))
911 return Exception { INVALID_CHARACTER_ERR };
913 return createElement(QualifiedName(nullAtom, name, nullAtom), false);
916 Ref<DocumentFragment> Document::createDocumentFragment()
918 return DocumentFragment::create(document());
921 Ref<Text> Document::createTextNode(const String& data)
923 return Text::create(*this, data);
926 Ref<Comment> Document::createComment(const String& data)
928 return Comment::create(*this, data);
931 ExceptionOr<Ref<CDATASection>> Document::createCDATASection(const String& data)
933 if (isHTMLDocument())
934 return Exception { NOT_SUPPORTED_ERR };
935 return CDATASection::create(*this, data);
938 ExceptionOr<Ref<ProcessingInstruction>> Document::createProcessingInstruction(const String& target, const String& data)
940 if (!isValidName(target))
941 return Exception { INVALID_CHARACTER_ERR };
943 if (data.contains("?>"))
944 return Exception { INVALID_CHARACTER_ERR };
946 return ProcessingInstruction::create(*this, target, data);
949 Ref<Text> Document::createEditingTextNode(const String& text)
951 return Text::createEditingText(*this, text);
954 Ref<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
956 Ref<MutableStyleProperties> propertySet(MutableStyleProperties::create());
957 return *propertySet->ensureCSSStyleDeclaration();
960 ExceptionOr<Ref<Node>> Document::importNode(Node& nodeToImport, bool deep)
962 switch (nodeToImport.nodeType()) {
963 case DOCUMENT_FRAGMENT_NODE:
964 if (nodeToImport.isShadowRoot())
969 case CDATA_SECTION_NODE:
970 case PROCESSING_INSTRUCTION_NODE:
972 return nodeToImport.cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf);
975 // FIXME: This will "Attr::normalize" child nodes of Attr.
976 return Ref<Node> { Attr::create(*this, QualifiedName(nullAtom, downcast<Attr>(nodeToImport).name(), nullAtom), downcast<Attr>(nodeToImport).value()) };
978 case DOCUMENT_NODE: // Can't import a document into another document.
979 case DOCUMENT_TYPE_NODE: // FIXME: Support cloning a DocumentType node per DOM4.
983 return Exception { NOT_SUPPORTED_ERR };
987 ExceptionOr<Ref<Node>> Document::adoptNode(Node& source)
989 EventQueueScope scope;
991 switch (source.nodeType()) {
993 return Exception { NOT_SUPPORTED_ERR };
994 case ATTRIBUTE_NODE: {
995 auto& attr = downcast<Attr>(source);
996 if (auto* element = attr.ownerElement()) {
997 auto result = element->removeAttributeNode(attr);
998 if (result.hasException())
999 return result.releaseException();
1004 if (source.isShadowRoot()) {
1005 // ShadowRoot cannot disconnect itself from the host node.
1006 return Exception { HIERARCHY_REQUEST_ERR };
1008 if (is<HTMLFrameOwnerElement>(source)) {
1009 auto& frameOwnerElement = downcast<HTMLFrameOwnerElement>(source);
1010 if (frame() && frame()->tree().isDescendantOf(frameOwnerElement.contentFrame()))
1011 return Exception { HIERARCHY_REQUEST_ERR };
1013 auto result = source.remove();
1014 if (result.hasException())
1015 return result.releaseException();
1018 adoptIfNeeded(&source);
1020 return Ref<Node> { source };
1023 bool Document::hasValidNamespaceForElements(const QualifiedName& qName)
1025 // These checks are from DOM Core Level 2, createElementNS
1026 // http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS
1027 if (!qName.prefix().isEmpty() && qName.namespaceURI().isNull()) // createElementNS(null, "html:div")
1029 if (qName.prefix() == xmlAtom && qName.namespaceURI() != XMLNames::xmlNamespaceURI) // createElementNS("http://www.example.com", "xml:lang")
1032 // Required by DOM Level 3 Core and unspecified by DOM Level 2 Core:
1033 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-DocCrElNS
1034 // createElementNS("http://www.w3.org/2000/xmlns/", "foo:bar"), createElementNS(null, "xmlns:bar"), createElementNS(null, "xmlns")
1035 if (qName.prefix() == xmlnsAtom || (qName.prefix().isEmpty() && qName.localName() == xmlnsAtom))
1036 return qName.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
1037 return qName.namespaceURI() != XMLNSNames::xmlnsNamespaceURI;
1040 bool Document::hasValidNamespaceForAttributes(const QualifiedName& qName)
1042 return hasValidNamespaceForElements(qName);
1045 static Ref<HTMLElement> createFallbackHTMLElement(Document& document, const QualifiedName& name)
1047 if (auto* window = document.domWindow()) {
1048 auto* registry = window->customElementRegistry();
1049 if (UNLIKELY(registry)) {
1050 if (auto* elementInterface = registry->findInterface(name)) {
1051 auto element = HTMLElement::create(name, document);
1052 element->enqueueToUpgrade(*elementInterface);
1057 // FIXME: Should we also check the equality of prefix between the custom element and name?
1058 if (auto element = createUpgradeCandidateElement(document, name))
1059 return element.releaseNonNull();
1060 return HTMLUnknownElement::create(name, document);
1063 // FIXME: This should really be in a possible ElementFactory class.
1064 Ref<Element> Document::createElement(const QualifiedName& name, bool createdByParser)
1066 RefPtr<Element> element;
1068 // FIXME: Use registered namespaces and look up in a hash to find the right factory.
1069 if (name.namespaceURI() == xhtmlNamespaceURI) {
1070 element = HTMLElementFactory::createKnownElement(name, *this, nullptr, createdByParser);
1071 if (UNLIKELY(!element))
1072 element = createFallbackHTMLElement(*this, name);
1073 } else if (name.namespaceURI() == SVGNames::svgNamespaceURI)
1074 element = SVGElementFactory::createElement(name, *this, createdByParser);
1076 else if (name.namespaceURI() == MathMLNames::mathmlNamespaceURI)
1077 element = MathMLElementFactory::createElement(name, *this, createdByParser);
1081 m_sawElementsInKnownNamespaces = true;
1083 element = Element::create(name, document());
1085 // <image> uses imgTag so we need a special rule.
1086 ASSERT((name.matches(imageTag) && element->tagQName().matches(imgTag) && element->tagQName().prefix() == name.prefix()) || name == element->tagQName());
1088 return element.releaseNonNull();
1091 CustomElementNameValidationStatus Document::validateCustomElementName(const AtomicString& localName)
1093 bool containsHyphen = false;
1094 for (auto character : StringView(localName).codeUnits()) {
1095 if (isASCIIUpper(character))
1096 return CustomElementNameValidationStatus::ContainsUpperCase;
1097 if (character == '-')
1098 containsHyphen = true;
1101 if (!containsHyphen)
1102 return CustomElementNameValidationStatus::NoHyphen;
1105 const auto& annotationXmlLocalName = MathMLNames::annotation_xmlTag.localName();
1107 static NeverDestroyed<const AtomicString> annotationXmlLocalName("annotation-xml", AtomicString::ConstructFromLiteral);
1110 if (localName == SVGNames::color_profileTag.localName()
1111 || localName == SVGNames::font_faceTag.localName()
1112 || localName == SVGNames::font_face_formatTag.localName()
1113 || localName == SVGNames::font_face_nameTag.localName()
1114 || localName == SVGNames::font_face_srcTag.localName()
1115 || localName == SVGNames::font_face_uriTag.localName()
1116 || localName == SVGNames::missing_glyphTag.localName()
1117 || localName == annotationXmlLocalName)
1118 return CustomElementNameValidationStatus::ConflictsWithBuiltinNames;
1120 return CustomElementNameValidationStatus::Valid;
1123 #if ENABLE(CSS_GRID_LAYOUT)
1125 bool Document::isCSSGridLayoutEnabled() const
1127 return RuntimeEnabledFeatures::sharedFeatures().isCSSGridLayoutEnabled();
1132 #if ENABLE(CSS_REGIONS)
1134 RefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
1139 updateStyleIfNeeded();
1141 return namedFlows().createCSSOMSnapshot();
1146 NamedFlowCollection& Document::namedFlows()
1149 m_namedFlows = NamedFlowCollection::create(this);
1151 return *m_namedFlows;
1154 ExceptionOr<Ref<Element>> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName)
1156 auto parseResult = parseQualifiedName(namespaceURI, qualifiedName);
1157 if (parseResult.hasException())
1158 return parseResult.releaseException();
1159 QualifiedName parsedName { parseResult.releaseReturnValue() };
1160 if (!hasValidNamespaceForElements(parsedName))
1161 return Exception { NAMESPACE_ERR };
1162 return createElement(parsedName, false);
1165 String Document::readyState() const
1167 static NeverDestroyed<const String> loading(ASCIILiteral("loading"));
1168 static NeverDestroyed<const String> interactive(ASCIILiteral("interactive"));
1169 static NeverDestroyed<const String> complete(ASCIILiteral("complete"));
1171 switch (m_readyState) {
1180 ASSERT_NOT_REACHED();
1184 void Document::setReadyState(ReadyState readyState)
1186 if (readyState == m_readyState)
1189 #if ENABLE(WEB_TIMING)
1190 switch (readyState) {
1192 if (!m_documentTiming.domLoading)
1193 m_documentTiming.domLoading = monotonicallyIncreasingTime();
1196 if (!m_documentTiming.domInteractive)
1197 m_documentTiming.domInteractive = monotonicallyIncreasingTime();
1200 if (!m_documentTiming.domComplete)
1201 m_documentTiming.domComplete = monotonicallyIncreasingTime();
1206 m_readyState = readyState;
1207 dispatchEvent(Event::create(eventNames().readystatechangeEvent, false, false));
1209 if (settings() && settings()->suppressesIncrementalRendering())
1210 setVisualUpdatesAllowed(readyState);
1213 void Document::setVisualUpdatesAllowed(ReadyState readyState)
1215 ASSERT(settings() && settings()->suppressesIncrementalRendering());
1216 switch (readyState) {
1218 ASSERT(!m_visualUpdatesSuppressionTimer.isActive());
1219 ASSERT(m_visualUpdatesAllowed);
1220 setVisualUpdatesAllowed(false);
1223 ASSERT(m_visualUpdatesSuppressionTimer.isActive() || m_visualUpdatesAllowed);
1226 if (m_visualUpdatesSuppressionTimer.isActive()) {
1227 ASSERT(!m_visualUpdatesAllowed);
1229 if (!view()->visualUpdatesAllowedByClient())
1232 setVisualUpdatesAllowed(true);
1234 ASSERT(m_visualUpdatesAllowed);
1239 void Document::setVisualUpdatesAllowed(bool visualUpdatesAllowed)
1241 if (m_visualUpdatesAllowed == visualUpdatesAllowed)
1244 m_visualUpdatesAllowed = visualUpdatesAllowed;
1246 if (visualUpdatesAllowed)
1247 m_visualUpdatesSuppressionTimer.stop();
1249 m_visualUpdatesSuppressionTimer.startOneShot(settings()->incrementalRenderingSuppressionTimeoutInSeconds());
1251 if (!visualUpdatesAllowed)
1254 FrameView* frameView = view();
1255 bool needsLayout = frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout());
1259 if (Page* page = this->page()) {
1260 if (frame()->isMainFrame()) {
1261 frameView->addPaintPendingMilestones(DidFirstPaintAfterSuppressedIncrementalRendering);
1262 if (page->requestedLayoutMilestones() & DidFirstLayoutAfterSuppressedIncrementalRendering)
1263 frame()->loader().didReachLayoutMilestone(DidFirstLayoutAfterSuppressedIncrementalRendering);
1268 view()->updateCompositingLayersAfterLayout();
1270 if (RenderView* renderView = this->renderView())
1271 renderView->repaintViewAndCompositedLayers();
1273 if (Frame* frame = this->frame())
1274 frame->loader().forcePageTransitionIfNeeded();
1277 void Document::visualUpdatesSuppressionTimerFired()
1279 ASSERT(!m_visualUpdatesAllowed);
1281 // If the client is extending the visual update suppression period explicitly, the
1282 // watchdog should not re-enable visual updates itself, but should wait for the client.
1283 if (!view()->visualUpdatesAllowedByClient())
1286 setVisualUpdatesAllowed(true);
1289 void Document::setVisualUpdatesAllowedByClient(bool visualUpdatesAllowedByClient)
1291 // We should only re-enable visual updates if ReadyState is Completed or the watchdog timer has fired,
1292 // both of which we can determine by looking at the timer.
1294 if (visualUpdatesAllowedByClient && !m_visualUpdatesSuppressionTimer.isActive() && !visualUpdatesAllowed())
1295 setVisualUpdatesAllowed(true);
1298 String Document::characterSetWithUTF8Fallback() const
1300 AtomicString name = encoding();
1303 return UTF8Encoding().domName();
1306 String Document::defaultCharsetForLegacyBindings() const
1308 if (Settings* settings = this->settings())
1309 return settings->defaultTextEncodingName();
1310 return UTF8Encoding().domName();
1313 void Document::setCharset(const String& charset)
1317 decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
1320 void Document::setContentLanguage(const String& language)
1322 if (m_contentLanguage == language)
1324 m_contentLanguage = language;
1326 // Recalculate style so language is used when selecting the initial font.
1327 m_styleScope->didChangeStyleSheetEnvironment();
1330 ExceptionOr<void> Document::setXMLVersion(const String& version)
1332 if (!XMLDocumentParser::supportsXMLVersion(version))
1333 return Exception { NOT_SUPPORTED_ERR };
1335 m_xmlVersion = version;
1339 void Document::setXMLStandalone(bool standalone)
1341 m_xmlStandalone = standalone ? Standalone : NotStandalone;
1344 void Document::setDocumentURI(const String& uri)
1346 // This property is read-only from JavaScript, but writable from Objective-C.
1347 m_documentURI = uri;
1351 void Document::setContent(const String& content)
1354 // FIXME: This should probably use insert(), but that's (intentionally)
1355 // not implemented for the XML parser as it's normally synonymous with
1356 // document.write(). append() will end up yielding, but close() will
1357 // pump the tokenizer syncrhonously and finish the parse.
1358 m_parser->append(content.impl());
1362 String Document::suggestedMIMEType() const
1364 if (isXHTMLDocument())
1365 return ASCIILiteral("application/xhtml+xml");
1366 if (isSVGDocument())
1367 return ASCIILiteral("image/svg+xml");
1368 if (xmlStandalone())
1369 return ASCIILiteral("text/xml");
1370 if (isHTMLDocument())
1371 return ASCIILiteral("text/html");
1372 if (DocumentLoader* loader = this->loader())
1373 return loader->responseMIMEType();
1377 void Document::overrideMIMEType(const String& mimeType)
1379 m_overriddenMIMEType = mimeType;
1382 String Document::contentType() const
1384 if (!m_overriddenMIMEType.isNull())
1385 return m_overriddenMIMEType;
1387 if (DocumentLoader* documentLoader = loader())
1388 return documentLoader->currentContentType();
1390 String mimeType = suggestedMIMEType();
1391 if (!mimeType.isNull())
1394 return ASCIILiteral("application/xml");
1397 RefPtr<Range> Document::caretRangeFromPoint(int x, int y)
1399 return caretRangeFromPoint(LayoutPoint(x, y));
1402 RefPtr<Range> Document::caretRangeFromPoint(const LayoutPoint& clientPoint)
1404 if (!hasLivingRenderTree())
1407 LayoutPoint localPoint;
1408 Node* node = nodeFromPoint(clientPoint, &localPoint);
1412 Node* shadowAncestorNode = ancestorInThisScope(node);
1413 if (shadowAncestorNode != node) {
1414 unsigned offset = shadowAncestorNode->computeNodeIndex();
1415 ContainerNode* container = shadowAncestorNode->parentNode();
1416 return Range::create(*this, container, offset, container, offset);
1419 RenderObject* renderer = node->renderer();
1422 VisiblePosition visiblePosition = renderer->positionForPoint(localPoint, nullptr);
1423 if (visiblePosition.isNull())
1426 Position rangeCompliantPosition = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
1427 return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
1430 Element* Document::scrollingElement()
1432 // FIXME: When we fix https://bugs.webkit.org/show_bug.cgi?id=106133, this should be replaced with the full implementation
1433 // of Document.scrollingElement() as specified at http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement.
1439 * Performs three operations:
1440 * 1. Convert control characters to spaces
1441 * 2. Trim leading and trailing spaces
1442 * 3. Collapse internal whitespace.
1444 template <typename CharacterType>
1445 static inline StringWithDirection canonicalizedTitle(Document* document, const StringWithDirection& titleWithDirection)
1447 const String& title = titleWithDirection.string();
1448 const CharacterType* characters = title.characters<CharacterType>();
1449 unsigned length = title.length();
1452 StringBuffer<CharacterType> buffer(length);
1453 unsigned builderIndex = 0;
1455 // Skip leading spaces and leading characters that would convert to spaces
1456 for (i = 0; i < length; ++i) {
1457 CharacterType c = characters[i];
1458 if (isNotHTMLSpace(c))
1463 return StringWithDirection();
1465 // Replace control characters with spaces, and backslashes with currency symbols, and collapse whitespace.
1466 bool previousCharWasWS = false;
1467 for (; i < length; ++i) {
1468 CharacterType c = characters[i];
1469 if (isHTMLSpace(c)) {
1470 if (previousCharWasWS)
1472 buffer[builderIndex++] = ' ';
1473 previousCharWasWS = true;
1475 buffer[builderIndex++] = c;
1476 previousCharWasWS = false;
1480 // Strip trailing spaces
1481 while (builderIndex > 0) {
1483 if (buffer[builderIndex] != ' ')
1487 if (!builderIndex && buffer[builderIndex] == ' ')
1488 return StringWithDirection();
1490 buffer.shrink(builderIndex + 1);
1492 // Replace the backslashes with currency symbols if the encoding requires it.
1493 document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
1495 return StringWithDirection(String::adopt(WTFMove(buffer)), titleWithDirection.direction());
1498 void Document::updateTitle(const StringWithDirection& title)
1500 if (m_rawTitle == title)
1505 if (m_rawTitle.string().isEmpty())
1506 m_title = StringWithDirection();
1508 if (m_rawTitle.string().is8Bit())
1509 m_title = canonicalizedTitle<LChar>(this, m_rawTitle);
1511 m_title = canonicalizedTitle<UChar>(this, m_rawTitle);
1513 if (DocumentLoader* loader = this->loader())
1514 loader->setTitle(m_title);
1517 void Document::updateTitleFromTitleElement()
1519 if (!m_titleElement) {
1520 updateTitle(StringWithDirection());
1524 if (is<HTMLTitleElement>(*m_titleElement))
1525 updateTitle(downcast<HTMLTitleElement>(*m_titleElement).textWithDirection());
1526 else if (is<SVGTitleElement>(*m_titleElement)) {
1527 // FIXME: does SVG have a title text direction?
1528 updateTitle(StringWithDirection(downcast<SVGTitleElement>(*m_titleElement).textContent(), LTR));
1532 void Document::setTitle(const String& title)
1534 if (!m_titleElement) {
1535 if (isHTMLDocument() || isXHTMLDocument()) {
1536 auto* headElement = head();
1539 m_titleElement = HTMLTitleElement::create(HTMLNames::titleTag, *this);
1540 headElement->appendChild(*m_titleElement);
1541 } else if (isSVGDocument()) {
1542 auto* element = documentElement();
1543 if (!is<SVGSVGElement>(element))
1545 m_titleElement = SVGTitleElement::create(SVGNames::titleTag, *this);
1546 element->insertBefore(*m_titleElement, element->firstChild());
1548 } else if (!isHTMLDocument() && !isXHTMLDocument() && !isSVGDocument())
1549 m_titleElement = nullptr;
1551 // The DOM API has no method of specifying direction, so assume LTR.
1552 updateTitle(StringWithDirection(title, LTR));
1554 if (is<HTMLTitleElement>(m_titleElement.get()))
1555 downcast<HTMLTitleElement>(*m_titleElement).setTextContent(title);
1556 else if (is<SVGTitleElement>(m_titleElement.get()))
1557 downcast<SVGTitleElement>(*m_titleElement).setTextContent(title);
1560 void Document::updateTitleElement(Element* newTitleElement)
1562 if (is<SVGSVGElement>(documentElement()))
1563 m_titleElement = childrenOfType<SVGTitleElement>(*documentElement()).first();
1565 if (m_titleElement) {
1566 if (isHTMLDocument() || isXHTMLDocument())
1567 m_titleElement = descendantsOfType<HTMLTitleElement>(*this).first();
1569 m_titleElement = newTitleElement;
1572 updateTitleFromTitleElement();
1575 void Document::titleElementAdded(Element& titleElement)
1577 if (m_titleElement == &titleElement)
1580 updateTitleElement(&titleElement);
1583 void Document::titleElementRemoved(Element& titleElement)
1585 if (m_titleElement != &titleElement)
1588 updateTitleElement(nullptr);
1591 void Document::titleElementTextChanged(Element& titleElement)
1593 if (m_titleElement != &titleElement)
1596 updateTitleFromTitleElement();
1599 void Document::registerForVisibilityStateChangedCallbacks(Element* element)
1601 m_visibilityStateCallbackElements.add(element);
1604 void Document::unregisterForVisibilityStateChangedCallbacks(Element* element)
1606 m_visibilityStateCallbackElements.remove(element);
1609 void Document::visibilityStateChanged()
1611 dispatchEvent(Event::create(eventNames().visibilitychangeEvent, false, false));
1612 for (auto* element : m_visibilityStateCallbackElements)
1613 element->visibilityStateChanged();
1616 PageVisibilityState Document::pageVisibilityState() const
1618 // The visibility of the document is inherited from the visibility of the
1619 // page. If there is no page associated with the document, we will assume
1620 // that the page is hidden, as specified by the spec:
1621 // http://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PageVisibility/Overview.html#dom-document-hidden
1622 if (!m_frame || !m_frame->page())
1623 return PageVisibilityStateHidden;
1624 return m_frame->page()->visibilityState();
1627 String Document::visibilityState() const
1629 return pageVisibilityStateString(pageVisibilityState());
1632 bool Document::hidden() const
1634 return pageVisibilityState() != PageVisibilityStateVisible;
1639 void Document::registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1641 m_allowsMediaDocumentInlinePlaybackElements.add(&element);
1644 void Document::unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement& element)
1646 m_allowsMediaDocumentInlinePlaybackElements.remove(&element);
1649 void Document::allowsMediaDocumentInlinePlaybackChanged()
1651 for (auto* element : m_allowsMediaDocumentInlinePlaybackElements)
1652 element->allowsMediaDocumentInlinePlaybackChanged();
1657 String Document::nodeName() const
1659 return ASCIILiteral("#document");
1662 Node::NodeType Document::nodeType() const
1664 return DOCUMENT_NODE;
1667 FormController& Document::formController()
1669 if (!m_formController)
1670 m_formController = std::make_unique<FormController>();
1671 return *m_formController;
1674 Vector<String> Document::formElementsState() const
1676 if (!m_formController)
1677 return Vector<String>();
1678 return m_formController->formElementsState();
1681 void Document::setStateForNewFormElements(const Vector<String>& stateVector)
1683 if (!stateVector.size() && !m_formController)
1685 formController().setStateForNewFormElements(stateVector);
1688 FrameView* Document::view() const
1690 return m_frame ? m_frame->view() : nullptr;
1693 Page* Document::page() const
1695 return m_frame ? m_frame->page() : nullptr;
1698 Settings* Document::settings() const
1700 return m_frame ? &m_frame->settings() : nullptr;
1703 Ref<Range> Document::createRange()
1705 return Range::create(*this);
1708 Ref<NodeIterator> Document::createNodeIterator(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1710 return NodeIterator::create(root, whatToShow, WTFMove(filter));
1713 Ref<TreeWalker> Document::createTreeWalker(Node& root, unsigned long whatToShow, RefPtr<NodeFilter>&& filter, bool)
1715 return TreeWalker::create(root, whatToShow, WTFMove(filter));
1718 void Document::scheduleForcedStyleRecalc()
1720 m_pendingStyleRecalcShouldForce = true;
1721 scheduleStyleRecalc();
1724 void Document::scheduleStyleRecalc()
1726 ASSERT(!m_renderView || !m_renderView->inHitTesting());
1728 if (m_styleRecalcTimer.isActive() || pageCacheState() != NotInPageCache)
1731 ASSERT(childNeedsStyleRecalc() || m_pendingStyleRecalcShouldForce);
1733 // FIXME: Why on earth is this here? This is clearly misplaced.
1734 invalidateAccessKeyMap();
1736 m_styleRecalcTimer.startOneShot(0);
1738 InspectorInstrumentation::didScheduleStyleRecalculation(*this);
1741 void Document::unscheduleStyleRecalc()
1743 ASSERT(!childNeedsStyleRecalc());
1745 m_styleRecalcTimer.stop();
1746 m_pendingStyleRecalcShouldForce = false;
1749 bool Document::hasPendingStyleRecalc() const
1751 return m_styleRecalcTimer.isActive() && !m_inStyleRecalc;
1754 bool Document::hasPendingForcedStyleRecalc() const
1756 return m_styleRecalcTimer.isActive() && m_pendingStyleRecalcShouldForce;
1759 void Document::recalcStyle(Style::Change change)
1761 ASSERT(!view() || !view()->isPainting());
1763 // NOTE: XSL code seems to be the only client stumbling in here without a RenderView.
1767 FrameView& frameView = m_renderView->frameView();
1768 Ref<FrameView> protect(frameView);
1769 if (frameView.isPainting())
1772 if (m_inStyleRecalc)
1773 return; // Guard against re-entrancy. -dwh
1775 TraceScope tracingScope(StyleRecalcStart, StyleRecalcEnd);
1777 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1778 AnimationUpdateBlock animationUpdateBlock(&m_frame->animation());
1780 // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
1781 // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
1782 // before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
1783 // resolves style (here) and then when we resolve style on the parent chain, we may end up
1784 // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
1785 // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
1787 styleScope().flushPendingUpdate();
1789 frameView.willRecalcStyle();
1791 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(*this);
1793 m_inStyleRecalc = true;
1794 bool updatedCompositingLayers = false;
1796 Style::PostResolutionCallbackDisabler disabler(*this);
1797 WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
1799 if (m_pendingStyleRecalcShouldForce)
1800 change = Style::Force;
1802 if (change == Style::Force) {
1803 // This may get set again during style resolve.
1804 m_hasNodesWithPlaceholderStyle = false;
1806 auto documentStyle = Style::resolveForDocument(*this);
1808 // Inserting the pictograph font at the end of the font fallback list is done by the
1809 // font selector, so set a font selector if needed.
1810 if (Settings* settings = this->settings()) {
1811 if (settings->fontFallbackPrefersPictographs())
1812 documentStyle.fontCascade().update(&fontSelector());
1815 auto documentChange = Style::determineChange(documentStyle, m_renderView->style());
1816 if (documentChange != Style::NoChange)
1817 renderView()->setStyle(WTFMove(documentStyle));
1820 Style::TreeResolver resolver(*this);
1821 auto styleUpdate = resolver.resolve(change);
1823 m_lastStyleUpdateSizeForTesting = styleUpdate ? styleUpdate->size() : 0;
1826 clearChildNeedsStyleRecalc();
1827 unscheduleStyleRecalc();
1829 m_inStyleRecalc = false;
1832 TemporaryChange<bool> inRenderTreeUpdate(m_inRenderTreeUpdate, true);
1834 RenderTreeUpdater updater(*this);
1835 updater.commit(WTFMove(styleUpdate));
1838 updatedCompositingLayers = frameView.updateCompositingLayersAfterStyleChange();
1841 // If we wanted to call implicitClose() during recalcStyle, do so now that we're finished.
1842 if (m_closeAfterStyleRecalc) {
1843 m_closeAfterStyleRecalc = false;
1847 ++m_styleRecalcCount;
1849 InspectorInstrumentation::didRecalculateStyle(cookie);
1851 // Some animated images may now be inside the viewport due to style recalc,
1852 // resume them if necessary if there is no layout pending. Otherwise, we'll
1853 // check if they need to be resumed after layout.
1854 if (updatedCompositingLayers && !frameView.needsLayout())
1855 frameView.viewportContentsChanged();
1857 if (!frameView.needsLayout())
1858 frameView.frame().selection().updateAppearanceAfterLayout();
1860 // As a result of the style recalculation, the currently hovered element might have been
1861 // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
1862 // to check if any other elements ended up under the mouse pointer due to re-layout.
1863 if (m_hoveredElement && !m_hoveredElement->renderer())
1864 frameView.frame().mainFrame().eventHandler().dispatchFakeMouseMoveEventSoon();
1867 bool Document::needsStyleRecalc() const
1869 if (pageCacheState() != NotInPageCache)
1872 return m_pendingStyleRecalcShouldForce || childNeedsStyleRecalc() || styleScope().hasPendingUpdate();
1875 void Document::updateStyleIfNeeded()
1877 ASSERT(isMainThread());
1878 ASSERT(!view() || !view()->isPainting());
1880 if (!view() || view()->isInRenderTreeLayout())
1883 styleScope().flushPendingUpdate();
1885 if (!needsStyleRecalc())
1891 void Document::updateLayout()
1893 ASSERT(isMainThread());
1895 FrameView* frameView = view();
1896 if (frameView && frameView->isInRenderTreeLayout()) {
1897 // View layout should not be re-entrant.
1898 ASSERT_NOT_REACHED();
1902 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1904 if (HTMLFrameOwnerElement* owner = ownerElement())
1905 owner->document().updateLayout();
1907 updateStyleIfNeeded();
1909 StackStats::LayoutCheckPoint layoutCheckPoint;
1911 // Only do a layout if changes have occurred that make it necessary.
1912 if (frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
1913 frameView->layout();
1916 // FIXME: This is a bad idea and needs to be removed eventually.
1917 // Other browsers load stylesheets before they continue parsing the web page.
1918 // Since we don't, we can run JavaScript code that needs answers before the
1919 // stylesheets are loaded. Doing a layout ignoring the pending stylesheets
1920 // lets us get reasonable answers. The long term solution to this problem is
1921 // to instead suspend JavaScript execution.
1922 void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
1924 bool oldIgnore = m_ignorePendingStylesheets;
1926 if (!haveStylesheetsLoaded()) {
1927 m_ignorePendingStylesheets = true;
1928 // FIXME: We are willing to attempt to suppress painting with outdated style info only once. Our assumption is that it would be
1929 // dangerous to try to stop it a second time, after page content has already been loaded and displayed
1930 // with accurate style information. (Our suppression involves blanking the whole page at the
1931 // moment. If it were more refined, we might be able to do something better.)
1932 // It's worth noting though that this entire method is a hack, since what we really want to do is
1933 // suspend JS instead of doing a layout with inaccurate information.
1934 HTMLElement* bodyElement = bodyOrFrameset();
1935 if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
1936 m_pendingSheetLayout = DidLayoutWithPendingSheets;
1937 styleScope().didChangeActiveStyleSheetCandidates();
1938 recalcStyle(Style::Force);
1939 } else if (m_hasNodesWithPlaceholderStyle)
1940 // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
1941 // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
1942 // but here we need up-to-date style immediately.
1943 recalcStyle(Style::Force);
1948 if (runPostLayoutTasks == RunPostLayoutTasks::Synchronously && view())
1949 view()->flushAnyPendingPostLayoutTasks();
1951 m_ignorePendingStylesheets = oldIgnore;
1954 std::unique_ptr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element& element, const RenderStyle* parentStyle)
1956 ASSERT(&element.document() == this);
1958 // On iOS request delegates called during styleForElement may result in re-entering WebKit and killing the style resolver.
1959 Style::PostResolutionCallbackDisabler disabler(*this);
1961 TemporaryChange<bool> change(m_ignorePendingStylesheets, true);
1962 auto elementStyle = element.resolveStyle(parentStyle);
1964 if (elementStyle.relations) {
1965 Style::Update emptyUpdate(*this);
1966 Style::commitRelations(WTFMove(elementStyle.relations), emptyUpdate);
1969 return WTFMove(elementStyle.renderStyle);
1972 bool Document::updateLayoutIfDimensionsOutOfDate(Element& element, DimensionsCheck dimensionsCheck)
1974 ASSERT(isMainThread());
1976 // If the stylesheets haven't loaded, just give up and do a full layout ignoring pending stylesheets.
1977 if (!haveStylesheetsLoaded()) {
1978 updateLayoutIgnorePendingStylesheets();
1982 // Check for re-entrancy and assert (same code that is in updateLayout()).
1983 FrameView* frameView = view();
1984 if (frameView && frameView->isInRenderTreeLayout()) {
1985 // View layout should not be re-entrant.
1986 ASSERT_NOT_REACHED();
1990 RenderView::RepaintRegionAccumulator repaintRegionAccumulator(renderView());
1992 // Mimic the structure of updateLayout(), but at each step, see if we have been forced into doing a full
1994 bool requireFullLayout = false;
1995 if (HTMLFrameOwnerElement* owner = ownerElement()) {
1996 if (owner->document().updateLayoutIfDimensionsOutOfDate(*owner))
1997 requireFullLayout = true;
2000 updateStyleIfNeeded();
2002 RenderObject* renderer = element.renderer();
2003 if (!renderer || renderer->needsLayout() || element.renderNamedFlowFragment()) {
2004 // If we don't have a renderer or if the renderer needs layout for any reason, give up.
2005 // Named flows can have auto height, so don't try to enforce the optimization in this case.
2006 // The 2-pass nature of auto height named flow layout means the region may not be dirty yet.
2007 requireFullLayout = true;
2010 bool isVertical = renderer && !renderer->isHorizontalWritingMode();
2011 bool checkingLogicalWidth = ((dimensionsCheck & WidthDimensionsCheck) && !isVertical) || ((dimensionsCheck & HeightDimensionsCheck) && isVertical);
2012 bool checkingLogicalHeight = ((dimensionsCheck & HeightDimensionsCheck) && !isVertical) || ((dimensionsCheck & WidthDimensionsCheck) && isVertical);
2013 bool hasSpecifiedLogicalHeight = renderer && renderer->style().logicalMinHeight() == Length(0, Fixed) && renderer->style().logicalHeight().isFixed() && renderer->style().logicalMaxHeight().isAuto();
2015 if (!requireFullLayout) {
2016 RenderBox* previousBox = nullptr;
2017 RenderBox* currentBox = nullptr;
2019 // Check our containing block chain. If anything in the chain needs a layout, then require a full layout.
2020 for (RenderObject* currRenderer = element.renderer(); currRenderer && !currRenderer->isRenderView(); currRenderer = currRenderer->container()) {
2022 // Require the entire container chain to be boxes.
2023 if (!is<RenderBox>(currRenderer)) {
2024 requireFullLayout = true;
2028 previousBox = currentBox;
2029 currentBox = downcast<RenderBox>(currRenderer);
2031 // If a box needs layout for itself or if a box has changed children and sizes its width to
2032 // its content, then require a full layout.
2033 if (currentBox->selfNeedsLayout() ||
2034 (checkingLogicalWidth && currRenderer->needsLayout() && currentBox->sizesLogicalWidthToFitContent(MainOrPreferredSize))) {
2035 requireFullLayout = true;
2039 // If a block contains floats and the child's height isn't specified, then
2040 // give up also, since our height could end up being influenced by the floats.
2041 if (checkingLogicalHeight && !hasSpecifiedLogicalHeight && currentBox->isRenderBlockFlow()) {
2042 RenderBlockFlow* currentBlockFlow = downcast<RenderBlockFlow>(currentBox);
2043 if (currentBlockFlow->containsFloats() && previousBox && !previousBox->isFloatingOrOutOfFlowPositioned()) {
2044 requireFullLayout = true;
2049 if (!currentBox->isRenderBlockFlow() || currentBox->flowThreadContainingBlock() || currentBox->isWritingModeRoot()) {
2050 // FIXME: For now require only block flows all the way back to the root. This limits the optimization
2051 // for now, and we'll expand it in future patches to apply to more and more scenarios.
2052 // Disallow regions/columns from having the optimization.
2053 // Give up if the writing mode changes at all in the containing block chain.
2054 requireFullLayout = true;
2058 if (currRenderer == frameView->layoutRoot())
2063 StackStats::LayoutCheckPoint layoutCheckPoint;
2065 // Only do a layout if changes have occurred that make it necessary.
2066 if (requireFullLayout && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
2067 frameView->layout();
2069 return requireFullLayout;
2072 bool Document::isPageBoxVisible(int pageIndex)
2074 updateStyleIfNeeded();
2075 std::unique_ptr<RenderStyle> pageStyle(styleScope().resolver().styleForPage(pageIndex));
2076 return pageStyle->visibility() != HIDDEN; // display property doesn't apply to @page.
2079 void Document::pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft)
2081 updateStyleIfNeeded();
2082 std::unique_ptr<RenderStyle> style = styleScope().resolver().styleForPage(pageIndex);
2084 int width = pageSize.width();
2085 int height = pageSize.height();
2086 switch (style->pageSizeType()) {
2087 case PAGE_SIZE_AUTO:
2089 case PAGE_SIZE_AUTO_LANDSCAPE:
2091 std::swap(width, height);
2093 case PAGE_SIZE_AUTO_PORTRAIT:
2095 std::swap(width, height);
2097 case PAGE_SIZE_RESOLVED: {
2098 LengthSize size = style->pageSize();
2099 ASSERT(size.width().isFixed());
2100 ASSERT(size.height().isFixed());
2101 width = valueForLength(size.width(), 0);
2102 height = valueForLength(size.height(), 0);
2106 ASSERT_NOT_REACHED();
2108 pageSize = IntSize(width, height);
2110 // The percentage is calculated with respect to the width even for margin top and bottom.
2111 // http://www.w3.org/TR/CSS2/box.html#margin-properties
2112 marginTop = style->marginTop().isAuto() ? marginTop : intValueForLength(style->marginTop(), width);
2113 marginRight = style->marginRight().isAuto() ? marginRight : intValueForLength(style->marginRight(), width);
2114 marginBottom = style->marginBottom().isAuto() ? marginBottom : intValueForLength(style->marginBottom(), width);
2115 marginLeft = style->marginLeft().isAuto() ? marginLeft : intValueForLength(style->marginLeft(), width);
2118 StyleResolver& Document::userAgentShadowTreeStyleResolver()
2120 if (!m_userAgentShadowTreeStyleResolver)
2121 m_userAgentShadowTreeStyleResolver = std::make_unique<StyleResolver>(*this);
2122 return *m_userAgentShadowTreeStyleResolver;
2125 void Document::fontsNeedUpdate(FontSelector&)
2127 if (auto* resolver = styleScope().resolverIfExists())
2128 resolver->invalidateMatchedPropertiesCache();
2129 if (pageCacheState() != NotInPageCache || !renderView())
2131 scheduleForcedStyleRecalc();
2134 void Document::didClearStyleResolver()
2136 m_userAgentShadowTreeStyleResolver = nullptr;
2138 m_fontSelector->buildStarted();
2141 void Document::createRenderTree()
2143 ASSERT(!renderView());
2144 ASSERT(m_pageCacheState != InPageCache);
2145 ASSERT(!m_axObjectCache || this != &topDocument());
2147 if (m_isNonRenderedPlaceholder)
2150 // FIXME: It would be better if we could pass the resolved document style directly here.
2151 m_renderView = createRenderer<RenderView>(*this, RenderStyle::create());
2152 Node::setRenderer(m_renderView.get());
2154 renderView()->setIsInWindow(true);
2156 recalcStyle(Style::Force);
2159 void Document::didBecomeCurrentDocumentInFrame()
2161 // FIXME: Are there cases where the document can be dislodged from the frame during the event handling below?
2162 // If so, then m_frame could become 0, and we need to do something about that.
2164 m_frame->script().updateDocument();
2166 if (!hasLivingRenderTree())
2169 updateViewportArguments();
2171 // FIXME: Doing this only for the main frame is insufficient.
2172 // Changing a subframe can also change the wheel event handler count.
2173 // FIXME: Doing this only when a document goes into the frame is insufficient.
2174 // Removing a document can also change the wheel event handler count.
2175 // FIXME: Doing this every time is a waste. If the current document and its
2176 // subframes' documents have no wheel event handlers, then the count did not change,
2177 // unless the documents they are replacing had wheel event handlers.
2178 if (page() && m_frame->isMainFrame())
2179 wheelEventHandlersChanged();
2181 #if ENABLE(TOUCH_EVENTS)
2182 // FIXME: Doing this only for the main frame is insufficient.
2183 // A subframe could have touch event handlers.
2184 if (hasTouchEventHandlers() && page() && m_frame->isMainFrame())
2185 page()->chrome().client().needTouchEvents(true);
2188 // Ensure that the scheduled task state of the document matches the DOM suspension state of the frame. It can
2189 // be out of sync if the DOM suspension state changed while the document was not in the frame (possibly in the
2190 // page cache, or simply newly created).
2191 if (m_frame->activeDOMObjectsAndAnimationsSuspended()) {
2192 m_frame->animation().suspendAnimationsForDocument(this);
2193 suspendScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2195 resumeScheduledTasks(ActiveDOMObject::PageWillBeSuspended);
2196 m_frame->animation().resumeAnimationsForDocument(this);
2200 void Document::disconnectFromFrame()
2205 void Document::destroyRenderTree()
2207 ASSERT(hasLivingRenderTree());
2208 ASSERT(m_pageCacheState != InPageCache);
2210 TemporaryChange<bool> change(m_renderTreeBeingDestroyed, true);
2212 if (this == &topDocument())
2213 clearAXObjectCache();
2215 documentWillBecomeInactive();
2217 if (FrameView* frameView = view())
2218 frameView->detachCustomScrollbars();
2220 #if ENABLE(FULLSCREEN_API)
2221 if (m_fullScreenRenderer)
2222 setFullScreenRenderer(nullptr);
2225 m_hoveredElement = nullptr;
2226 m_focusedElement = nullptr;
2227 m_activeElement = nullptr;
2228 m_focusNavigationStartingNode = nullptr;
2230 if (m_documentElement)
2231 RenderTreeUpdater::tearDownRenderers(*m_documentElement);
2233 clearChildNeedsStyleRecalc();
2235 unscheduleStyleRecalc();
2237 m_renderView = nullptr;
2238 Node::setRenderer(nullptr);
2240 #if ENABLE(TEXT_AUTOSIZING)
2241 // Do this before the arena is cleared, which is needed to deref the RenderStyle on TextAutoSizingKey.
2242 m_textAutoSizedNodes.clear();
2246 void Document::prepareForDestruction()
2248 if (m_hasPreparedForDestruction)
2251 #if ENABLE(IOS_TOUCH_EVENTS)
2252 clearTouchEventHandlersAndListeners();
2255 #if HAVE(ACCESSIBILITY)
2256 // Sub-frames need to cleanup Nodes in the text marker cache when the Document disappears.
2257 if (this != &topDocument()) {
2258 if (AXObjectCache* cache = existingAXObjectCache())
2259 cache->clearTextMarkerNodesInUse(this);
2263 disconnectDescendantFrames();
2264 if (m_domWindow && m_frame)
2265 m_domWindow->willDetachDocumentFromFrame();
2267 if (hasLivingRenderTree())
2268 destroyRenderTree();
2270 if (is<PluginDocument>(*this))
2271 downcast<PluginDocument>(*this).detachFromPluginElement();
2273 #if ENABLE(POINTER_LOCK)
2275 page()->pointerLockController().documentDetached(this);
2278 InspectorInstrumentation::documentDetached(*this);
2280 stopActiveDOMObjects();
2281 m_eventQueue.close();
2282 #if ENABLE(FULLSCREEN_API)
2283 m_fullScreenChangeEventTargetQueue.clear();
2284 m_fullScreenErrorEventTargetQueue.clear();
2289 #if ENABLE(TOUCH_EVENTS)
2290 if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
2291 parentDocument()->didRemoveEventTargetNode(*this);
2294 if (m_wheelEventTargets && m_wheelEventTargets->size() && parentDocument())
2295 parentDocument()->didRemoveEventTargetNode(*this);
2297 if (m_mediaQueryMatcher)
2298 m_mediaQueryMatcher->documentDestroyed();
2300 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2301 if (!m_clientToIDMap.isEmpty() && page()) {
2302 Vector<WebCore::MediaPlaybackTargetClient*> clients;
2303 copyKeysToVector(m_clientToIDMap, clients);
2304 for (auto* client : clients)
2305 removePlaybackTargetPickerClient(*client);
2309 disconnectFromFrame();
2311 m_hasPreparedForDestruction = true;
2314 void Document::removeAllEventListeners()
2316 EventTarget::removeAllEventListeners();
2319 m_domWindow->removeAllEventListeners();
2320 #if ENABLE(IOS_TOUCH_EVENTS)
2321 clearTouchEventHandlersAndListeners();
2323 for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
2324 node->removeAllEventListeners();
2326 #if ENABLE(TOUCH_EVENTS)
2327 m_touchEventTargets = nullptr;
2329 m_wheelEventTargets = nullptr;
2332 void Document::suspendDeviceMotionAndOrientationUpdates()
2334 if (m_areDeviceMotionAndOrientationUpdatesSuspended)
2336 m_areDeviceMotionAndOrientationUpdatesSuspended = true;
2337 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2338 if (m_deviceMotionController)
2339 m_deviceMotionController->suspendUpdates();
2340 if (m_deviceOrientationController)
2341 m_deviceOrientationController->suspendUpdates();
2345 void Document::resumeDeviceMotionAndOrientationUpdates()
2347 if (!m_areDeviceMotionAndOrientationUpdatesSuspended)
2349 m_areDeviceMotionAndOrientationUpdatesSuspended = false;
2350 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
2351 if (m_deviceMotionController)
2352 m_deviceMotionController->resumeUpdates();
2353 if (m_deviceOrientationController)
2354 m_deviceOrientationController->resumeUpdates();
2358 bool Document::shouldBypassMainWorldContentSecurityPolicy() const
2360 JSC::CallFrame* callFrame = JSDOMWindow::commonVM().topCallFrame;
2361 if (callFrame == JSC::CallFrame::noCaller())
2363 DOMWrapperWorld& domWrapperWorld = currentWorld(callFrame);
2364 if (domWrapperWorld.isNormal())
2369 void Document::platformSuspendOrStopActiveDOMObjects()
2372 if (WebThreadCountOfObservedContentModifiers() > 0) {
2373 Frame* frame = this->frame();
2374 if (Page* page = frame ? frame->page() : nullptr)
2375 page->chrome().client().clearContentChangeObservers(frame);
2380 void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2382 ScriptExecutionContext::suspendActiveDOMObjects(why);
2383 suspendDeviceMotionAndOrientationUpdates();
2384 platformSuspendOrStopActiveDOMObjects();
2387 void Document::resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
2389 ScriptExecutionContext::resumeActiveDOMObjects(why);
2390 resumeDeviceMotionAndOrientationUpdates();
2391 // FIXME: For iOS, do we need to add content change observers that were removed in Document::suspendActiveDOMObjects()?
2394 void Document::stopActiveDOMObjects()
2396 ScriptExecutionContext::stopActiveDOMObjects();
2397 platformSuspendOrStopActiveDOMObjects();
2400 void Document::clearAXObjectCache()
2402 ASSERT(&topDocument() == this);
2403 // Clear the cache member variable before calling delete because attempts
2404 // are made to access it during destruction.
2405 m_axObjectCache = nullptr;
2408 static bool hasEverCreatedAnAXObjectCache = false;
2410 AXObjectCache* Document::existingAXObjectCache() const
2412 if (!hasEverCreatedAnAXObjectCache)
2415 Document& topDocument = this->topDocument();
2416 if (!topDocument.hasLivingRenderTree())
2418 return topDocument.m_axObjectCache.get();
2421 AXObjectCache* Document::axObjectCache() const
2423 if (!AXObjectCache::accessibilityEnabled())
2426 // The only document that actually has a AXObjectCache is the top-level
2427 // document. This is because we need to be able to get from any WebCoreAXObject
2428 // to any other WebCoreAXObject on the same page. Using a single cache allows
2429 // lookups across nested webareas (i.e. multiple documents).
2430 Document& topDocument = this->topDocument();
2432 // If the document has already been detached, do not make a new axObjectCache.
2433 if (!topDocument.hasLivingRenderTree())
2436 ASSERT(&topDocument == this || !m_axObjectCache);
2437 if (!topDocument.m_axObjectCache) {
2438 topDocument.m_axObjectCache = std::make_unique<AXObjectCache>(topDocument);
2439 hasEverCreatedAnAXObjectCache = true;
2441 return topDocument.m_axObjectCache.get();
2444 void Document::setVisuallyOrdered()
2446 m_visuallyOrdered = true;
2448 renderView()->mutableStyle().setRTLOrdering(VisualOrder);
2451 Ref<DocumentParser> Document::createParser()
2453 // FIXME: this should probably pass the frame instead
2454 return XMLDocumentParser::create(*this, view());
2457 ScriptableDocumentParser* Document::scriptableDocumentParser() const
2459 return parser() ? parser()->asScriptableDocumentParser() : nullptr;
2462 void Document::open(Document* ownerDocument)
2464 if (m_ignoreOpensDuringUnloadCount)
2467 if (ownerDocument) {
2468 setURL(ownerDocument->url());
2469 setCookieURL(ownerDocument->cookieURL());
2470 setSecurityOriginPolicy(ownerDocument->securityOriginPolicy());
2474 if (ScriptableDocumentParser* parser = scriptableDocumentParser()) {
2475 if (parser->isParsing()) {
2476 // FIXME: HTML5 doesn't tell us to check this, it might not be correct.
2477 if (parser->isExecutingScript())
2480 if (!parser->wasCreatedByScript() && parser->hasInsertionPoint())
2485 if (m_frame->loader().state() == FrameStateProvisional)
2486 m_frame->loader().stopAllLoaders();
2489 removeAllEventListeners();
2491 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
2492 parser->setWasCreatedByScript(true);
2495 m_frame->loader().didExplicitOpen();
2498 void Document::detachParser()
2506 void Document::cancelParsing()
2511 // We have to clear the parser to avoid possibly triggering
2512 // the onload handler when closing as a side effect of a cancel-style
2513 // change, such as opening a new document or closing the window while
2519 void Document::implicitOpen()
2523 setCompatibilityMode(DocumentCompatibilityMode::NoQuirksMode);
2526 m_parser = createParser();
2528 setReadyState(Loading);
2531 HTMLBodyElement* Document::body() const
2533 auto* element = documentElement();
2536 return childrenOfType<HTMLBodyElement>(*element).first();
2539 HTMLElement* Document::bodyOrFrameset() const
2541 // Return the first body or frameset child of the html element.
2542 auto* element = documentElement();
2543 if (!is<HTMLHtmlElement>(element))
2545 for (auto& child : childrenOfType<HTMLElement>(*element)) {
2546 if (is<HTMLBodyElement>(child) || is<HTMLFrameSetElement>(child))
2552 ExceptionOr<void> Document::setBodyOrFrameset(RefPtr<HTMLElement>&& newBody)
2554 if (!is<HTMLBodyElement>(newBody.get()) && !is<HTMLFrameSetElement>(newBody.get()))
2555 return Exception { HIERARCHY_REQUEST_ERR };
2557 auto* currentBody = bodyOrFrameset();
2558 if (newBody == currentBody)
2561 if (!m_documentElement)
2562 return Exception { HIERARCHY_REQUEST_ERR };
2565 return m_documentElement->replaceChild(*newBody, *currentBody);
2566 return m_documentElement->appendChild(*newBody);
2569 Location* Document::location() const
2571 auto* window = domWindow();
2575 return window->location();
2578 HTMLHeadElement* Document::head()
2580 if (auto element = documentElement())
2581 return childrenOfType<HTMLHeadElement>(*element).first();
2585 void Document::close()
2587 // FIXME: We should follow the specification more closely:
2588 // http://www.whatwg.org/specs/web-apps/current-work/#dom-document-close
2590 if (!scriptableDocumentParser() || !scriptableDocumentParser()->wasCreatedByScript() || !scriptableDocumentParser()->isParsing())
2596 void Document::explicitClose()
2598 if (RefPtr<DocumentParser> parser = m_parser)
2602 // Because we have no frame, we don't know if all loading has completed,
2603 // so we just call implicitClose() immediately. FIXME: This might fire
2604 // the load event prematurely <http://bugs.webkit.org/show_bug.cgi?id=14568>.
2609 m_frame->loader().checkCompleted();
2612 void Document::implicitClose()
2614 // If we're in the middle of recalcStyle, we need to defer the close until the style information is accurate and all elements are re-attached.
2615 if (m_inStyleRecalc) {
2616 m_closeAfterStyleRecalc = true;
2620 bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
2621 bool doload = !parsing() && m_parser && !m_processingLoadEvent && !wasLocationChangePending;
2626 // Call to dispatchWindowLoadEvent can blow us from underneath.
2627 Ref<Document> protectedThis(*this);
2629 m_processingLoadEvent = true;
2631 ScriptableDocumentParser* parser = scriptableDocumentParser();
2632 m_wellFormed = parser && parser->wellFormed();
2634 // We have to clear the parser, in case someone document.write()s from the
2635 // onLoad event handler, as in Radar 3206524.
2638 // FIXME: We kick off the icon loader when the Document is done parsing.
2639 // There are earlier opportunities we could start it:
2640 // -When the <head> finishes parsing
2641 // -When any new HTMLLinkElement is inserted into the document
2642 // But those add a dynamic component to the favicon that has UI
2643 // ramifications, and we need to decide what is the Right Thing To Do(tm)
2646 f->loader().icon().startLoader();
2647 f->animation().startAnimationsIfNotSuspended(this);
2649 // FIXME: We shouldn't be dispatching pending events globally on all Documents here.
2650 // For now, only do this when there is a Frame, otherwise this could cause JS reentrancy
2651 // below SVG font parsing, for example. <https://webkit.org/b/136269>
2652 ImageLoader::dispatchPendingBeforeLoadEvents();
2653 ImageLoader::dispatchPendingLoadEvents();
2654 ImageLoader::dispatchPendingErrorEvents();
2655 HTMLLinkElement::dispatchPendingLoadEvents();
2656 HTMLStyleElement::dispatchPendingLoadEvents();
2659 // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
2660 // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
2661 // which is the default, for ='true' its fired at a later time, once all external resources finished loading).
2662 if (svgExtensions())
2663 accessSVGExtensions().dispatchSVGLoadEventToOutermostSVGElements();
2665 dispatchWindowLoadEvent();
2666 enqueuePageshowEvent(PageshowEventNotPersisted);
2667 if (m_pendingStateObject)
2668 enqueuePopstateEvent(WTFMove(m_pendingStateObject));
2671 f->loader().dispatchOnloadEvents();
2673 // An event handler may have removed the frame
2675 m_processingLoadEvent = false;
2679 // Make sure both the initial layout and reflow happen after the onload
2680 // fires. This will improve onload scores, and other browsers do it.
2681 // If they wanna cheat, we can too. -dwh
2683 if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < settings()->layoutInterval()) {
2684 // Just bail out. Before or during the onload we were shifted to another page.
2685 // The old i-Bench suite does this. When this happens don't bother painting or laying out.
2686 m_processingLoadEvent = false;
2687 view()->unscheduleRelayout();
2691 frame()->loader().checkCallImplicitClose();
2693 // We used to force a synchronous display and flush here. This really isn't
2694 // necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
2695 // (if your platform is syncing flushes and limiting them to 60fps).
2696 m_overMinimumLayoutThreshold = true;
2697 if (!ownerElement() || (ownerElement()->renderer() && !ownerElement()->renderer()->needsLayout())) {
2698 updateStyleIfNeeded();
2700 // Always do a layout after loading if needed.
2701 if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
2705 m_processingLoadEvent = false;
2707 #if PLATFORM(COCOA) || PLATFORM(WIN) || PLATFORM(GTK) || PLATFORM(EFL)
2708 if (f && hasLivingRenderTree() && AXObjectCache::accessibilityEnabled()) {
2709 // The AX cache may have been cleared at this point, but we need to make sure it contains an
2710 // AX object to send the notification to. getOrCreate will make sure that an valid AX object
2711 // exists in the cache (we ignore the return value because we don't need it here). This is
2712 // only safe to call when a layout is not in progress, so it can not be used in postNotification.
2714 // This notification is now called AXNewDocumentLoadComplete because there are other handlers that will
2715 // catch new AND page history loads, and that uses AXLoadComplete
2717 axObjectCache()->getOrCreate(renderView());
2718 if (this == &topDocument())
2719 axObjectCache()->postNotification(renderView(), AXObjectCache::AXNewDocumentLoadComplete);
2721 // AXLoadComplete can only be posted on the top document, so if it's a document
2722 // in an iframe that just finished loading, post AXLayoutComplete instead.
2723 axObjectCache()->postNotification(renderView(), AXObjectCache::AXLayoutComplete);
2728 if (svgExtensions())
2729 accessSVGExtensions().startAnimations();
2732 void Document::setParsing(bool b)
2736 if (m_bParsing && !m_sharedObjectPool)
2737 m_sharedObjectPool = std::make_unique<DocumentSharedObjectPool>();
2739 if (!m_bParsing && view() && !view()->needsLayout())
2740 view()->fireLayoutRelatedMilestonesIfNeeded();
2743 bool Document::shouldScheduleLayout()
2745 // This function will only be called when FrameView thinks a layout is needed.
2746 // This enforces a couple extra rules.
2748 // (a) Only schedule a layout once the stylesheets are loaded.
2749 // (b) Only schedule layout once we have a body element.
2751 return (haveStylesheetsLoaded() && bodyOrFrameset())
2752 || (documentElement() && !is<HTMLHtmlElement>(*documentElement()));
2755 bool Document::isLayoutTimerActive()
2757 return view() && view()->layoutPending() && !minimumLayoutDelay().count();
2760 std::chrono::milliseconds Document::minimumLayoutDelay()
2762 if (m_overMinimumLayoutThreshold)
2765 auto elapsed = elapsedTime();
2766 m_overMinimumLayoutThreshold = elapsed > settings()->layoutInterval();
2768 // We'll want to schedule the timer to fire at the minimum layout threshold.
2769 return std::max(0ms, settings()->layoutInterval() - elapsed);
2772 std::chrono::milliseconds Document::elapsedTime() const
2774 auto elapsedTime = std::chrono::steady_clock::now() - m_startTime;
2776 return std::chrono::duration_cast<std::chrono::milliseconds>(elapsedTime);
2779 void Document::write(const SegmentedString& text, Document* ownerDocument)
2781 NestingLevelIncrementer nestingLevelIncrementer(m_writeRecursionDepth);
2783 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > 1) && m_writeRecursionIsTooDeep;
2784 m_writeRecursionIsTooDeep = (m_writeRecursionDepth > cMaxWriteRecursionDepth) || m_writeRecursionIsTooDeep;
2786 if (m_writeRecursionIsTooDeep)
2789 bool hasInsertionPoint = m_parser && m_parser->hasInsertionPoint();
2790 if (!hasInsertionPoint && (m_ignoreOpensDuringUnloadCount || m_ignoreDestructiveWriteCount))
2793 if (!hasInsertionPoint)
2794 open(ownerDocument);
2797 m_parser->insert(text);
2800 void Document::write(const String& text, Document* ownerDocument)
2802 write(SegmentedString(text), ownerDocument);
2805 void Document::writeln(const String& text, Document* ownerDocument)
2807 write(text, ownerDocument);
2808 write("\n", ownerDocument);
2811 std::chrono::milliseconds Document::minimumTimerInterval() const
2813 auto* page = this->page();
2815 return ScriptExecutionContext::minimumTimerInterval();
2816 return page->settings().minimumDOMTimerInterval();
2819 void Document::setTimerThrottlingEnabled(bool shouldThrottle)
2821 if (m_isTimerThrottlingEnabled == shouldThrottle)
2824 m_isTimerThrottlingEnabled = shouldThrottle;
2825 didChangeTimerAlignmentInterval();
2828 std::chrono::milliseconds Document::timerAlignmentInterval(bool hasReachedMaxNestingLevel) const
2830 auto alignmentInterval = ScriptExecutionContext::timerAlignmentInterval(hasReachedMaxNestingLevel);
2832 // Apply Document-level DOMTimer throttling only if timers have reached their maximum nesting level as the Page may still be visible.
2833 if (m_isTimerThrottlingEnabled && hasReachedMaxNestingLevel)
2834 alignmentInterval = std::max(alignmentInterval, DOMTimer::hiddenPageAlignmentInterval());
2836 if (Page* page = this->page())
2837 alignmentInterval = std::max(alignmentInterval, page->domTimerAlignmentInterval());
2839 return alignmentInterval;
2842 EventTarget* Document::errorEventTarget()
2844 return m_domWindow.get();
2847 void Document::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&& callStack)
2849 addMessage(MessageSource::JS, MessageLevel::Error, errorMessage, sourceURL, lineNumber, columnNumber, WTFMove(callStack));
2852 void Document::setURL(const URL& url)
2854 const URL& newURL = url.isEmpty() ? blankURL() : url;
2855 if (newURL == m_url)
2859 m_documentURI = m_url.string();
2863 void Document::updateBaseURL()
2865 URL oldBaseURL = m_baseURL;
2866 // DOM 3 Core: When the Document supports the feature "HTML" [DOM Level 2 HTML], the base URI is computed using
2867 // first the value of the href attribute of the HTML BASE element if any, and the value of the documentURI attribute
2868 // from the Document interface otherwise.
2869 if (!m_baseElementURL.isEmpty())
2870 m_baseURL = m_baseElementURL;
2871 else if (!m_baseURLOverride.isEmpty())
2872 m_baseURL = m_baseURLOverride;
2874 // The documentURI attribute is read-only from JavaScript, but writable from Objective C, so we need to retain
2875 // this fallback behavior. We use a null base URL, since the documentURI attribute is an arbitrary string
2876 // and DOM 3 Core does not specify how it should be resolved.
2877 m_baseURL = URL(ParsedURLString, documentURI());
2880 clearSelectorQueryCache();
2882 if (!m_baseURL.isValid())
2885 if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
2886 // Base URL change changes any relative visited links.
2887 // FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
2888 for (auto& anchor : descendantsOfType<HTMLAnchorElement>(*this))
2889 anchor.invalidateCachedVisitedLinkHash();
2893 void Document::setBaseURLOverride(const URL& url)
2895 m_baseURLOverride = url;
2899 void Document::processBaseElement()
2901 // Find the first href attribute in a base element and the first target attribute in a base element.
2902 const AtomicString* href = nullptr;
2903 const AtomicString* target = nullptr;
2904 auto baseDescendants = descendantsOfType<HTMLBaseElement>(*this);
2905 for (auto& base : baseDescendants) {
2907 const AtomicString& value = base.attributeWithoutSynchronization(hrefAttr);
2908 if (!value.isNull()) {
2915 const AtomicString& value = base.attributeWithoutSynchronization(targetAttr);
2916 if (!value.isNull()) {
2924 // FIXME: Since this doesn't share code with completeURL it may not handle encodings correctly.
2927 String strippedHref = stripLeadingAndTrailingHTMLSpaces(*href);
2928 if (!strippedHref.isEmpty())
2929 baseElementURL = URL(url(), strippedHref);
2931 if (m_baseElementURL != baseElementURL && contentSecurityPolicy()->allowBaseURI(baseElementURL)) {
2932 m_baseElementURL = baseElementURL;
2936 m_baseTarget = target ? *target : nullAtom;
2939 String Document::userAgent(const URL& url) const
2941 return frame() ? frame()->loader().userAgent(url) : String();
2944 void Document::disableEval(const String& errorMessage)
2949 frame()->script().disableEval(errorMessage);
2952 #if ENABLE(INDEXED_DATABASE)
2954 IDBClient::IDBConnectionProxy* Document::idbConnectionProxy()
2956 if (!m_idbConnectionProxy) {
2957 Page* currentPage = page();
2960 m_idbConnectionProxy = ¤tPage->idbConnection().proxy();
2962 return m_idbConnectionProxy.get();
2967 #if ENABLE(WEB_SOCKETS)
2969 SocketProvider* Document::socketProvider()
2971 return m_socketProvider.get();
2976 bool Document::canNavigate(Frame* targetFrame)
2981 // FIXME: We shouldn't call this function without a target frame, but
2982 // fast/forms/submit-to-blank-multiple-times.html depends on this function
2983 // returning true when supplied with a 0 targetFrame.
2987 // Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
2988 if (!isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2991 if (isSandboxed(SandboxNavigation)) {
2992 if (targetFrame->tree().isDescendantOf(m_frame))
2995 const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
2996 if (isSandboxed(SandboxTopNavigation) && targetFrame == &m_frame->tree().top())
2997 reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
2999 printNavigationErrorMessage(targetFrame, url(), reason);
3003 // This is the normal case. A document can navigate its decendant frames,
3004 // or, more generally, a document can navigate a frame if the document is
3005 // in the same origin as any of that frame's ancestors (in the frame
3008 // See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
3009 // historical information about this security check.
3010 if (canAccessAncestor(securityOrigin(), targetFrame))
3013 // Top-level frames are easier to navigate than other frames because they
3014 // display their URLs in the address bar (in most browsers). However, there
3015 // are still some restrictions on navigation to avoid nuisance attacks.
3016 // Specifically, a document can navigate a top-level frame if that frame
3017 // opened the document or if the document is the same-origin with any of
3018 // the top-level frame's opener's ancestors (in the frame hierarchy).
3020 // In both of these cases, the document performing the navigation is in
3021 // some way related to the frame being navigate (e.g., by the "opener"
3022 // and/or "parent" relation). Requiring some sort of relation prevents a
3023 // document from navigating arbitrary, unrelated top-level frames.
3024 if (!targetFrame->tree().parent()) {
3025 if (targetFrame == m_frame->loader().opener())
3028 if (canAccessAncestor(securityOrigin(), targetFrame->loader().opener()))
3032 printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
3036 Frame* Document::findUnsafeParentScrollPropagationBoundary()
3038 Frame* currentFrame = m_frame;
3042 Frame* ancestorFrame = currentFrame->tree().parent();
3044 while (ancestorFrame) {
3045 if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
3046 return currentFrame;
3047 currentFrame = ancestorFrame;
3048 ancestorFrame = ancestorFrame->tree().parent();
3053 void Document::didRemoveAllPendingStylesheet()
3055 m_needsNotifyRemoveAllPendingStylesheet = false;
3057 if (m_pendingSheetLayout == DidLayoutWithPendingSheets) {
3058 m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
3060 renderView()->repaintViewAndCompositedLayers();
3063 if (ScriptableDocumentParser* parser = scriptableDocumentParser())
3064 parser->executeScriptsWaitingForStylesheets();
3066 if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
3067 view()->scrollToFragment(m_url);
3070 bool Document::usesStyleBasedEditability() const
3072 if (m_hasElementUsingStyleBasedEditability)
3075 ASSERT(!m_renderView || !m_renderView->frameView().isPainting());
3076 ASSERT(!m_inStyleRecalc);
3078 auto& styleScope = const_cast<Style::Scope&>(this->styleScope());
3079 styleScope.flushPendingUpdate();
3080 return styleScope.usesStyleBasedEditability();
3083 void Document::setHasElementUsingStyleBasedEditability()
3085 m_hasElementUsingStyleBasedEditability = true;
3088 void Document::processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead)
3090 ASSERT(!equiv.isNull());
3091 ASSERT(!content.isNull());
3093 HttpEquivPolicy policy = httpEquivPolicy();
3094 if (policy != HttpEquivPolicy::Enabled) {
3097 case HttpEquivPolicy::Enabled:
3098 ASSERT_NOT_REACHED();
3100 case HttpEquivPolicy::DisabledBySettings:
3101 reason = "by the embedder.";
3103 case HttpEquivPolicy::DisabledByContentDispositionAttachmentSandbox:
3104 reason = "for documents with Content-Disposition: attachment.";
3107 String message = "http-equiv '" + equiv + "' is disabled " + reason;
3108 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3112 Frame* frame = this->frame();
3114 HTTPHeaderName headerName;
3115 if (!findHTTPHeaderName(equiv, headerName))
3118 switch (headerName) {
3119 case HTTPHeaderName::DefaultStyle:
3120 // The preferred style set has been overridden as per section
3121 // 14.3.2 of the HTML4.0 specification. We need to update the
3122 // sheet used variable and then update our style selector.
3123 // For more info, see the test at:
3124 // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
3126 styleScope().setSelectedStylesheetSetName(content);
3127 styleScope().setPreferredStylesheetSetName(content);
3130 case HTTPHeaderName::Refresh: {
3133 if (frame && parseMetaHTTPEquivRefresh(content, delay, urlString)) {
3135 if (urlString.isEmpty())
3136 completedURL = m_url;
3138 completedURL = completeURL(urlString);
3139 if (!protocolIsJavaScript(completedURL))
3140 frame->navigationScheduler().scheduleRedirect(this, delay, completedURL);
3142 String message = "Refused to refresh " + m_url.stringCenterEllipsizedToLength() + " to a javascript: URL";
3143 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message);
3150 case HTTPHeaderName::SetCookie:
3151 // FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
3152 if (is<HTMLDocument>(*this)) {
3153 // Exception (for sandboxed documents) ignored.
3154 downcast<HTMLDocument>(*this).setCookie(content);
3158 case HTTPHeaderName::ContentLanguage:
3159 setContentLanguage(content);
3162 case HTTPHeaderName::XDNSPrefetchControl:
3163 parseDNSPrefetchControlHeader(content);
3166 case HTTPHeaderName::XFrameOptions:
3168 FrameLoader& frameLoader = frame->loader();
3169 unsigned long requestIdentifier = 0;
3170 if (frameLoader.activeDocumentLoader() && frameLoader.activeDocumentLoader()->mainResourceLoader())
3171 requestIdentifier = frameLoader.activeDocumentLoader()->mainResourceLoader()->identifier();
3173 String message = "The X-Frame-Option '" + content + "' supplied in a <meta> element was ignored. X-Frame-Options may only be provided by an HTTP header sent with the document.";
3174 addConsoleMessage(MessageSource::Security, MessageLevel::Error, message, requestIdentifier);
3178 case HTTPHeaderName::ContentSecurityPolicy:
3179 if (isInDocumentHead)
3180 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::Enforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3183 case HTTPHeaderName::XWebKitCSP:
3184 if (isInDocumentHead)
3185 contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicyHeaderType::PrefixedEnforce, ContentSecurityPolicy::PolicyFrom::HTTPEquivMeta);
3193 void Document::processViewport(const String& features, ViewportArguments::Type origin)
3195 ASSERT(!features.isNull());
3197 if (origin < m_viewportArguments.type)
3200 m_viewportArguments = ViewportArguments(origin);
3202 processFeaturesString(features, [this](StringView key, StringView value) {
3203 setViewportFeature(m_viewportArguments, *this, key, value);
3206 updateViewportArguments();
3209 void Document::updateViewportArguments()
3211 if (page() && frame()->isMainFrame()) {
3213 m_didDispatchViewportPropertiesChanged = true;
3215 page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
3217 page()->chrome().didReceiveDocType(frame());
3224 void Document::processFormatDetection(const String& features)
3226 // FIXME: Find a better place for this function.
3227 processFeaturesString(features, [this](StringView key, StringView value) {
3228 if (equalLettersIgnoringASCIICase(key, "telephone") && equalLettersIgnoringASCIICase(value, "no"))
3229 setIsTelephoneNumberParsingAllowed(false);
3233 void Document::processWebAppOrientations()
3235 if (Page* page = this->page())
3236 page->chrome().client().webAppOrientationsUpdated();
3241 void Document::processReferrerPolicy(const String& policy)
3243 ASSERT(!policy.isNull());
3245 // Documents in a Content-Disposition: attachment sandbox should never send a Referer header,
3246 // even if the document has a meta tag saying otherwise.
3247 if (shouldEnforceContentDispositionAttachmentSandbox())
3251 if (shouldEnforceQuickLookSandbox())
3255 // Note that we're supporting both the standard and legacy keywords for referrer
3256 // policies, as defined by http://www.w3.org/TR/referrer-policy/#referrer-policy-delivery-meta
3257 if (equalLettersIgnoringASCIICase(policy, "no-referrer") || equalLettersIgnoringASCIICase(policy, "never"))
3258 setReferrerPolicy(ReferrerPolicy::Never);
3259 else if (equalLettersIgnoringASCIICase(policy, "unsafe-url") || equalLettersIgnoringASCIICase(policy, "always"))
3260 setReferrerPolicy(ReferrerPolicy::Always);
3261 else if (equalLettersIgnoringASCIICase(policy, "origin"))
3262 setReferrerPolicy(ReferrerPolicy::Origin);
3263 else if (equalLettersIgnoringASCIICase(policy, "no-referrer-when-downgrade") || equalLettersIgnoringASCIICase(policy, "default"))
3264 setReferrerPolicy(ReferrerPolicy::Default);
3266 addConsoleMessage(MessageSource::Rendering, MessageLevel::Error, "Failed to set referrer policy: The value '" + policy + "' is not one of 'no-referrer', 'origin', 'no-referrer-when-downgrade', or 'unsafe-url'. Defaulting to 'no-referrer'.");
3267 setReferrerPolicy(ReferrerPolicy::Never);
3271 MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
3273 if (!hasLivingRenderTree())
3274 return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
3276 HitTestResult result(documentPoint);
3277 renderView()->hitTest(request, result);
3279 if (!request.readOnly())
3280 updateHoverActiveState(request, result.innerElement());
3282 return MouseEventWithHitTestResults(event, result);
3285 // DOM Section 1.1.1
3286 bool Document::childTypeAllowed(NodeType type) const
3289 case ATTRIBUTE_NODE:
3290 case CDATA_SECTION_NODE:
3291 case DOCUMENT_FRAGMENT_NODE:
3296 case PROCESSING_INSTRUCTION_NODE:
3298 case DOCUMENT_TYPE_NODE:
3300 // Documents may contain no more than one of each of these.
3301 // (One Element and one DocumentType.)
3302 for (Node* c = firstChild(); c; c = c->nextSibling())
3303 if (c->nodeType() == type)
3310 bool Document::canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation operation) const
3312 if (operation == AcceptChildOperation::Replace && refChild->nodeType() == newChild.nodeType())
3315 switch (newChild.nodeType()) {
3316 case ATTRIBUTE_NODE:
3317 case CDATA_SECTION_NODE:
3322 case PROCESSING_INSTRUCTION_NODE:
3324 case DOCUMENT_FRAGMENT_NODE: {
3325 bool hasSeenElementChild = false;
3326 for (auto* node = downcast<DocumentFragment>(newChild).firstChild(); node; node = node->nextSibling()) {
3327 if (is<Element>(*node)) {
3328 if (hasSeenElementChild)
3330 hasSeenElementChild = true;
3332 if (!canAcceptChild(*node, refChild, operation))
3337 case DOCUMENT_TYPE_NODE: {
3338 auto* existingDocType = childrenOfType<DocumentType>(*this).first();
3339 if (operation == AcceptChildOperation::Replace) {
3340 // parent has a doctype child that is not child, or an element is preceding child.
3341 if (existingDocType && existingDocType != refChild)
3343 if (refChild->previousElementSibling())
3346 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3347 if (existingDocType)
3349 if ((refChild && refChild->previousElementSibling()) || (!refChild && firstElementChild()))
3354 case ELEMENT_NODE: {
3355 auto* existingElementChild = firstElementChild();
3356 if (operation == AcceptChildOperation::Replace) {
3357 if (existingElementChild && existingElementChild != refChild)
3359 for (auto* child = refChild->nextSibling(); child; child = child->nextSibling()) {
3360 if (is<DocumentType>(*child))
3364 ASSERT(operation == AcceptChildOperation::InsertOrAdd);
3365 if (existingElementChild)
3367 for (auto* child = refChild; child; child = child->nextSibling()) {
3368 if (is<DocumentType>(*child))
3378 Ref<Node> Document::cloneNodeInternal(Document&, CloningOperation type)
3380 Ref<Document> clone = cloneDocumentWithoutChildren();
3381 clone->cloneDataFromDocument(*this);
3383 case CloningOperation::OnlySelf:
3384 case CloningOperation::SelfWithTemplateContent:
3386 case CloningOperation::Everything:
3387 cloneChildNodes(clone);
3390 return WTFMove(clone);
3393 Ref<Document> Document::cloneDocumentWithoutChildren() const
3395 if (isXMLDocument()) {
3396 if (isXHTMLDocument())
3397 return XMLDocument::createXHTML(nullptr, url());
3398 return XMLDocument::create(nullptr, url());
3400 return create(nullptr, url());
3403 void Document::cloneDataFromDocument(const Document& other)
3405 ASSERT(m_url == other.url());
3406 m_baseURL = other.baseURL();
3407 m_baseURLOverride = other.baseURLOverride();
3408 m_documentURI = other.documentURI();
3410 setCompatibilityMode(other.m_compatibilityMode);
3411 setContextDocument(other.contextDocument());
3412 setSecurityOriginPolicy(other.securityOriginPolicy());
3413 overrideMIMEType(other.contentType());
3414 setDecoder(other.decoder());
3417 StyleSheetList& Document::styleSheets()
3419 if (!m_styleSheetList)
3420 m_styleSheetList = StyleSheetList::create(this);
3421 return *m_styleSheetList;
3424 String Document::preferredStylesheetSet() const
3426 return styleScope().preferredStylesheetSetName();
3429 String Document::selectedStylesheetSet() const
3431 return styleScope().selectedStylesheetSetName();
3434 void Document::setSelectedStylesheetSet(const String& aString)
3436 styleScope().setSelectedStylesheetSetName(aString);
3439 void Document::evaluateMediaQueryList()
3441 if (m_mediaQueryMatcher)
3442 m_mediaQueryMatcher->styleResolverChanged();
3444 checkViewportDependentPictures();
3447 void Document::checkViewportDependentPictures()
3449 Vector<HTMLPictureElement*, 16> changedPictures;
3450 HashSet<HTMLPictureElement*>::iterator end = m_viewportDependentPictures.end();
3451 for (HashSet<HTMLPictureElement*>::iterator it = m_viewportDependentPictures.begin(); it != end; ++it) {
3452 if ((*it)->viewportChangeAffectedPicture())
3453 changedPictures.append(*it);
3455 for (auto* picture : changedPictures)
3456 picture->sourcesChanged();
3459 void Document::updateViewportUnitsOnResize()
3461 if (!hasStyleWithViewportUnits())
3464 styleScope().resolver().clearCachedPropertiesAffectedByViewportUnits();
3466 // FIXME: Ideally, we should save the list of elements that have viewport units and only iterate over those.
3467 for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::nextIncludingPseudo(*element)) {
3468 auto* renderer = element->renderer();
3469 if (renderer && renderer->style().hasViewportUnits())
3470 element->invalidateStyle();
3474 void Document::addAudioProducer(MediaProducer* audioProducer)
3476 m_audioProducers.add(audioProducer);
3477 updateIsPlayingMedia();
3480 void Document::removeAudioProducer(MediaProducer* audioProducer)
3482 m_audioProducers.remove(audioProducer);
3483 updateIsPlayingMedia();
3486 void Document::updateIsPlayingMedia(uint64_t sourceElementID)
3488 MediaProducer::MediaStateFlags state = MediaProducer::IsNotPlaying;
3489 for (auto* audioProducer : m_audioProducers)
3490 state |= audioProducer->mediaState();
3492 #if ENABLE(MEDIA_SESSION)
3493 if (HTMLMediaElement* sourceElement = HTMLMediaElement::elementWithID(sourceElementID)) {
3494 if (sourceElement->isPlaying())
3495 state |= MediaProducer::IsSourceElementPlaying;
3497 if (auto* session = sourceElement->session()) {
3498 if (auto* controls = session->controls()) {
3499 if (controls->previousTrackEnabled())
3500 state |= MediaProducer::IsPreviousTrackControlEnabled;
3501 if (controls->nextTrackEnabled())
3502 state |= MediaProducer::IsNextTrackControlEnabled;
3508 if (state == m_mediaState)
3511 m_mediaState = state;
3514 page()->updateIsPlayingMedia(sourceElementID);
3517 void Document::pageMutedStateDidChange()
3519 for (auto* audioProducer : m_audioProducers)
3520 audioProducer->pageMutedStateDidChange();
3523 static bool isNodeInSubtree(Node* node, Node* container, bool amongChildrenOnly)
3525 bool nodeInSubtree = false;
3526 if (amongChildrenOnly)
3527 nodeInSubtree = node->isDescendantOf(container);
3529 nodeInSubtree = (node == container) || node->isDescendantOf(container);
3531 return nodeInSubtree;
3534 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
3536 if (!m_focusedElement || pageCacheState() != NotInPageCache) // If the document is in the page cache, then we don't need to clear out the focused node.
3539 Element* focusedElement = node->treeScope().focusedElement();
3540 if (!focusedElement)
3543 if (isNodeInSubtree(focusedElement, node, amongChildrenOnly)) {
3544 setFocusedElement(nullptr, FocusDirectionNone, FocusRemovalEventsMode::DoNotDispatch);
3545 // Set the focus navigation starting node to the previous focused element so that
3546 // we can fallback to the siblings or parent node for the next search.
3547 // Also we need to call removeFocusNavigationNodeOfSubtree after this function because
3548 // setFocusedElement(nullptr) will reset m_focusNavigationStartingNode.
3549 setFocusNavigationStartingNode(focusedElement);
3553 void Document::hoveredElementDidDetach(Element* element)
3555 if (!m_hoveredElement || element != m_hoveredElement)
3558 m_hoveredElement = element->parentElement();
3559 while (m_hoveredElement && !m_hoveredElement->renderer())
3560 m_hoveredElement = m_hoveredElement->parentElement();
3562 frame()->eventHandler().scheduleHoverStateUpdate();
3565 void Document::elementInActiveChainDidDetach(Element* element)
3567 if (!m_activeElement || element != m_activeElement)
3570 m_activeElement = element->parentElement();
3571 while (m_activeElement && !m_activeElement->renderer())
3572 m_activeElement = m_activeElement->parentElement();
3575 #if ENABLE(DASHBOARD_SUPPORT)
3577 const Vector<AnnotatedRegionValue>& Document::annotatedRegions() const
3579 return m_annotatedRegions;
3582 void Document::setAnnotatedRegions(const Vector<AnnotatedRegionValue>& regions)
3584 m_annotatedRegions = regions;
3585 setAnnotatedRegionsDirty(false);
3590 bool Document::setFocusedElement(Element* element, FocusDirection direction, FocusRemovalEventsMode eventsMode)
3592 RefPtr<Element> newFocusedElement = element;
3593 // Make sure newFocusedElement is actually in this document
3594 if (newFocusedElement && (&newFocusedElement->document() != this))
3597 if (m_focusedElement == newFocusedElement)
3600 if (pageCacheState() != NotInPageCache)
3603 bool focusChangeBlocked = false;
3604 RefPtr<Element> oldFocusedElement = WTFMove(m_focusedElement);
3606 // Remove focus from the existing focus node (if any)
3607 if (oldFocusedElement) {
3608 oldFocusedElement->setFocus(false);
3609 setFocusNavigationStartingNode(nullptr);
3611 if (eventsMode == FocusRemovalEventsMode::Dispatch) {
3612 // Dispatch a change event for form control elements that have been edited.
3613 if (is<HTMLFormControlElement>(*oldFocusedElement)) {
3614 HTMLFormControlElement& formControlElement = downcast<HTMLFormControlElement>(*oldFocusedElement);
3615 if (formControlElement.wasChangedSinceLastFormControlChangeEvent())
3616 formControlElement.dispatchFormControlChangeEvent();
3619 // Dispatch the blur event and let the node do any other blur related activities (important for text fields)
3620 oldFocusedElement->dispatchBlurEvent(newFocusedElement.copyRef());
3622 if (m_focusedElement) {
3623 // handler shifted focus
3624 focusChangeBlocked = true;
3625 newFocusedElement = nullptr;
3628 oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.copyRef()); // DOM level 3 name for the bubbling blur event.
3629 // FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
3630 // on it, probably when <rdar://problem/8503958> is resolved.
3631 oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.copyRef()); // DOM level 2 name for compatibility.
3633 if (m_focusedElement) {
3634 // handler shifted focus
3635 focusChangeBlocked = true;
3636 newFocusedElement = nullptr;
3639 // Match the order in HTMLTextFormControlElement::dispatchBlurEvent.
3640 if (is<HTMLInputElement>(*oldFocusedElement))
3641 downcast<HTMLInputElement>(*oldFocusedElement).endEditing();
3643 page()->chrome().client().elementDidBlur(oldFocusedElement.get());
3644 ASSERT(!m_focusedElement);
3647 if (oldFocusedElement->isRootEditableElement())
3648 frame()->editor().didEndEditing();
3651 if (Widget* oldWidget = widgetForElement(oldFocusedElement.get()))
3652 oldWidget->setFocus(false);
3654 view()->setFocus(false);
3658 if (newFocusedElement && newFocusedElement->isFocusable()) {
3659 if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
3660 // delegate blocks focus change
3661 focusChangeBlocked = true;
3662 goto SetFocusedNodeDone;
3664 // Set focus on the new node
3665 m_focusedElement = newFocusedElement;
3666 setFocusNavigationStartingNode(m_focusedElement.get());
3668 // Dispatch the focus event and let the node do any other focus related activities (important for text fields)
3669 m_focusedElement->dispatchFocusEvent(oldFocusedElement.copyRef(), direction);
3671 if (m_focusedElement != newFocusedElement) {
3672 // handler shifted focus
3673 focusChangeBlocked = true;
3674 goto SetFocusedNodeDone;
3677 m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement.copyRef()); // DOM level 3 bubbling focus event.
3679 if (m_focusedElement != newFocusedElement) {
3680 // handler shifted focus
3681 focusChangeBlocked = true;
3682 goto SetFocusedNodeDone;
3685 // FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
3686 // on it, probably when <rdar://problem/8503958> is m.
3687 m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement.copyRef()); // DOM level 2 for compatibility.
3689 if (m_focusedElement != newFocusedElement) {
3690 // handler shifted focus
3691 focusChangeBlocked = true;
3692 goto SetFocusedNodeDone;
3695 m_focusedElement->setFocus(true);
3697 if (m_focusedElement->isRootEditableElement())
3698 frame()->editor().didBeginEditing();
3700 // eww, I suck. set the qt focus correctly
3701 // ### find a better place in the code for this
3703 Widget* focusWidget = widgetForElement(m_focusedElement.get());
3705 // Make sure a widget has the right size before giving it focus.
3706 // Otherwise, we are testing edge cases of the Widget code.
3707 // Specifically, in WebCore this does not work well for text fields.
3709 // Re-get the widget in case updating the layout changed things.
3710 focusWidget = widgetForElement(m_focusedElement.get());
3713 focusWidget->setFocus(true);
3715 view()->setFocus(true);
3719 if (!focusChangeBlocked && m_focusedElement) {
3720 // Create the AXObject cache in a focus change because GTK relies on it.
3721 if (AXObjectCache* cache = axObjectCache())
3722 cache->handleFocusedUIElementChanged(oldFocusedElement.get(), newFocusedElement.get());
3725 if (!focusChangeBlocked && page())
3726 page()->chrome().focusedElementChanged(m_focusedElement.get());
3729 updateStyleIfNeeded();
3730 return !focusChangeBlocked;
3733 static bool shouldResetFocusNavigationStartingNode(Node& node)
3735 // Setting focus navigation starting node to the following nodes means that we should start
3736 // the search from the beginning of the document.
3737 return is<HTMLHtmlElement>(node) || is<HTMLDocument>(node);
3740 void Document::setFocusNavigationStartingNode(Node* node)
3745 m_focusNavigationStartingNodeIsRemoved = false;
3746 if (!node || shouldResetFocusNavigationStartingNode(*node)) {
3747 m_focusNavigationStartingNode = nullptr;
3751 m_focusNavigationStartingNode = node;
3754 Element* Document::focusNavigationStartingNode(FocusDirection direction) const
3756 if (m_focusedElement) {
3757 if (!m_focusNavigationStartingNode || !m_focusNavigationStartingNode->isDescendantOf(m_focusedElement.get()))
3758 return m_focusedElement.get();
3761 if (!m_focusNavigationStartingNode)
3764 Node* node = m_focusNavigationStartingNode.get();
3766 // When the node was removed from the document tree. This case is not specified in the spec:
3767 // https://html.spec.whatwg.org/multipage/interaction.html#sequential-focus-navigation-starting-point
3768 // Current behaivor is to move the sequential navigation node to / after (based on the focus direction)
3769 // the previous sibling of the removed node.
3770 if (m_focusNavigationStartingNodeIsRemoved) {
3771 Node* nextNode = NodeTraversal::next(*node);
3774 if (direction == FocusDirectionForward)
3775 return ElementTraversal::previous(*nextNode);
3776 if (is<Element>(*nextNode))
3777 return downcast<Element>(nextNode);
3778 return ElementTraversal::next(*nextNode);
3781 if (is<Element>(*node))
3782 return downcast<Element>(node);
3783 if (Element* elementBeforeNextFocusableElement = direction == FocusDirectionForward ? ElementTraversal::previous(*node) : ElementTraversal::next(*node))
3784 return elementBeforeNextFocusableElement;
3785 return node->parentOrShadowHostElement();
3788 void Document::setCSSTarget(Element* n)
3791 m_cssTarget->invalidateStyleForSubtree();
3794 n->invalidateStyleForSubtree();
3797 void Document::registerNodeListForInvalidation(LiveNodeList& list)
3799 m_nodeListAndCollectionCounts[list.invalidationType()]++;
3800 if (!list.isRootedAtDocument())
3802 ASSERT(!list.isRegisteredForInvalidationAtDocument());
3803 list.setRegisteredForInvalidationAtDocument(true);
3804 m_listsInvalidatedAtDocument.add(&list);
3807 void Document::unregisterNodeListForInvalidation(LiveNodeList& list)
3809 m_nodeListAndCollectionCounts[list.invalidationType()]--;
3810 if (!list.isRegisteredForInvalidationAtDocument())
3813 list.setRegisteredForInvalidationAtDocument(false);
3814 ASSERT(m_listsInvalidatedAtDocument.contains(&list));
3815 m_listsInvalidatedAtDocument.remove(&list);
3818 void Document::registerCollection(HTMLCollection& collection)
3820 m_nodeListAndCollectionCounts[collection.invalidationType()]++;
3821 if (collection.isRootedAtDocument())
3822 m_collectionsInvalidatedAtDocument.add(&collection);
3825 void Document::unregisterCollection(HTMLCollection& collection)
3827 ASSERT(m_nodeListAndCollectionCounts[collection.invalidationType()]);
3828 m_nodeListAndCollectionCounts[collection.invalidationType()]--;
3829 if (!collection.isRootedAtDocument())
3832 m_collectionsInvalidatedAtDocument.remove(&collection);
3835 void Document::collectionCachedIdNameMap(const HTMLCollection& collection)
3837 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3838 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]++;
3841 void Document::collectionWillClearIdNameMap(const HTMLCollection& collection)
3843 ASSERT_UNUSED(collection, collection.hasNamedElementCache());
3844 ASSERT(m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]);
3845 m_nodeListAndCollectionCounts[InvalidateOnIdNameAttrChange]--;
3848 void Document::attachNodeIterator(NodeIterator* ni)
3850 m_nodeIterators.add(ni);
3853 void Document::detachNodeIterator(NodeIterator* ni)
3855 // The node iterator can be detached without having been attached if its root node didn't have a document
3856 // when the iterator was created, but has it now.
3857 m_nodeIterators.remove(ni);
3860 void Document::moveNodeIteratorsToNewDocument(Node* node, Document* newDocument)
3862 Vector<NodeIterator*> nodeIterators;
3863 copyToVector(m_nodeIterators, nodeIterators);
3864 for (auto* it : nodeIterators) {
3865 if (&it->root() == node) {
3866 detachNodeIterator(it);
3867 newDocument->attachNodeIterator(it);
3872 void Document::updateRangesAfterChildrenChanged(ContainerNode& container)
3874 for (auto* range : m_ranges)
3875 range->nodeChildrenChanged(container);
3878 void Document::nodeChildrenWillBeRemoved(ContainerNode& container)
3880 NoEventDispatchAssertion assertNoEventDispatch;
3882 removeFocusedNodeOfSubtree(&container, true /* amongChildrenOnly */);
3883 removeFocusNavigationNodeOfSubtree(container, true /* amongChildrenOnly */);
3885 #if ENABLE(FULLSCREEN_API)
3886 removeFullScreenElementOfSubtree(&container, true /* amongChildrenOnly */);
3889 for (auto* range : m_ranges)
3890 range->nodeChildrenWillBeRemoved(container);
3892 for (auto* it : m_nodeIterators) {
3893 for (Node* n = container.firstChild(); n; n = n->nextSibling())
3894 it->nodeWillBeRemoved(*n);
3897 if (Frame* frame = this->frame()) {
3898 for (Node* n = container.firstChild(); n; n = n->nextSibling()) {
3899 frame->eventHandler().nodeWillBeRemoved(*n);
3900 frame->selection().nodeWillBeRemoved(*n);
3901 frame->page()->dragCaretController().nodeWillBeRemoved(*n);
3905 if (m_markers->hasMarkers()) {
3906 for (Text* textNode = TextNodeTraversal::firstChild(container); textNode; textNode = TextNodeTraversal::nextSibling(*textNode))
3907 m_markers->removeMarkers(textNode);
3911 void Document::nodeWillBeRemoved(Node& n)
3913 NoEventDispatchAssertion assertNoEventDispatch;
3915 removeFocusedNodeOfSubtree(&n);
3916 removeFocusNavigationNodeOfSubtree(n);
3918 #if ENABLE(FULLSCREEN_API)
3919 removeFullScreenElementOfSubtree(&n);
3922 for (auto* it : m_nodeIterators)
3923 it->nodeWillBeRemoved(n);
3925 for (auto* range : m_ranges)
3926 range->nodeWillBeRemoved(n);
3928 if (Frame* frame = this->frame()) {
3929 frame->eventHandler().nodeWillBeRemoved(n);
3930 frame->selection().nodeWillBeRemoved(n);
3931 frame->page()->dragCaretController().nodeWillBeRemoved(n);
3935 m_markers->removeMarkers(&n);
3938 static Node* fallbackFocusNavigationStartingNodeAfterRemoval(Node& node)
3940 return node.previousSibling() ? node.previousSibling() : node.parentNode();
3943 void Document::removeFocusNavigationNodeOfSubtree(Node& node, bool amongChildrenOnly)
3945 if (!m_focusNavigationStartingNode)
3948 if (isNodeInSubtree(m_focusNavigationStartingNode.get(), &node, amongChildrenOnly)) {
3949 m_focusNavigationStartingNode = amongChildrenOnly ? &node : fallbackFocusNavigationStartingNodeAfterRemoval(node);
3950 m_focusNavigationStartingNodeIsRemoved = true;
3954 void Document::textInserted(Node* text, unsigned offset, unsigned length)
3956 if (!m_ranges.isEmpty()) {
3957 for (auto* range : m_ranges)
3958 range->textInserted(text, offset, length);
3961 // Update the markers for spelling and grammar checking.
3962 m_markers->shiftMarkers(text, offset, length);
3965 void Document::textRemoved(Node* text, unsigned offset, unsigned length)
3967 if (!m_ranges.isEmpty()) {
3968 for (auto* range : m_ranges)
3969 range->textRemoved(text, offset, length);
3972 // Update the markers for spelling and grammar checking.
3973 m_markers->removeMarkers(text, offset, length);
3974 m_markers->shiftMarkers(text, offset + length, 0 - length);
3977 void Document::textNodesMerged(Text* oldNode, unsigned offset)
3979 if (!m_ranges.isEmpty()) {
3980 NodeWithIndex oldNodeWithIndex(oldNode);
3981 for (auto* range : m_ranges)
3982 range->textNodesMerged(oldNodeWithIndex, offset);
3985 // FIXME: This should update markers for spelling and grammar checking.
3988 void Document::textNodeSplit(Text* oldNode)
3990 for (auto* range : m_ranges)
3991 range->textNodeSplit(oldNode);
3993 // FIXME: This should update markers for spelling and grammar checking.
3996 void Document::createDOMWindow()
3999 ASSERT(!m_domWindow);
4001 m_domWindow = DOMWindow::create(this);
4003 ASSERT(m_domWindow->document() == this);
4004 ASSERT(m_domWindow->frame() == m_frame);
4007 void Document::takeDOMWindowFrom(Document* document)
4010 ASSERT(!m_domWindow);
4011 ASSERT(document->m_domWindow);
4012 // A valid DOMWindow is needed by CachedFrame for its documents.
4013 ASSERT(pageCacheState() == NotInPageCache);
4015 m_domWindow = WTFMove(document->m_domWindow);
4016 m_domWindow->didSecureTransitionTo(this);
4018 ASSERT(m_domWindow->document() == this);
4019 ASSERT(m_domWindow->frame() == m_frame);
4022 Document& Document::contextDocument() const
4024 if (m_contextDocument)
4025 return *m_contextDocument.get();
4026 return const_cast<Document&>(*this);
4029 void Document::setAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
4031 setAttributeEventListener(eventType, JSLazyEventListener::create(*this, attributeName, attributeValue));
4034 void Document::setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener)
4038 m_domWindow->setAttributeEventListener(eventType, listener);
4041 void Document::setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& attributeValue)
4045 setWindowAttributeEventListener(eventType, JSLazyEventListener::create(*m_domWindow, attributeName, attributeValue));
4048 EventListener* Document::getWindowAttributeEventListener(const AtomicString& eventType)
4052 return m_domWindow->attributeEventListener(eventType);
4055 void Document::dispatchWindowEvent(Event& event, EventTarget* target)
4057 ASSERT_WITH_SECURITY_IMPLICATION(!NoEventDispatchAssertion::isEventDispatchForbidden());
4060 m_domWindow->dispatchEvent(event, target);
4063 void Document::dispatchWindowLoadEvent()
4065 ASSERT_WITH_SECURITY_IMPLICATION(!NoEventDispatchAssertion::isEventDispatchForbidden());
4068 m_domWindow->dispatchLoadEvent();
4069 m_loadEventFinished = true;
4070 m_cachedResourceLoader->documentDidFinishLoadEvent();
4073 void Document::enqueueWindowEvent(Ref<Event>&& event)
4075 event->setTarget(m_domWindow.get());
4076 m_eventQueue.enqueueEvent(WTFMove(event));
4079 void Document::enqueueDocumentEvent(Ref<Event>&& event)
4081 event->setTarget(this);
4082 m_eventQueue.enqueueEvent(WTFMove(event));
4085 void Document::enqueueOverflowEvent(Ref<Event>&& event)
4087 m_eventQueue.enqueueEvent(WTFMove(event));
4090 ExceptionOr<Ref<Event>> Document::createEvent(const String& type)
4092 // Please do *not* add new event classes to this function unless they are
4093 // required for compatibility of some actual legacy web content.
4095 // This mechanism is superceded by use of event constructors.
4096 // That is what we should use for any new event classes.
4098 // The following strings are the ones from the DOM specification
4099 // <https://dom.spec.whatwg.org/#dom-document-createevent>.
4101 if (equalLettersIgnoringASCIICase(type, "customevent"))
4102 return Ref<Event> { CustomEvent::create() };
4103 if (equalLettersIgnoringASCIICase(type, "event") || equalLettersIgnoringASCIICase(type, "events") || equalLettersIgnoringASCIICase(type, "htmlevents"))
4104 return Event::createForBindings();
4105 if (equalLettersIgnoringASCIICase(type, "keyboardevent") || equalLettersIgnoringASCIICase(type, "keyboardevents"))
4106 return Ref<Event> { KeyboardEvent::createForBindings() };
4107 if (equalLettersIgnoringASCIICase(type, "messageevent"))
4108 return Ref<Event> { MessageEvent::createForBindings() };
4109 if (equalLettersIgnoringASCIICase(type, "mouseevent") || equalLettersIgnoringASCIICase(type, "mouseevents"))
4110 return Ref<Event> { MouseEvent::createForBindings() };
4111 if (equalLettersIgnoringASCIICase(type, "uievent") || equalLettersIgnoringASCIICase(type, "uievents"))
4112 return Ref<Event> { UIEvent::createForBindings() };
4113 if (equalLettersIgnoringASCIICase(type, "popstateevent"))
4114 return Ref<Event> { PopStateEvent::createForBindings() };
4116 #if ENABLE(TOUCH_EVENTS)
4117 if (equalLettersIgnoringASCIICase(type, "touchevent"))
4118 return Ref<Event> { TouchEvent::createForBindings() };
4121 // The following string comes from the SVG specifications
4122 // <http://www.w3.org/TR/SVG/script.html#InterfaceSVGZoomEvent>
4123 // <http://www.w3.org/TR/SVG2/interact.html#InterfaceSVGZoomEvent>.
4124 // However, since there is no provision for initializing the event once it is created,
4125 // there is no practical value in this feature.
4127 if (equalLettersIgnoringASCIICase(type, "svgzoomevents"))
4128 return Ref<Event> { SVGZoomEvent::createForBindings() };
4130 // The following strings are for event classes where WebKit supplies an init function.
4131 // These strings are not part of the DOM specification and we would like to eliminate them.
4132 // However, we currently include these because we have concerns about backward compatibility.
4134 // FIXME: For each of the strings below, prove there is no content depending on it and remove
4135 // both the string and the corresponding init function for that class.
4137 if (equalLettersIgnoringASCIICase(type, "compositionevent"))
4138 return Ref<Event> { CompositionEvent::createForBindings() };
4139 if (equalLettersIgnoringASCIICase(type, "hashchangeevent"))
4140 return Ref<Event> { HashChangeEvent::createForBindings() };
4141 if (equalLettersIgnoringASCIICase(type, "mutationevent") || equalLettersIgnoringASCIICase(type, "mutationevents"))
4142 return Ref<Event> { MutationEvent::createForBindings() };
4143 if (equalLettersIgnoringASCIICase(type, "overflowevent"))
4144 return Ref<Event> { OverflowEvent::createForBindings() };
4145 if (equalLettersIgnoringASCIICase(type, "storageevent"))
4146 return Ref<Event> { StorageEvent::createForBindings() };
4147 if (equalLettersIgnoringASCIICase(type, "textevent"))
4148 return Ref<Event> { TextEvent::createForBindings() };
4149 if (equalLettersIgnoringASCIICase(type, "wheelevent"))
4150 return Ref<Event> { WheelEvent::createForBindings() };
4152 #if ENABLE(DEVICE_ORIENTATION)
4153 if (equalLettersIgnoringASCIICase(type, "devicemotionevent"))
4154 return Ref<Event> { DeviceMotionEvent::createForBindings() };
4155 if (equalLettersIgnoringASCIICase(type, "deviceorientationevent"))
4156 return Ref<Event> { DeviceOrientationEvent::createForBindings() };
4159 return Exception { NOT_SUPPORTED_ERR };
4162 bool Document::hasListenerTypeForEventType(PlatformEvent::Type eventType) const
4164 switch (eventType) {
4165 case PlatformEvent::MouseForceChanged:
4166 return m_listenerTypes & Document::FORCECHANGED_LISTENER;
4167 case PlatformEvent::MouseForceDown:
4168 return m_listenerTypes & Document::FORCEDOWN_LISTENER;
4169 case PlatformEvent::MouseForceUp:
4170 return m_listenerTypes & Document::FORCEUP_LISTENER;
4171 case PlatformEvent::MouseScroll:
4172 return m_listenerTypes & Document::SCROLL_LISTENER;
4178 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
4180 if (eventType == eventNames().DOMSubtreeModifiedEvent)
4181 addListenerType(DOMSUBTREEMODIFIED_LISTENER);
4182 else if (eventType == eventNames().DOMNodeInsertedEvent)
4183 addListenerType(DOMNODEINSERTED_LISTENER);
4184 else if (eventType == eventNames().DOMNodeRemovedEvent)
4185 addListenerType(DOMNODEREMOVED_LISTENER);
4186 else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
4187 addListenerType(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
4188 else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
4189 addListenerType(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
4190 else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
4191 addListenerType(DOMCHARACTERDATAMODIFIED_LISTENER);
4192 else if (eventType == eventNames().overflowchangedEvent)
4193 addListenerType(OVERFLOWCHANGED_LISTENER);
4194 else if (eventType == eventNames().webkitAnimationStartEvent || eventType == eventNames().animationstartEvent)
4195 addListenerType(ANIMATIONSTART_LISTENER);
4196 else if (eventType == eventNames().webkitAnimationEndEvent || eventType == eventNames().animationendEvent)
4197 addListenerType(ANIMATIONEND_LISTENER);
4198 else if (eventType == eventNames().webkitAnimationIterationEvent || eventType == eventNames().animationiterationEvent)
4199 addListenerType(ANIMATIONITERATION_LISTENER);
4200 else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent)
4201 addListenerType(TRANSITIONEND_LISTENER);
4202 else if (eventType == eventNames().beforeloadEvent)
4203 addListenerType(BEFORELOAD_LISTENER);
4204 else if (eventType == eventNames().scrollEvent)
4205 addListenerType(SCROLL_LISTENER);
4206 else if (eventType == eventNames().webkitmouseforcewillbeginEvent)
4207 addListenerType(FORCEWILLBEGIN_LISTENER);
4208 else if (eventType == eventNames().webkitmouseforcechangedEvent)
4209 addListenerType(FORCECHANGED_LISTENER);
4210 else if (eventType == eventNames().webkitmouseforcedownEvent)
4211 addListenerType(FORCEDOWN_LISTENER);
4212 else if (eventType == eventNames().webkitmouseforceupEvent)
4213 addListenerType(FORCEUP_LISTENER);
4216 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
4221 HTMLFrameOwnerElement* Document::ownerElement() const
4225 return frame()->ownerElement();
4228 ExceptionOr<String> Document::cookie()
4230 if (page() && !page()->settings().cookieEnabled())
4233 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4234 // INVALID_STATE_ERR exception on getting if the Document has no
4235 // browsing context.
4237 if (!securityOrigin()->canAccessCookies())
4238 return Exception { SECURITY_ERR };
4240 URL cookieURL = this->cookieURL();
4241 if (cookieURL.isEmpty())
4244 if (!isDOMCookieCacheValid())
4245 setCachedDOMCookies(cookies(*this, cookieURL));
4247 return String { cachedDOMCookies() };
4250 ExceptionOr<void> Document::setCookie(const String& value)
4252 if (page() && !page()->settings().cookieEnabled())
4255 // FIXME: The HTML5 DOM spec states that this attribute can raise an
4256 // INVALID_STATE_ERR exception on setting if the Document has no
4257 // browsing context.
4259 if (!securityOrigin()->canAccessCookies())
4260 return Exception { SECURITY_ERR };
4262 URL cookieURL = this->cookieURL();
4263 if (cookieURL.isEmpty())
4266 invalidateDOMCookieCache();
4267 setCookies(*this, cookieURL, value);
4271 String Document::referrer() const
4274 return frame()->loader().referrer();
4278 String Document::origin() const
4280 return SecurityOriginData::fromSecurityOrigin(*securityOrigin()).databaseIdentifier();
4283 String Document::domain() const
4285 return securityOrigin()->domain();
4288 ExceptionOr<void> Document::setDomain(const String& newDomain)
4290 if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol()))
4291 return Exception { SECURITY_ERR };
4293 // Both NS and IE specify that changing the domain is only allowed when
4294 // the new domain is a suffix of the old domain.
4296 // FIXME: We should add logging indicating why a domain was not allowed.
4298 String oldDomain = domain();
4300 // If the new domain is the same as the old domain, still call
4301 // securityOrigin()->setDomainForDOM. This will change the
4302 // security check behavior. For example, if a page loaded on port 8000
4303 // assigns its current domain using document.domain, the page will