1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_dom_Document_h___
8 #define mozilla_dom_Document_h___
15 #include "ErrorList.h"
16 #include "MainThreadUtils.h"
18 #include "imgIRequest.h"
19 #include "js/RootingAPI.h"
20 #include "js/friend/DOMProxy.h"
21 #include "mozilla/AlreadyAddRefed.h"
22 #include "mozilla/Assertions.h"
23 #include "mozilla/Attributes.h"
24 #include "mozilla/BasicEvents.h"
25 #include "mozilla/BitSet.h"
26 #include "mozilla/OriginTrials.h"
27 #include "mozilla/ContentBlockingNotifier.h"
28 #include "mozilla/CORSMode.h"
29 #include "mozilla/CallState.h"
30 #include "mozilla/FlushType.h"
31 #include "mozilla/FunctionRef.h"
32 #include "mozilla/HashTable.h"
33 #include "mozilla/LinkedList.h"
34 #include "mozilla/Maybe.h"
35 #include "mozilla/MozPromise.h"
36 #include "mozilla/NotNull.h"
37 #include "mozilla/PointerLockManager.h"
38 #include "mozilla/PreloadService.h"
39 #include "mozilla/RefPtr.h"
40 #include "mozilla/Result.h"
41 #include "mozilla/SegmentedVector.h"
42 #include "mozilla/StorageAccessAPIHelper.h"
43 #include "mozilla/TaskCategory.h"
44 #include "mozilla/TimeStamp.h"
45 #include "mozilla/UniquePtr.h"
46 #include "mozilla/UseCounter.h"
47 #include "mozilla/WeakPtr.h"
48 #include "mozilla/css/StylePreloadKind.h"
49 #include "mozilla/dom/AnimationFrameProvider.h"
50 #include "mozilla/dom/DispatcherTrait.h"
51 #include "mozilla/dom/DocumentOrShadowRoot.h"
52 #include "mozilla/dom/Element.h"
53 #include "mozilla/dom/EventTarget.h"
54 #include "mozilla/dom/Nullable.h"
55 #include "mozilla/dom/TreeOrderedArray.h"
56 #include "mozilla/dom/ViewportMetaData.h"
57 #include "mozilla/glean/GleanMetrics.h"
59 #include "nsCOMArray.h"
61 #include "nsClassHashtable.h"
62 #include "nsCompatibility.h"
63 #include "nsContentListDeclarations.h"
64 #include "nsCycleCollectionParticipant.h"
65 #include "nsTHashMap.h"
67 #include "nsGkAtoms.h"
68 #include "nsHashKeys.h"
69 #include "nsIChannel.h"
70 #include "nsIChannelEventSink.h"
71 #include "nsIContentViewer.h"
73 #include "nsIInterfaceRequestor.h"
74 #include "nsILoadContext.h"
75 #include "nsILoadGroup.h"
76 #include "nsILoadInfo.h"
78 #include "nsIObserver.h"
79 #include "nsIParser.h"
80 #include "nsIPrincipal.h"
81 #include "nsIProgressEventSink.h"
82 #include "nsIRadioGroupContainer.h"
83 #include "nsIReferrerInfo.h"
84 #include "nsIRequestObserver.h"
85 #include "nsIScriptObjectPrincipal.h"
86 #include "nsIStreamListener.h"
87 #include "nsISupports.h"
88 #include "nsISupportsUtils.h"
89 #include "nsITransportSecurityInfo.h"
91 #include "nsIWeakReferenceUtils.h"
92 #include "nsLiteralString.h"
93 #include "nsPIDOMWindow.h"
94 #include "nsPropertyTable.h"
95 #include "nsRefPtrHashtable.h"
98 #include "nsTHashSet.h"
99 #include "nsTLiteralString.h"
100 #include "nsTObserverArray.h"
101 #include "nsThreadUtils.h"
102 #include "nsURIHashKey.h"
103 #include "nsViewportInfo.h"
104 #include "nsWeakReference.h"
105 #include "nsWindowSizes.h"
106 #include "nsXULElement.h"
109 // XXX We need to include this here to ensure that DefaultDeleter for Servo
110 // types is specialized before the template is instantiated. Probably, this
111 // should be included at some other place already that's generated by cbindgen.
112 #include "mozilla/ServoBindingTypes.h"
114 // windows.h #defines CreateEvent
119 #ifdef MOZILLA_INTERNAL_API
120 # include "mozilla/dom/DocumentBinding.h"
124 class ElementCreationOptionsOrString
;
126 } // namespace mozilla
127 #endif // MOZILLA_INTERNAL_API
129 class InfallibleAllocPolicy
;
133 class gfxUserFontSet
;
134 class mozIDOMWindowProxy
;
135 class nsCachableElementsByNameNodeList
;
136 class nsCommandManager
;
138 class nsCycleCollectionTraversalCallback
;
139 class nsDOMCaretPosition
;
140 class nsDOMNavigationTiming
;
143 class nsFrameLoaderOwner
;
144 class nsGenericHTMLElement
;
145 class nsGlobalWindowInner
;
146 class nsHTMLDocument
;
147 class nsHtml5TreeOpExecutor
;
149 class nsIAsyncVerifyRedirectCallback
;
150 class nsIBFCacheEntry
;
152 class nsIContentSecurityPolicy
;
153 class nsIContentSink
;
154 class nsICookieJarSettings
;
155 class nsIDOMXULCommandDispatcher
;
157 class nsIDocShellTreeItem
;
158 class nsIDocumentEncoder
;
159 class nsIDocumentObserver
;
160 class nsIEventTarget
;
162 class nsIGlobalObject
;
163 class nsIHTMLCollection
;
164 class nsIInputStream
;
165 class nsILayoutHistoryState
;
166 class nsIObjectLoadingContent
;
167 class nsIPermissionDelegateHandler
;
168 class nsIRadioVisitor
;
171 class nsIScriptGlobalObject
;
172 class nsISecurityConsoleMessage
;
173 class nsISerialEventTarget
;
174 class nsIStructuredCloneContainer
;
176 class nsNodeInfoManager
;
177 class nsPIWindowRoot
;
180 class nsSimpleContentList
;
183 class nsXULPrototypeDocument
;
188 class AbstractThread
;
189 class AttributeStyles
;
195 class EventListenerManager
;
196 class FullscreenExit
;
197 class FullscreenRequest
;
199 struct LangGroupFontPrefs
;
200 class PendingAnimationTracker
;
201 class PermissionDelegateHandler
;
203 class ScrollTimelineAnimationTracker
;
205 enum class StyleOrigin
: uint8_t;
206 class SMILAnimationController
;
207 enum class StyleCursorKind
: uint8_t;
208 class SVGContextPaint
;
209 enum class ColorScheme
: uint8_t;
210 enum class StyleRuleChangeKind
: uint32_t;
211 struct StyleUseCounters
;
223 class AnonymousContent
;
225 class XULBroadcastManager
;
227 class BrowserBridgeChild
;
228 class ChromeObserver
;
235 class DocumentFragment
;
236 class DocumentTimeline
;
238 class DOMImplementation
;
239 class DOMIntersectionObserver
;
243 struct FailedCertSecurityInfo
;
246 class FrameRequestCallback
;
248 class HighlightRegistry
;
249 class HTMLAllCollection
;
250 class HTMLBodyElement
;
251 class HTMLInputElement
;
252 class HTMLMetaElement
;
253 class HTMLDialogElement
;
254 class HTMLSharedElement
;
255 class HTMLImageElement
;
256 struct LifecycleCallbackArgs
;
259 class MediaQueryList
;
264 enum class OrientationType
: uint8_t;
265 class ProcessingInstruction
;
269 class ServiceWorkerDescriptor
;
279 enum class ViewportFitType
: uint8_t;
281 class WindowGlobalChild
;
282 class WindowProxyHolder
;
284 class WorkerDocumentListener
;
285 class XPathEvaluator
;
286 class XPathExpression
;
287 class XPathNSResolver
;
289 class BrowsingContext
;
291 class nsUnblockOnloadEvent
;
293 template <typename
, typename
>
294 class CallbackObjectHolder
;
296 enum class CallerType
: uint32_t;
299 NOT_ALLOWED
= 1 << 0, // Status 0
300 EVENT_HANDLING_SUPPRESSED
= 1 << 1, // Status 1
301 SUSPENDED
= 1 << 2, // Status 2
302 UNLOAD_LISTENER
= 1 << 3, // Status 3
303 REQUEST
= 1 << 4, // Status 4
304 ACTIVE_GET_USER_MEDIA
= 1 << 5, // Status 5
305 ACTIVE_PEER_CONNECTION
= 1 << 6, // Status 6
306 CONTAINS_EME_CONTENT
= 1 << 7, // Status 7
307 CONTAINS_MSE_CONTENT
= 1 << 8, // Status 8
308 HAS_ACTIVE_SPEECH_SYNTHESIS
= 1 << 9, // Status 9
309 HAS_USED_VR
= 1 << 10, // Status 10
310 CONTAINS_REMOTE_SUBFRAMES
= 1 << 11, // Status 11
311 NOT_ONLY_TOPLEVEL_IN_BCG
= 1 << 12, // Status 12
312 ABOUT_PAGE
= 1 << 13, // Status 13
313 RESTORING
= 1 << 14, // Status 14
314 BEFOREUNLOAD_LISTENER
= 1 << 15, // Status 15
315 ACTIVE_LOCK
= 1 << 16, // Status 16
316 ACTIVE_WEBTRANSPORT
= 1 << 17, // Status 17
320 } // namespace mozilla
322 namespace mozilla::net
{
323 class ChannelEventQueue
;
324 class EarlyHintConnectArgs
;
325 } // namespace mozilla::net
327 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
328 #define NS_IDOCUMENT_IID \
330 0xce1f7627, 0x7109, 0x4977, { \
331 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
335 namespace mozilla::dom
{
338 class DOMStyleSheetSetList
;
339 class ResizeObserver
;
340 class ResizeObserverController
;
341 class PostMessageEvent
;
343 #define DEPRECATED_OPERATION(_op) e##_op,
344 enum class DeprecatedOperations
: uint16_t {
345 #include "nsDeprecatedOperationList.h"
346 eDeprecatedOperationCount
348 #undef DEPRECATED_OPERATION
350 class ExternalResourceMap
{
351 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
355 * A class that represents an external resource load that has begun but
356 * doesn't have a document yet. Observers can be registered on this object,
357 * and will be notified after the document is created. Observers registered
358 * after the document has been created will NOT be notified. When observers
359 * are notified, the subject will be the newly-created document, the topic
360 * will be "external-resource-document-created", and the data will be null.
361 * If document creation fails for some reason, observers will still be
362 * notified, with a null document pointer.
364 class ExternalResourceLoad
: public nsISupports
{
366 virtual ~ExternalResourceLoad() = default;
368 void AddObserver(nsIObserver
* aObserver
) {
369 MOZ_ASSERT(aObserver
, "Must have observer");
370 mObservers
.AppendElement(aObserver
);
373 const nsTArray
<nsCOMPtr
<nsIObserver
>>& Observers() { return mObservers
; }
376 AutoTArray
<nsCOMPtr
<nsIObserver
>, 8> mObservers
;
379 ExternalResourceMap();
382 * Request an external resource document. This does exactly what
383 * Document::RequestExternalResource is documented to do.
385 Document
* RequestResource(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
386 nsINode
* aRequestingNode
,
387 Document
* aDisplayDocument
,
388 ExternalResourceLoad
** aPendingLoad
);
391 * Enumerate the resource documents. See
392 * Document::EnumerateExternalResources.
394 void EnumerateResources(SubDocEnumFunc aCallback
);
397 * Traverse ourselves for cycle-collection
399 void Traverse(nsCycleCollectionTraversalCallback
* aCallback
) const;
402 * Shut ourselves down (used for cycle-collection unlink), as well
403 * as for document destruction.
406 mPendingLoads
.Clear();
408 mHaveShutDown
= true;
411 bool HaveShutDown() const { return mHaveShutDown
; }
413 // Needs to be public so we can traverse them sanely
414 struct ExternalResource
{
416 RefPtr
<Document
> mDocument
;
417 nsCOMPtr
<nsIContentViewer
> mViewer
;
418 nsCOMPtr
<nsILoadGroup
> mLoadGroup
;
421 // Hide all our viewers
424 // Show all our viewers
428 class PendingLoad
: public ExternalResourceLoad
, public nsIStreamListener
{
429 ~PendingLoad() = default;
432 explicit PendingLoad(Document
* aDisplayDocument
)
433 : mDisplayDocument(aDisplayDocument
) {}
436 NS_DECL_NSISTREAMLISTENER
437 NS_DECL_NSIREQUESTOBSERVER
440 * Start aURI loading. This will perform the necessary security checks and
443 nsresult
StartLoad(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
444 nsINode
* aRequestingNode
);
446 * Set up an nsIContentViewer based on aRequest. This is guaranteed to
447 * put null in *aViewer and *aLoadGroup on all failures.
449 nsresult
SetupViewer(nsIRequest
* aRequest
, nsIContentViewer
** aViewer
,
450 nsILoadGroup
** aLoadGroup
);
453 RefPtr
<Document
> mDisplayDocument
;
454 nsCOMPtr
<nsIStreamListener
> mTargetListener
;
455 nsCOMPtr
<nsIURI
> mURI
;
457 friend class PendingLoad
;
459 class LoadgroupCallbacks final
: public nsIInterfaceRequestor
{
460 ~LoadgroupCallbacks() = default;
463 explicit LoadgroupCallbacks(nsIInterfaceRequestor
* aOtherCallbacks
)
464 : mCallbacks(aOtherCallbacks
) {}
466 NS_DECL_NSIINTERFACEREQUESTOR
468 // The only reason it's safe to hold a strong ref here without leaking is
469 // that the notificationCallbacks on a loadgroup aren't the docshell itself
470 // but a shim that holds a weak reference to the docshell.
471 nsCOMPtr
<nsIInterfaceRequestor
> mCallbacks
;
473 // Use shims for interfaces that docshell implements directly so that we
474 // don't hand out references to the docshell. The shims should all allow
475 // getInterface back on us, but other than that each one should only
476 // implement one interface.
478 // XXXbz I wish we could just derive the _allcaps thing from _i
479 #define DECL_SHIM(_i, _allcaps) \
480 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
484 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
485 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
486 NS_ASSERTION(mIfReq, "Expected non-null here"); \
487 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
490 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
491 NS_FORWARD_##_allcaps(mRealPtr->) private \
492 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
493 nsCOMPtr<_i> mRealPtr; \
496 DECL_SHIM(nsILoadContext
, NSILOADCONTEXT
)
497 DECL_SHIM(nsIProgressEventSink
, NSIPROGRESSEVENTSINK
)
498 DECL_SHIM(nsIChannelEventSink
, NSICHANNELEVENTSINK
)
503 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
504 * when this is called if the URI didn't result in an XML document. This
505 * function makes sure to remove the pending load for aURI, if any, from our
506 * hashtable, and to notify its observers, if any.
508 nsresult
AddExternalResource(nsIURI
* aURI
, nsIContentViewer
* aViewer
,
509 nsILoadGroup
* aLoadGroup
,
510 Document
* aDisplayDocument
);
512 nsClassHashtable
<nsURIHashKey
, ExternalResource
> mMap
;
513 nsRefPtrHashtable
<nsURIHashKey
, PendingLoad
> mPendingLoads
;
517 // The current status for a preload.
518 enum class SheetPreloadStatus
: uint8_t {
519 // There's no need to preload anything, the sheet is already in-memory.
521 // The load is in-progress. There's no guarantee that a load was started, it
522 // could be coalesced with other redundant loads.
524 // Something went wrong, and we errored out.
528 //----------------------------------------------------------------------
530 // Document interface. This is implemented by all document objects in
532 class Document
: public nsINode
,
533 public DocumentOrShadowRoot
,
534 public nsSupportsWeakReference
,
535 public nsIRadioGroupContainer
,
536 public nsIScriptObjectPrincipal
,
537 public DispatcherTrait
,
538 public SupportsWeakPtr
{
539 friend class DocumentOrShadowRoot
;
542 explicit Document(const char* aContentType
);
545 Document(const Document
&) = delete;
546 Document
& operator=(const Document
&) = delete;
549 using ExternalResourceLoad
= dom::ExternalResourceMap::ExternalResourceLoad
;
550 using ReferrerPolicyEnum
= dom::ReferrerPolicy
;
551 using AdoptedStyleSheetCloneCache
=
552 nsRefPtrHashtable
<nsPtrHashKey
<const StyleSheet
>, StyleSheet
>;
554 // nsINode overrides the new operator for DOM Arena allocation.
555 // to use the default one, we need to bring it back again
556 void* operator new(size_t aSize
) { return ::operator new(aSize
); }
559 * Called when XPCOM shutdown.
561 static void Shutdown();
563 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID
)
565 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
567 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
569 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document
,
572 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
574 for (RefPtr obs : mObservers.ForwardRange()) { \
575 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
576 obs->func_ params_; \
579 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
581 if (PresShell* presShell = GetObservingPresShell()) { \
582 presShell->func_ params_; \
586 // nsIRadioGroupContainer
587 NS_IMETHOD
WalkRadioGroup(const nsAString
& aName
,
588 nsIRadioVisitor
* aVisitor
) final
{
589 return DocumentOrShadowRoot::WalkRadioGroup(aName
, aVisitor
);
592 void SetCurrentRadioButton(const nsAString
& aName
,
593 HTMLInputElement
* aRadio
) final
{
594 DocumentOrShadowRoot::SetCurrentRadioButton(aName
, aRadio
);
597 HTMLInputElement
* GetCurrentRadioButton(const nsAString
& aName
) final
{
598 return DocumentOrShadowRoot::GetCurrentRadioButton(aName
);
602 GetNextRadioButton(const nsAString
& aName
, const bool aPrevious
,
603 HTMLInputElement
* aFocusedRadio
,
604 HTMLInputElement
** aRadioOut
) final
{
605 return DocumentOrShadowRoot::GetNextRadioButton(aName
, aPrevious
,
606 aFocusedRadio
, aRadioOut
);
608 void AddToRadioGroup(const nsAString
& aName
, HTMLInputElement
* aRadio
) final
{
609 DocumentOrShadowRoot::AddToRadioGroup(aName
, aRadio
, nullptr);
611 void RemoveFromRadioGroup(const nsAString
& aName
,
612 HTMLInputElement
* aRadio
) final
{
613 DocumentOrShadowRoot::RemoveFromRadioGroup(aName
, aRadio
);
615 uint32_t GetRequiredRadioCount(const nsAString
& aName
) const final
{
616 return DocumentOrShadowRoot::GetRequiredRadioCount(aName
);
618 void RadioRequiredWillChange(const nsAString
& aName
,
619 bool aRequiredAdded
) final
{
620 DocumentOrShadowRoot::RadioRequiredWillChange(aName
, aRequiredAdded
);
622 bool GetValueMissingState(const nsAString
& aName
) const final
{
623 return DocumentOrShadowRoot::GetValueMissingState(aName
);
625 void SetValueMissingState(const nsAString
& aName
, bool aValue
) final
{
626 return DocumentOrShadowRoot::SetValueMissingState(aName
, aValue
);
629 nsIPrincipal
* EffectiveCookiePrincipal() const;
631 nsIPrincipal
* EffectiveStoragePrincipal() const;
633 // nsIScriptObjectPrincipal
634 nsIPrincipal
* GetPrincipal() final
{ return NodePrincipal(); }
636 nsIPrincipal
* GetEffectiveCookiePrincipal() final
{
637 return EffectiveCookiePrincipal();
640 nsIPrincipal
* GetEffectiveStoragePrincipal() final
{
641 return EffectiveStoragePrincipal();
644 // You should probably not be using this function, since it performs no checks
645 // to ensure that the partitioned principal should really be used here. It is
646 // only designed to be used in very specific circumstances, such as when
647 // inheriting the document/storage principal.
648 nsIPrincipal
* PartitionedPrincipal() final
{ return mPartitionedPrincipal
; }
650 // Gets the appropriate principal to check the URI against a blocklist /
652 nsIPrincipal
* GetPrincipalForPrefBasedHacks() const;
654 void ClearActiveCookieAndStoragePrincipals() {
655 mActiveStoragePrincipal
= nullptr;
656 mActiveCookiePrincipal
= nullptr;
660 void GetEventTargetParent(EventChainPreVisitor
& aVisitor
) override
;
661 EventListenerManager
* GetOrCreateListenerManager() override
;
662 EventListenerManager
* GetExistingListenerManager() const override
;
664 // This helper class must be set when we dispatch beforeunload and unload
665 // events in order to avoid unterminate sync XHRs.
666 class MOZ_RAII PageUnloadingEventTimeStamp
{
667 RefPtr
<Document
> mDocument
;
671 explicit PageUnloadingEventTimeStamp(Document
* aDocument
)
672 : mDocument(aDocument
), mSet(false) {
673 MOZ_ASSERT(aDocument
);
674 if (mDocument
->mPageUnloadingEventTimeStamp
.IsNull()) {
675 mDocument
->SetPageUnloadingEventTimeStamp();
680 ~PageUnloadingEventTimeStamp() {
682 mDocument
->CleanUnloadEventsTimeStamp();
688 * Let the document know that we're starting to load data into it.
689 * @param aCommand The parser command. Must not be null.
690 * XXXbz It's odd to have that here.
691 * @param aChannel The channel the data will come from. The channel must be
692 * able to report its Content-Type.
693 * @param aLoadGroup The loadgroup this document should use from now on.
694 * Note that the document might not be the only thing using
696 * @param aContainer The container this document is in. This may be null.
697 * XXXbz maybe we should make it more explicit (eg make the
698 * container an nsIWebNavigation or nsIDocShell or
700 * @param [out] aDocListener the listener to pump data from the channel into.
701 * Generally this will be the parser this document
702 * sets up, or some sort of data-handler for media
704 * @param aReset whether the document should call Reset() on itself. If this
705 * is false, the document will NOT set its principal to the
706 * channel's owner, will not clear any event listeners that are
707 * already set on it, etc.
709 * Once this has been called, the document will return false for
710 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
711 * sure this happens is the responsibility of the caller of
712 * StartDocumentLoad().
714 * This function has an implementation, and does some setup, but does NOT set
715 * *aDocListener; this is the job of subclasses.
717 virtual nsresult
StartDocumentLoad(const char* aCommand
, nsIChannel
* aChannel
,
718 nsILoadGroup
* aLoadGroup
,
719 nsISupports
* aContainer
,
720 nsIStreamListener
** aDocListener
,
722 void StopDocumentLoad();
724 virtual void SetSuppressParserErrorElement(bool aSuppress
) {}
725 virtual bool SuppressParserErrorElement() { return false; }
727 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress
) {}
728 virtual bool SuppressParserErrorConsoleMessages() { return false; }
731 void InsertChildBefore(nsIContent
* aKid
, nsIContent
* aBeforeThis
,
732 bool aNotify
, ErrorResult
& aRv
) override
;
733 void RemoveChildNode(nsIContent
* aKid
, bool aNotify
) final
;
734 nsresult
Clone(dom::NodeInfo
* aNodeInfo
, nsINode
** aResult
) const override
{
735 return NS_ERROR_NOT_IMPLEMENTED
;
737 nsresult
CloneDocHelper(Document
* clone
) const;
739 Document
* GetLatestStaticClone() const { return mLatestStaticClone
; }
742 * Signal that the document title may have changed
743 * (see Document::GetTitle).
744 * @param aBoundTitleElement true if an HTML or SVG <title> element
745 * has just been bound to the document.
747 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement
);
750 * Return the URI for the document. May return null. If it ever stops being
751 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
752 * also never return null.
754 * The value returned corresponds to the "document's address" in
755 * HTML5. As such, it may change over the lifetime of the document, for
756 * instance as a result of the user navigating to a fragment identifier on
757 * the page, or as a result to a call to pushState() or replaceState().
759 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
761 nsIURI
* GetDocumentURI() const { return mDocumentURI
; }
764 * Return the original URI of the document. This is the same as the
765 * document's URI unless that has changed from its original value (for
766 * example, due to history.pushState() or replaceState() being invoked on the
769 * This method corresponds to the "creation URL" in HTML5 and, once set,
770 * doesn't change over the lifetime of the document.
772 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
774 nsIURI
* GetOriginalURI() const { return mOriginalURI
; }
777 * Return the base domain of the document. This has been computed using
778 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
779 * checks. When the URI of the document changes, this value is recomputed.
781 nsCString
GetBaseDomain() const { return mBaseDomain
; }
784 * Set the URI for the document. This also sets the document's original URI,
787 void SetDocumentURI(nsIURI
* aURI
);
790 * Set the URI for the document loaded via XHR, when accessed from
791 * chrome privileged script.
793 void SetChromeXHRDocURI(nsIURI
* aURI
) { mChromeXHRDocURI
= aURI
; }
796 * Set the base URI for the document loaded via XHR, when accessed from
797 * chrome privileged script.
799 void SetChromeXHRDocBaseURI(nsIURI
* aURI
) { mChromeXHRDocBaseURI
= aURI
; }
802 * The CSP in general is stored in the ClientInfo, but we also cache
803 * the CSP on the document so subresources loaded within a document
804 * can query that cached CSP instead of having to deserialize the CSP
807 * Please note that at the time of CSP parsing the Client is not
808 * available yet, hence we sync CSP of document and Client when the
809 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
811 nsIContentSecurityPolicy
* GetCsp() const;
812 void SetCsp(nsIContentSecurityPolicy
* aCSP
);
814 nsIContentSecurityPolicy
* GetPreloadCsp() const;
815 void SetPreloadCsp(nsIContentSecurityPolicy
* aPreloadCSP
);
817 void GetCspJSON(nsString
& aJSON
);
820 * Set referrer policy and upgrade-insecure-requests flags
822 void ApplySettingsFromCSP(bool aSpeculative
);
824 already_AddRefed
<nsIParser
> CreatorParserOrNull() {
825 nsCOMPtr
<nsIParser
> parser
= mParser
;
826 return parser
.forget();
830 * ReferrerInfo getter for Document.webidl.
832 nsIReferrerInfo
* ReferrerInfo() const { return GetReferrerInfo(); }
834 nsIReferrerInfo
* GetReferrerInfo() const { return mReferrerInfo
; }
836 nsIReferrerInfo
* GetPreloadReferrerInfo() const {
837 return mPreloadReferrerInfo
;
840 * Return the referrer policy of the document. Return "default" if there's no
841 * valid meta referrer tag found in the document.
842 * Referrer policy should be inherited from parent if the iframe is srcdoc
844 ReferrerPolicyEnum
GetReferrerPolicy() const;
847 * GetReferrerPolicy() for Document.webidl.
849 ReferrerPolicyEnum
ReferrerPolicy() const { return GetReferrerPolicy(); }
852 * If true, this flag indicates that all mixed content subresource
853 * loads for this document (and also embeded browsing contexts) will
856 bool GetBlockAllMixedContent(bool aPreload
) const {
858 return mBlockAllMixedContentPreloads
;
860 return mBlockAllMixedContent
;
864 * If true, this flag indicates that all subresource loads for this
865 * document need to be upgraded from http to https.
866 * This flag becomes true if the CSP of the document itself, or any
867 * of the document's ancestors up to the toplevel document makes use
868 * of the CSP directive 'upgrade-insecure-requests'.
870 bool GetUpgradeInsecureRequests(bool aPreload
) const {
872 return mUpgradeInsecurePreloads
;
874 return mUpgradeInsecureRequests
;
877 void SetReferrerInfo(nsIReferrerInfo
*);
880 * Referrer policy from <meta name="referrer" content=`policy`>
881 * will have higher priority than referrer policy from Referrer-Policy
882 * header. So override the old ReferrerInfo if we get one from meta
884 void UpdateReferrerInfoFromMeta(const nsAString
& aMetaReferrer
,
888 * Set the principals responsible for this document. Chances are, you do not
889 * want to be using this.
891 void SetPrincipals(nsIPrincipal
* aPrincipal
,
892 nsIPrincipal
* aPartitionedPrincipal
);
895 * Returns true if exempt from HTTPS-Only Mode upgrade.
897 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus
; }
900 * Return the LoadGroup for the document. May return null.
902 already_AddRefed
<nsILoadGroup
> GetDocumentLoadGroup() const {
903 nsCOMPtr
<nsILoadGroup
> group
= do_QueryReferent(mDocumentLoadGroup
);
904 return group
.forget();
908 * Return the fallback base URL for this document, as defined in the HTML
909 * specification. Note that this can return null if there is no document URI.
911 * XXXbz: This doesn't implement the bits for about:blank yet.
913 nsIURI
* GetFallbackBaseURI() const {
914 if (mIsSrcdocDocument
&& mParentDocument
) {
915 return mParentDocument
->GetDocBaseURI();
921 * Return the referrer from document URI as defined in the Referrer Policy
923 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
924 * While document is an iframe srcdoc document, let document be document's
925 * browsing context's browsing context container's node document.
926 * Then referrer should be document's URL
929 nsIURI
* GetDocumentURIAsReferrer() const {
930 if (mIsSrcdocDocument
&& mParentDocument
) {
931 return mParentDocument
->GetDocumentURIAsReferrer();
937 * Return the base URI for relative URIs in the document (the document uri
938 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
939 * returned URI could be null if there is no document URI. If the document is
940 * a srcdoc document and has no explicit base URL, return the parent
941 * document's base URL.
943 nsIURI
* GetDocBaseURI() const {
944 if (mDocumentBaseURI
) {
945 return mDocumentBaseURI
;
947 return GetFallbackBaseURI();
950 nsIURI
* GetBaseURI(bool aTryUseXHRDocBaseURI
= false) const final
;
952 void SetBaseURI(nsIURI
* aURI
);
955 * Resolves a URI based on the document's base URI.
957 Result
<OwningNonNull
<nsIURI
>, nsresult
> ResolveWithBaseURI(
958 const nsAString
& aURI
);
961 * Return the URL data which style system needs for resolving url value.
962 * This method attempts to use the cached object in mCachedURLData, but
963 * if the base URI, document URI, or principal has changed since last
964 * call to this function, or the function is called the first time for
965 * the document, a new one is created.
967 URLExtraData
* DefaultStyleAttrURLData();
968 nsIReferrerInfo
* ReferrerInfoForInternalCSSAndSVGResources();
971 * Get/Set the base target of a link in a document.
973 void GetBaseTarget(nsAString
& aBaseTarget
) const {
974 aBaseTarget
= mBaseTarget
;
977 void SetBaseTarget(const nsString
& aBaseTarget
) { mBaseTarget
= aBaseTarget
; }
980 * Return a standard name for the document's character set.
982 NotNull
<const Encoding
*> GetDocumentCharacterSet() const {
983 return mCharacterSet
;
987 * Set the document's character encoding.
989 void SetDocumentCharacterSet(NotNull
<const Encoding
*> aEncoding
);
991 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource
; }
993 // This method MUST be called before SetDocumentCharacterSet if
994 // you're planning to call both.
995 void SetDocumentCharacterSetSource(int32_t aCharsetSource
) {
996 mCharacterSetSource
= aCharsetSource
;
1000 * Get the Content-Type of this document.
1002 void GetContentType(nsAString
& aContentType
);
1005 * Set the Content-Type of this document.
1007 void SetContentType(const nsACString
& aContentType
);
1010 * Return the language of this document.
1012 void GetContentLanguage(nsAString
& aContentLanguage
) const {
1013 CopyASCIItoUTF16(mContentLanguage
, aContentLanguage
);
1016 // The states BidiEnabled and MathMLEnabled should persist across multiple
1017 // views (screen, print) of the same document.
1020 * Check if the document contains bidi data.
1021 * If so, we have to apply the Unicode Bidi Algorithm.
1023 bool GetBidiEnabled() const { return mBidiEnabled
; }
1026 * Indicate the document contains bidi data.
1027 * Currently, we cannot disable bidi, because once bidi is enabled,
1028 * it affects a frame model irreversibly, and plays even though
1029 * the document no longer contains bidi data.
1031 void SetBidiEnabled() { mBidiEnabled
= true; }
1033 void SetMathMLEnabled() { mMathMLEnabled
= true; }
1036 * Ask this document whether it's the initial document in its window.
1038 bool IsInitialDocument() const { return mIsInitialDocumentInWindow
; }
1041 * Tell this document that it's the initial document in its window. See
1042 * comments on mIsInitialDocumentInWindow for when this should be called.
1044 void SetIsInitialDocument(bool aIsInitialDocument
);
1046 void SetLoadedAsData(bool aLoadedAsData
, bool aConsiderForMemoryReporting
);
1049 * Normally we assert if a runnable labeled with one DocGroup touches data
1050 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1051 * means that we can touch that document from any DocGroup without asserting.
1053 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches
= true; }
1056 * Get the bidi options for this document.
1057 * @see nsBidiUtils.h
1059 uint32_t GetBidiOptions() const { return mBidiOptions
; }
1062 * Set the bidi options for this document. This just sets the bits;
1063 * callers are expected to take action as needed if they want this
1064 * change to actually change anything immediately.
1065 * @see nsBidiUtils.h
1067 void SetBidiOptions(uint32_t aBidiOptions
) { mBidiOptions
= aBidiOptions
; }
1070 * Returns true if the document holds a CSP
1071 * delivered through an HTTP Header.
1073 bool GetHasCSPDeliveredThroughHeader() {
1074 return mHasCSPDeliveredThroughHeader
;
1078 * Return a promise which resolves to the content blocking events.
1080 using GetContentBlockingEventsPromise
= MozPromise
<uint32_t, bool, true>;
1081 [[nodiscard
]] RefPtr
<GetContentBlockingEventsPromise
>
1082 GetContentBlockingEvents();
1085 * Get the sandbox flags for this document.
1086 * @see nsSandboxFlags.h for the possible flags
1088 uint32_t GetSandboxFlags() const { return mSandboxFlags
; }
1090 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> GetEmbedderPolicy() const {
1091 return mEmbedderPolicy
;
1094 void SetEmbedderPolicy(
1095 const Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
>& aCOEP
) {
1096 mEmbedderPolicy
= aCOEP
;
1100 * Get string representation of sandbox flags (null if no flags are set)
1102 void GetSandboxFlagsAsString(nsAString
& aFlags
);
1105 * Set the sandbox flags for this document.
1106 * @see nsSandboxFlags.h for the possible flags
1108 void SetSandboxFlags(uint32_t sandboxFlags
) { mSandboxFlags
= sandboxFlags
; }
1111 * Called when the document was decoded as UTF-8 and decoder encountered no
1114 void EnableEncodingMenu() { mEncodingMenuDisabled
= false; }
1117 * Called to disable client access to cookies through the document.cookie API
1118 * from user JavaScript code.
1120 void DisableCookieAccess() { mDisableCookieAccess
= true; }
1122 void SetLinkHandlingEnabled(bool aValue
) { mLinksEnabled
= aValue
; }
1123 bool LinkHandlingEnabled() { return mLinksEnabled
; }
1126 * Set compatibility mode for this document
1128 void SetCompatibilityMode(nsCompatibility aMode
);
1131 * Called to disable client access to document.write() API from user
1134 void SetDocWriteDisabled(bool aDisabled
) { mDisableDocWrite
= aDisabled
; }
1137 * Whether a document.write() call is in progress.
1139 bool IsWriting() const { return mWriteLevel
!= uint32_t(0); }
1142 * Access HTTP header data (this may also get set from other
1143 * sources, like HTML META tags).
1145 void GetHeaderData(nsAtom
* aHeaderField
, nsAString
& aData
) const;
1146 void SetHeaderData(nsAtom
* aheaderField
, const nsAString
& aData
);
1149 * Set Early Hint data, moves the arrays into the function, leaving the
1150 * passed variables empty
1152 void SetEarlyHints(nsTArray
<net::EarlyHintConnectArgs
>&& aEarlyHints
);
1153 const nsTArray
<net::EarlyHintConnectArgs
>& GetEarlyHints() const {
1158 * Create a new presentation shell that will use aContext for its
1159 * presentation context (presentation contexts <b>must not</b> be
1160 * shared among multiple presentation shells). The caller of this
1161 * method is responsible for calling BeginObservingDocument() on the
1162 * presshell if the presshell should observe document mutations.
1164 MOZ_CAN_RUN_SCRIPT already_AddRefed
<PresShell
> CreatePresShell(
1165 nsPresContext
* aContext
, nsViewManager
* aViewManager
);
1166 void DeletePresShell();
1168 PresShell
* GetPresShell() const {
1169 return GetBFCacheEntry() ? nullptr : mPresShell
;
1172 inline PresShell
* GetObservingPresShell() const;
1174 // Return whether the presshell for this document is safe to flush.
1175 bool IsSafeToFlush() const;
1177 inline nsPresContext
* GetPresContext() const;
1179 bool HasShellOrBFCacheEntry() const { return mPresShell
|| mBFCacheEntry
; }
1181 // Instead using this method, what you probably want is
1182 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1183 void DisallowBFCaching(uint32_t aStatus
= BFCacheStatus::NOT_ALLOWED
);
1185 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed
; }
1187 // Accepts null to clear the BFCache entry too.
1188 void SetBFCacheEntry(nsIBFCacheEntry
* aEntry
);
1190 nsIBFCacheEntry
* GetBFCacheEntry() const { return mBFCacheEntry
; }
1192 // Removes this document from the BFCache, if it is cached, and returns
1194 bool RemoveFromBFCacheSync();
1197 * Return the parent document of this document. Will return null
1198 * unless this document is within a compound document and has a
1199 * parent. Note that this parent chain may cross chrome boundaries.
1201 Document
* GetInProcessParentDocument() const { return mParentDocument
; }
1204 * Set the parent document of this document.
1206 void SetParentDocument(Document
* aParent
) {
1207 mParentDocument
= aParent
;
1209 RecomputeResistFingerprinting();
1210 mIgnoreDocGroupMismatches
= aParent
->mIgnoreDocGroupMismatches
;
1211 if (!mIsDevToolsDocument
) {
1212 mIsDevToolsDocument
= mParentDocument
->IsDevToolsDocument();
1217 void SetCurrentContextPaint(const SVGContextPaint
* aContextPaint
) {
1218 mCurrentContextPaint
= aContextPaint
;
1221 const SVGContextPaint
* GetCurrentContextPaint() const {
1222 return mCurrentContextPaint
;
1226 * Are plugins allowed in this document ?
1228 bool GetAllowPlugins();
1231 * Set the sub document for aContent to aSubDoc.
1233 nsresult
SetSubDocumentFor(Element
* aContent
, Document
* aSubDoc
);
1236 * Get the sub document for aContent
1238 Document
* GetSubDocumentFor(nsIContent
* aContent
) const;
1241 * Get the content node for which this document is a sub document.
1243 Element
* GetEmbedderElement() const;
1246 * Return the doctype for this document.
1248 DocumentType
* GetDoctype() const;
1251 * Return the root element for this document.
1253 Element
* GetRootElement() const;
1255 Selection
* GetSelection(ErrorResult
& aRv
);
1257 void MakeBrowsingContextNonSynthetic();
1258 nsresult
HasStorageAccessSync(bool& aHasStorageAccess
);
1259 already_AddRefed
<Promise
> HasStorageAccess(ErrorResult
& aRv
);
1261 StorageAccessAPIHelper::PerformPermissionGrant
CreatePermissionGrantPromise(
1262 nsPIDOMWindowInner
* aInnerWindow
, nsIPrincipal
* aPrincipal
,
1263 bool aHasUserInteraction
, const Maybe
<nsCString
>& aTopLevelBaseDomain
,
1266 already_AddRefed
<Promise
> RequestStorageAccess(ErrorResult
& aRv
);
1268 already_AddRefed
<Promise
> RequestStorageAccessForOrigin(
1269 const nsAString
& aThirdPartyOrigin
, const bool aRequireUserInteraction
,
1272 already_AddRefed
<Promise
> RequestStorageAccessUnderSite(
1273 const nsAString
& aSerializedSite
, ErrorResult
& aRv
);
1274 already_AddRefed
<Promise
> CompleteStorageAccessRequestFromSite(
1275 const nsAString
& aSerializedOrigin
, ErrorResult
& aRv
);
1277 bool UseRegularPrincipal() const;
1280 * Gets the event target to dispatch key events to if there is no focused
1281 * content in the document.
1283 virtual Element
* GetUnfocusedKeyEventTarget();
1286 * Retrieve information about the viewport as a data structure.
1287 * This will return information in the viewport META data section
1288 * of the document. This can be used in lieu of ProcessViewportInfo(),
1289 * which places the viewport information in the document header instead
1290 * of returning it directly.
1292 * @param aDisplaySize size of the on-screen display area for this
1293 * document, in device pixels.
1295 * NOTE: If the site is optimized for mobile (via the doctype), this
1296 * will return viewport information that specifies default information.
1298 nsViewportInfo
GetViewportInfo(const ScreenIntSize
& aDisplaySize
);
1300 void SetMetaViewportData(UniquePtr
<ViewportMetaData
> aData
);
1302 // Returns a ViewportMetaData for this document.
1303 ViewportMetaData
GetViewportMetaData() const;
1306 * True iff this doc will ignore manual character encoding overrides.
1308 virtual bool WillIgnoreCharsetOverride() { return true; }
1311 * Return whether the document was created by a srcdoc iframe.
1313 bool IsSrcdocDocument() const { return mIsSrcdocDocument
; }
1316 * Sets whether the document was created by a srcdoc iframe.
1318 void SetIsSrcdocDocument(bool aIsSrcdocDocument
) {
1319 mIsSrcdocDocument
= aIsSrcdocDocument
;
1323 * Gets the srcdoc string from within the channel (assuming both exist).
1324 * Returns a void string if this isn't a srcdoc document or if
1325 * the channel has not been set.
1327 nsresult
GetSrcdocData(nsAString
& aSrcdocData
);
1329 already_AddRefed
<AnonymousContent
> InsertAnonymousContent(bool aForce
,
1331 void RemoveAnonymousContent(AnonymousContent
&);
1333 * If aNode is a descendant of anonymous content inserted by
1334 * InsertAnonymousContent, this method returns the root element of the
1335 * inserted anonymous content (in other words, the clone of the aElement
1336 * that was passed to InsertAnonymousContent).
1338 Element
* GetAnonRootIfInAnonymousContentContainer(nsINode
* aNode
) const;
1339 nsTArray
<RefPtr
<AnonymousContent
>>& GetAnonymousContents() {
1340 return mAnonymousContents
;
1343 TimeStamp
GetPageUnloadingEventTimeStamp() const {
1344 if (!mParentDocument
) {
1345 return mPageUnloadingEventTimeStamp
;
1348 TimeStamp
parentTimeStamp(
1349 mParentDocument
->GetPageUnloadingEventTimeStamp());
1350 if (parentTimeStamp
.IsNull()) {
1351 return mPageUnloadingEventTimeStamp
;
1354 if (!mPageUnloadingEventTimeStamp
||
1355 parentTimeStamp
< mPageUnloadingEventTimeStamp
) {
1356 return parentTimeStamp
;
1359 return mPageUnloadingEventTimeStamp
;
1362 void NotifyLayerManagerRecreated();
1364 // Add an element to the list of elements that need their mapped attributes
1365 // resolved to a declaration block.
1367 // These are weak pointers, manually unschedule them when an element is
1368 // removed from the tree.
1369 void ScheduleForPresAttrEvaluation(Element
* aElement
);
1371 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1372 // generally when it's unbound from the tree.
1373 void UnscheduleForPresAttrEvaluation(Element
* aElement
);
1375 // Resolve all presentational attributes scheduled in
1376 // ScheduleForPresAttrEvaluation
1377 void ResolveScheduledPresAttrs() {
1378 if (mLazyPresElements
.IsEmpty()) {
1381 DoResolveScheduledPresAttrs();
1384 Maybe
<ClientInfo
> GetClientInfo() const;
1385 Maybe
<ClientState
> GetClientState() const;
1386 Maybe
<ServiceWorkerDescriptor
> GetController() const;
1388 // Returns the size of the mBlockedNodesByClassifier array.
1390 // This array contains nodes that have been blocked to prevent user tracking,
1391 // fingerprinting, cryptomining, etc. They most likely have had their
1392 // nsIChannel canceled by the URL classifier (Safebrowsing).
1394 // A script can subsequently use GetBlockedNodesByClassifier()
1395 // to get a list of references to these nodes.
1398 // This expresses how many tracking nodes have been blocked for this document
1399 // since its beginning, not how many of them are still around in the DOM tree.
1400 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1401 // array but they are not removed when those nodes are removed from the tree
1402 // or even garbage collected.
1403 long BlockedNodeByClassifierCount() const {
1404 return mBlockedNodesByClassifier
.Length();
1408 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1410 // This array contains nodes that have been blocked to prevent
1411 // user tracking. They most likely have had their nsIChannel
1412 // canceled by the URL classifier (Safebrowsing).
1414 already_AddRefed
<nsSimpleContentList
> BlockedNodesByClassifier() const;
1416 // Helper method that returns true if the document has storage-access sandbox
1418 bool StorageAccessSandboxed() const;
1420 // Helper method that returns true if storage access API is enabled and
1421 // the passed flag has storage-access sandbox flag.
1422 static bool StorageAccessSandboxed(uint32_t aSandboxFlags
);
1424 // Returns the cookie jar settings for this and sub contexts.
1425 nsICookieJarSettings
* CookieJarSettings();
1427 // Returns whether this document is using unpartitioned cookies
1428 bool UsingStorageAccess();
1430 // Returns whether the storage access permission of the document is granted by
1432 bool HasStorageAccessPermissionGrantedByAllowList();
1434 // Increments the document generation.
1435 inline void Changed() { ++mGeneration
; }
1437 // Returns the current generation.
1438 inline int32_t GetGeneration() const { return mGeneration
; }
1440 // Adds cached sizes values to aSizes if there's any
1441 // cached value and if the document generation hasn't
1442 // changed since the cache was created.
1443 // Returns true if sizes were added.
1444 bool GetCachedSizes(nsTabSizes
* aSizes
);
1446 // Sets the cache sizes for the current generation.
1447 void SetCachedSizes(nsTabSizes
* aSizes
);
1450 * Should be called when an element's editable changes as a result of
1451 * changing its contentEditable attribute/property.
1453 * The change should be +1 if the contentEditable attribute/property was
1454 * changed to true, -1 if it was changed to false.
1456 void ChangeContentEditableCount(Element
*, int32_t aChange
);
1457 MOZ_CAN_RUN_SCRIPT
void DeferredContentEditableCountChange(Element
*);
1459 enum class EditingState
: int8_t {
1468 * Returns the editing state of the document (not editable, contentEditable or
1471 EditingState
GetEditingState() const { return mEditingState
; }
1474 * Returns whether the document is editable.
1476 bool IsEditingOn() const {
1477 return GetEditingState() == EditingState::eDesignMode
||
1478 GetEditingState() == EditingState::eContentEditable
;
1481 class MOZ_STACK_CLASS nsAutoEditingState
{
1483 nsAutoEditingState(Document
* aDoc
, EditingState aState
)
1484 : mDoc(aDoc
), mSavedState(aDoc
->mEditingState
) {
1485 aDoc
->mEditingState
= aState
;
1487 ~nsAutoEditingState() { mDoc
->mEditingState
= mSavedState
; }
1490 RefPtr
<Document
> mDoc
;
1491 EditingState mSavedState
;
1493 friend class nsAutoEditingState
;
1496 * Set the editing state of the document. Don't use this if you want
1497 * to enable/disable editing, call EditingStateChanged() or
1500 void SetEditingState(EditingState aState
) { mEditingState
= aState
; }
1503 * Called when this Document's editor is destroyed.
1505 void TearingDownEditor();
1507 void SetKeyPressEventModel(uint16_t aKeyPressEventModel
);
1509 // Gets the next form number.
1511 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1512 // parser inserted form element.
1513 int32_t GetNextFormNumber() { return mNextFormNumber
++; }
1515 // Gets the next form control number.
1517 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1518 // parser inserted form control element.
1519 int32_t GetNextControlNumber() { return mNextControlNumber
++; }
1521 PreloadService
& Preloads() { return mPreloadService
; }
1523 bool HasThirdPartyChannel();
1525 bool ShouldIncludeInTelemetry(bool aAllowExtensionURIs
);
1527 void AddMediaElementWithMSE();
1528 void RemoveMediaElementWithMSE();
1530 void DoNotifyPossibleTitleChange();
1532 void InitFeaturePolicy();
1533 nsresult
InitFeaturePolicy(nsIChannel
* aChannel
);
1535 void EnsureNotEnteringAndExitFullscreen();
1538 friend class nsUnblockOnloadEvent
;
1540 nsresult
InitCSP(nsIChannel
* aChannel
);
1541 nsresult
InitCOEP(nsIChannel
* aChannel
);
1543 nsresult
InitReferrerInfo(nsIChannel
* aChannel
);
1545 void PostUnblockOnloadEvent();
1547 void DoUnblockOnload();
1549 void DoResolveScheduledPresAttrs();
1551 void RetrieveRelevantHeaders(nsIChannel
* aChannel
);
1553 void TryChannelCharset(nsIChannel
* aChannel
, int32_t& aCharsetSource
,
1554 NotNull
<const Encoding
*>& aEncoding
,
1555 nsHtml5TreeOpExecutor
* aExecutor
);
1557 MOZ_CAN_RUN_SCRIPT
void DispatchContentLoadedEvents();
1559 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1560 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void DispatchPageTransition(
1561 EventTarget
* aDispatchTarget
, const nsAString
& aType
, bool aInFrameSwap
,
1562 bool aPersisted
, bool aOnlySystemGroup
);
1564 // Call this before the document does something that will unbind all content.
1565 // That will stop us from doing a lot of work as each element is removed.
1566 void DestroyElementMaps();
1568 Element
* GetRootElementInternal() const;
1570 void SetPageUnloadingEventTimeStamp() {
1571 MOZ_ASSERT(!mPageUnloadingEventTimeStamp
);
1572 mPageUnloadingEventTimeStamp
= TimeStamp::NowLoRes();
1575 void CleanUnloadEventsTimeStamp() {
1576 MOZ_ASSERT(mPageUnloadingEventTimeStamp
);
1577 mPageUnloadingEventTimeStamp
= TimeStamp();
1581 * Clears any Servo element data stored on Elements in the document.
1583 void ClearStaleServoData();
1586 * Do the tree-disconnection that ResetToURI and document.open need to do.
1588 void DisconnectNodeTree();
1591 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1592 * "CheckKeyPressEventModel" event to check whether we should dispatch
1593 * keypress events in confluent model or split model. This should be
1594 * called only when mEditingState is changed to eDesignMode or
1595 * eConentEditable at first time.
1597 void MaybeDispatchCheckKeyPressEventModelEvent();
1599 /* Midas implementation */
1600 nsCommandManager
* GetMidasCommandManager();
1602 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
TurnEditingOff();
1604 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1605 // of places, and I'm pretty sure the exact ExecCommand call it
1606 // makes cannot actually run script.
1607 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
EditingStateChanged();
1609 void MaybeEditingStateChanged();
1612 // Get the root <html> element, or return null if there isn't one (e.g.
1613 // if the root isn't <html>)
1614 Element
* GetHtmlElement() const;
1615 // Returns the first child of GetHtmlContent which has the given tag,
1616 // or nullptr if that doesn't exist.
1617 Element
* GetHtmlChildElement(nsAtom
* aTag
);
1618 // Get the canonical <body> element, or return null if there isn't one (e.g.
1619 // if the root isn't <html> or if the <body> isn't there)
1620 HTMLBodyElement
* GetBodyElement();
1621 // Get the canonical <head> element, or return null if there isn't one (e.g.
1622 // if the root isn't <html> or if the <head> isn't there)
1623 Element
* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head
); }
1624 // Get the "body" in the sense of document.body: The first <body> or
1625 // <frameset> that's a child of a root <html>
1626 nsGenericHTMLElement
* GetBody();
1627 // Set the "body" in the sense of document.body.
1628 void SetBody(nsGenericHTMLElement
* aBody
, ErrorResult
& rv
);
1629 // Get the "head" element in the sense of document.head.
1630 HTMLSharedElement
* GetHead();
1632 ServoStyleSet
* StyleSetForPresShellOrMediaQueryEvaluation() const {
1633 return mStyleSet
.get();
1636 // ShadowRoot has APIs that can change styles. This notifies the shell that
1637 // stlyes applicable in the shadow tree have potentially changed.
1638 void RecordShadowStyleChange(ShadowRoot
&);
1640 // Needs to be called any time the applicable style can has changed, in order
1641 // to schedule a style flush and setup all the relevant state.
1642 void ApplicableStylesChanged();
1644 // Whether we filled the style set with any style sheet. Only meant to be used
1645 // from DocumentOrShadowRoot::Traverse.
1646 bool StyleSetFilled() const { return mStyleSetFilled
; }
1649 * Accessors to the collection of stylesheets owned by this document.
1650 * Style sheets are ordered, most significant last.
1653 void InsertSheetAt(size_t aIndex
, StyleSheet
&);
1656 * Add a stylesheet to the document
1658 * TODO(emilio): This is only used by parts of editor that are no longer in
1659 * use by m-c or c-c, so remove.
1661 void AddStyleSheet(StyleSheet
* aSheet
) {
1663 InsertSheetAt(SheetCount(), *aSheet
);
1667 * Notify the document that the applicable state of the sheet changed
1668 * and that observers should be notified and style sets updated
1670 void StyleSheetApplicableStateChanged(StyleSheet
&);
1671 void PostStyleSheetApplicableStateChangeEvent(StyleSheet
&);
1672 void PostStyleSheetRemovedEvent(StyleSheet
&);
1674 enum additionalSheetType
{
1678 AdditionalSheetTypeCount
1681 nsresult
LoadAdditionalStyleSheet(additionalSheetType aType
,
1683 nsresult
AddAdditionalStyleSheet(additionalSheetType aType
,
1684 StyleSheet
* aSheet
);
1685 void RemoveAdditionalStyleSheet(additionalSheetType aType
, nsIURI
* sheetURI
);
1687 StyleSheet
* GetFirstAdditionalAuthorSheet() {
1688 return mAdditionalSheets
[eAuthorSheet
].SafeElementAt(0);
1692 * Returns the index that aSheet should be inserted at to maintain document
1695 size_t FindDocStyleSheetInsertionPoint(const StyleSheet
& aSheet
);
1698 * Get this document's CSSLoader. This is guaranteed to not return null.
1700 css::Loader
* CSSLoader() const { return mCSSLoader
; }
1703 * Get this document's StyleImageLoader. This is guaranteed to not return
1706 css::ImageLoader
* StyleImageLoader() const { return mStyleImageLoader
; }
1709 * Get the channel that was passed to StartDocumentLoad or Reset for this
1710 * document. Note that this may be null in some cases (eg if
1711 * StartDocumentLoad or Reset were never called)
1713 nsIChannel
* GetChannel() const { return mChannel
; }
1716 * Get this document's attribute stylesheet. May return null if
1719 AttributeStyles
* GetAttributeStyles() const { return mAttributeStyles
.get(); }
1721 virtual void SetScriptGlobalObject(nsIScriptGlobalObject
* aGlobalObject
);
1724 * Get/set the object from which the context for the event/script handling can
1725 * be got. Normally GetScriptHandlingObject() returns the same object as
1726 * GetScriptGlobalObject(), but if the document is loaded as data,
1727 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1728 * aHasHadScriptHandlingObject is set true if document has had the object
1729 * for event/script handling. Do not process any events/script if the method
1730 * returns null, but aHasHadScriptHandlingObject is true.
1732 nsIScriptGlobalObject
* GetScriptHandlingObject(
1733 bool& aHasHadScriptHandlingObject
) const {
1734 aHasHadScriptHandlingObject
= mHasHadScriptHandlingObject
;
1735 return mScriptGlobalObject
? mScriptGlobalObject
.get()
1736 : GetScriptHandlingObjectInternal();
1738 void SetScriptHandlingObject(nsIScriptGlobalObject
* aScriptObject
);
1741 * Get the object that is used as the scope for all of the content
1742 * wrappers whose owner document is this document. Unlike the script global
1743 * object, this will only return null when the global object for this
1744 * document is truly gone. Use this object when you're trying to find a
1745 * content wrapper in XPConnect.
1747 nsIGlobalObject
* GetScopeObject() const;
1748 void SetScopeObject(nsIGlobalObject
* aGlobal
);
1751 * Return the window containing the document (the outer window).
1753 nsPIDOMWindowOuter
* GetWindow() const {
1754 return mWindow
? mWindow
->GetOuterWindow() : GetWindowInternal();
1757 bool IsInBackgroundWindow() const {
1758 auto* outer
= mWindow
? mWindow
->GetOuterWindow() : nullptr;
1759 return outer
&& outer
->IsBackground();
1763 * Return the inner window used as the script compilation scope for
1764 * this document. If you're not absolutely sure you need this, use
1767 nsPIDOMWindowInner
* GetInnerWindow() const {
1768 return mRemovedFromDocShell
? nullptr : mWindow
;
1772 * Return the outer window ID.
1774 uint64_t OuterWindowID() const {
1775 nsPIDOMWindowOuter
* window
= GetWindow();
1776 return window
? window
->WindowID() : 0;
1780 * Return the inner window ID.
1782 uint64_t InnerWindowID() const {
1783 nsPIDOMWindowInner
* window
= GetInnerWindow();
1784 return window
? window
->WindowID() : 0;
1788 * Return WindowGlobalChild that is associated with the inner window.
1790 WindowGlobalChild
* GetWindowGlobalChild() {
1791 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1796 * Return WindowContext associated with the inner window.
1798 WindowContext
* GetWindowContext() const {
1799 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1802 bool IsTopLevelWindowInactive() const;
1805 * Get the script loader for this document
1807 dom::ScriptLoader
* ScriptLoader() { return mScriptLoader
; }
1810 * Add/Remove an element to the document's id and name hashes
1812 void AddToIdTable(Element
* aElement
, nsAtom
* aId
);
1813 void RemoveFromIdTable(Element
* aElement
, nsAtom
* aId
);
1814 void AddToNameTable(Element
* aElement
, nsAtom
* aName
);
1815 void RemoveFromNameTable(Element
* aElement
, nsAtom
* aName
);
1818 * Returns all elements in the top layer in the insertion order.
1820 nsTArray
<Element
*> GetTopLayer() const;
1822 bool TopLayerContains(Element
&) const;
1824 // Do the "fullscreen element ready check" from the fullscreen spec.
1825 // It returns true if the given element is allowed to go into fullscreen.
1826 // It is responsive to dispatch "fullscreenerror" event when necessary.
1827 bool FullscreenElementReadyCheck(FullscreenRequest
&);
1830 * When this is called on content process, this asynchronously requests that
1831 * the document make aElement the fullscreen element, and move into fullscreen
1832 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1833 * and it can be returned to fullscreen status by calling
1834 * RestorePreviousFullscreenState().
1835 * If on chrome process, this is synchronously.
1837 * Note that requesting fullscreen in a document also makes the element which
1838 * contains this document in this document's parent document fullscreen. i.e.
1839 * the <iframe> or <browser> that contains this document is also mode
1840 * fullscreen. This happens recursively in all ancestor documents.
1842 void RequestFullscreen(UniquePtr
<FullscreenRequest
> aRequest
,
1843 bool aApplyFullscreenDirectly
= false);
1846 void RequestFullscreenInContentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1847 bool aApplyFullscreenDirectly
);
1848 void RequestFullscreenInParentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1849 bool aApplyFullscreenDirectly
);
1851 // Pushes aElement onto the top layer
1852 void TopLayerPush(Element
&);
1854 // Removes the topmost element for which aPredicate returns true from the top
1855 // layer. The removed element, if any, is returned.
1856 Element
* TopLayerPop(FunctionRef
<bool(Element
*)> aPredicate
);
1858 // Removes the given element from the top layer. The removed element, if any,
1860 Element
* TopLayerPop(Element
&);
1862 MOZ_CAN_RUN_SCRIPT
bool TryAutoFocusCandidate(Element
& aElement
);
1865 // Removes all the elements with fullscreen flag set from the top layer, and
1866 // clears their fullscreen flag.
1867 void CleanupFullscreenState();
1869 // Pops the fullscreen element from the top layer and clears its
1870 // fullscreen flag. Returns whether there was any fullscreen element.
1871 enum class UpdateViewport
: bool { No
, Yes
};
1872 bool PopFullscreenElement(UpdateViewport
= UpdateViewport::Yes
);
1874 // Pushes the given element into the top of top layer and set fullscreen
1876 void SetFullscreenElement(Element
&);
1878 // Whether we has pending fullscreen request.
1879 bool HasPendingFullscreenRequests();
1882 * When Esc key is pressed, cancel the dialog element if the document is
1883 * blocked by the dialog or hide popover if popover is shown.
1885 MOZ_CAN_RUN_SCRIPT
void HandleEscKey();
1887 void AddModalDialog(HTMLDialogElement
&);
1888 void RemoveModalDialog(HTMLDialogElement
&);
1891 * Called when a frame in a child process has entered fullscreen or when a
1892 * fullscreen frame in a child process changes to another origin.
1893 * aFrameElement is the frame element which contains the child-process
1894 * fullscreen document.
1896 void RemoteFrameFullscreenChanged(Element
* aFrameElement
);
1899 * Called when a frame in a remote child document has rolled back fullscreen
1900 * so that all its top layer are empty; we must continue the
1901 * rollback in this parent process' doc tree branch which is fullscreen.
1902 * Note that only one branch of the document tree can have its documents in
1903 * fullscreen state at one time. We're in inconsistent state if a
1904 * fullscreen document has a parent and that parent isn't fullscreen. We
1905 * preserve this property across process boundaries.
1907 void RemoteFrameFullscreenReverted();
1910 * Restores the previous fullscreen element to fullscreen status. If there
1911 * is no former fullscreen element, this exits fullscreen, moving the
1912 * top-level browser window out of fullscreen mode.
1914 void RestorePreviousFullscreenState(UniquePtr
<FullscreenExit
>);
1917 * Returns true if this document is a fullscreen leaf document, i.e. it
1918 * is in fullscreen mode and has no fullscreen children.
1920 bool IsFullscreenLeaf();
1923 * Returns the document which is at the root of this document's branch
1924 * in the in-process document tree. Returns nullptr if the document isn't
1927 Document
* GetFullscreenRoot();
1929 size_t CountFullscreenElements() const;
1932 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1935 void SetFullscreenRoot(Document
* aRoot
);
1938 * Synchronously cleans up the fullscreen state on the given document.
1940 * Calling this without performing fullscreen transition could lead
1941 * to undesired effect (the transition happens after document state
1942 * flips), hence it should only be called either by nsGlobalWindow
1943 * when we have performed the transition, or when it is necessary to
1944 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1945 * should be called instead.
1947 * aDocument must not be null.
1949 static void ExitFullscreenInDocTree(Document
* aDocument
);
1952 * Ask the document to exit fullscreen state asynchronously.
1954 * Different from ExitFullscreenInDocTree(), this allows the window
1955 * to perform fullscreen transition first if any.
1957 * If aDocument is null, it will exit fullscreen from all documents
1960 static void AsyncExitFullscreen(Document
* aDocument
);
1963 * Handles any pending fullscreen in aDocument or its subdocuments.
1965 * Returns whether there is any fullscreen request handled.
1967 static bool HandlePendingFullscreenRequests(Document
* aDocument
);
1970 * Clear pending fullscreen in aDocument.
1972 static void ClearPendingFullscreenRequests(Document
* aDocument
);
1974 // ScreenOrientation related APIs
1976 void ClearOrientationPendingPromise();
1977 bool SetOrientationPendingPromise(Promise
* aPromise
);
1978 Promise
* GetOrientationPendingPromise() const {
1979 return mOrientationPendingPromise
;
1982 //----------------------------------------------------------------------
1984 // Document notification API's
1987 * Add a new observer of document change notifications. Whenever
1988 * content is changed, appended, inserted or removed the observers are
1989 * informed. An observer that is already observing the document must
1990 * not be added without being removed first.
1992 void AddObserver(nsIDocumentObserver
* aObserver
);
1995 * Remove an observer of document change notifications. This will
1996 * return false if the observer cannot be found.
1998 bool RemoveObserver(nsIDocumentObserver
* aObserver
);
2000 // Observation hooks used to propagate notifications to document observers.
2001 // BeginUpdate must be called before any batch of modifications of the
2002 // content model or of style data, EndUpdate must be called afterward.
2003 // To make this easy and painless, use the mozAutoDocUpdate helper class.
2006 uint32_t UpdateNestingLevel() { return mUpdateNestLevel
; }
2009 virtual void EndLoad();
2012 READYSTATE_UNINITIALIZED
= 0,
2013 READYSTATE_LOADING
= 1,
2014 READYSTATE_INTERACTIVE
= 3,
2015 READYSTATE_COMPLETE
= 4
2017 // Set the readystate of the document. If aUpdateTimingInformation is true,
2018 // this will record relevant timestamps in the document's performance timing.
2019 // Some consumers (document.open is the only one right now, actually) don't
2020 // want to do that, though.
2021 void SetReadyStateInternal(ReadyState
, bool aUpdateTimingInformation
= true);
2022 ReadyState
GetReadyStateEnum() { return mReadyState
; }
2024 void NotifyLoading(bool aNewParentIsLoading
, const ReadyState
& aCurrentState
,
2025 ReadyState aNewState
);
2027 void NotifyAbortedLoad();
2029 // Notify that an element changed state. This must happen under a
2030 // scriptblocker but NOT within a begin/end update.
2031 void ElementStateChanged(Element
*, ElementState
);
2033 // Update a set of document states that may have changed.
2034 // This should only be called by callers whose state is also reflected in the
2035 // implementation of Document::GetDocumentState.
2037 // aNotify controls whether we notify our DocumentStatesChanged observers.
2038 void UpdateDocumentStates(DocumentState aMaybeChangedStates
, bool aNotify
);
2040 void ResetDocumentDirection();
2042 // Observation hooks for style data to propagate notifications
2043 // to document observers
2044 void RuleChanged(StyleSheet
&, css::Rule
*, StyleRuleChangeKind
);
2045 void RuleAdded(StyleSheet
&, css::Rule
&);
2046 void RuleRemoved(StyleSheet
&, css::Rule
&);
2047 void SheetCloned(StyleSheet
&) {}
2048 void ImportRuleLoaded(CSSImportRule
&, StyleSheet
&);
2051 * Flush notifications for this document and its parent documents
2052 * (since those may affect the layout of this one).
2054 void FlushPendingNotifications(FlushType aType
);
2057 * Another variant of the above FlushPendingNotifications. This function
2058 * takes a ChangesToFlush to specify whether throttled animations are flushed
2060 * If in doubt, use the above FlushPendingNotifications.
2062 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2063 void FlushPendingNotifications(ChangesToFlush aFlush
);
2066 * Calls FlushPendingNotifications on any external resources this document
2067 * has. If this document has no external resources or is an external resource
2068 * itself this does nothing. This should only be called with
2069 * aType >= FlushType::Style.
2071 void FlushExternalResources(FlushType aType
);
2073 void AddWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2074 void RemoveWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2076 // Triggers an update of <svg:use> element shadow trees.
2077 void UpdateSVGUseElementShadowTrees() {
2078 if (mSVGUseElementsNeedingShadowTreeUpdate
.IsEmpty()) {
2081 DoUpdateSVGUseElementShadowTrees();
2085 * Only to be used inside Gecko, you can't really do anything with the
2086 * pointer outside Gecko anyway.
2088 nsNodeInfoManager
* NodeInfoManager() const { return mNodeInfoManager
; }
2091 * Reset the document using the given channel and loadgroup. This works
2092 * like ResetToURI, but also sets the document's channel to aChannel.
2093 * The principal of the document will be set from the channel.
2095 virtual void Reset(nsIChannel
* aChannel
, nsILoadGroup
* aLoadGroup
);
2098 * Reset this document to aURI, aLoadGroup, aPrincipal and
2099 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2100 * content principal based on aURI will be used.
2102 virtual void ResetToURI(nsIURI
* aURI
, nsILoadGroup
* aLoadGroup
,
2103 nsIPrincipal
* aPrincipal
,
2104 nsIPrincipal
* aPartitionedPrincipal
);
2107 * Set the container (docshell) for this document. Virtual so that
2108 * docshell can call it.
2110 virtual void SetContainer(nsDocShell
* aContainer
);
2113 * Get the container (docshell) for this document.
2115 nsISupports
* GetContainer() const;
2118 * Get the container's load context for this document.
2120 nsILoadContext
* GetLoadContext() const;
2123 * Get docshell the for this document.
2125 nsIDocShell
* GetDocShell() const;
2128 * Set and get XML declaration. If aVersion is null there is no declaration.
2129 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2130 * was no standalone parameter in the declaration, that it was given as no,
2131 * or that it was given as yes.
2133 void SetXMLDeclaration(const char16_t
* aVersion
, const char16_t
* aEncoding
,
2134 const int32_t aStandalone
);
2135 void GetXMLDeclaration(nsAString
& aVersion
, nsAString
& aEncoding
,
2136 nsAString
& Standalone
);
2139 * Returns the bits for the color-scheme specified by the
2140 * <meta name="color-scheme">.
2142 uint8_t GetColorSchemeBits() const { return mColorSchemeBits
; }
2145 * Traverses the DOM and computes the supported color schemes as per
2146 * https://html.spec.whatwg.org/#meta-color-scheme
2148 void RecomputeColorScheme();
2149 void AddColorSchemeMeta(HTMLMetaElement
&);
2150 void RemoveColorSchemeMeta(HTMLMetaElement
&);
2153 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2154 * regular HTML document with Content-Type "text/html", image documents and
2155 * media documents). Returns false for XHTML and any other documents parsed
2156 * by the XML parser.
2158 bool IsHTMLDocument() const { return mType
== eHTML
; }
2159 bool IsHTMLOrXHTML() const { return mType
== eHTML
|| mType
== eXHTML
; }
2160 bool IsImageDocument() const {
2161 return MediaDocumentKind() == MediaDocumentKind::Image
;
2163 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2164 bool IsSVGDocument() const { return mType
== eSVG
; }
2165 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2166 bool LoadsFullXULStyleSheetUpFront() {
2167 if (IsSVGDocument()) {
2170 return AllowXULXBL();
2173 bool IsScriptEnabled() const;
2176 * Returns true if this document was created from a nsXULPrototypeDocument.
2178 bool LoadedFromPrototype() const { return mPrototypeDocument
; }
2180 * Returns the prototype the document was created from, or null if it was not
2181 * created from a prototype.
2183 nsXULPrototypeDocument
* GetPrototype() const { return mPrototypeDocument
; }
2185 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument
; }
2186 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument
) {
2187 mIsTopLevelContentDocument
= aIsTopLevelContentDocument
;
2190 bool IsContentDocument() const { return mIsContentDocument
; }
2191 void SetIsContentDocument(bool aIsContentDocument
) {
2192 mIsContentDocument
= aIsContentDocument
;
2195 void ProcessMETATag(HTMLMetaElement
* aMetaElement
);
2197 * Create an element with the specified name, prefix and namespace ID.
2198 * Returns null if element name parsing failed.
2200 already_AddRefed
<Element
> CreateElem(const nsAString
& aName
, nsAtom
* aPrefix
,
2201 int32_t aNamespaceID
,
2202 const nsAString
* aIs
= nullptr);
2205 * Get the security info (i.e. SSL state etc) that the document got
2206 * from the channel/document that created the content of the
2211 nsITransportSecurityInfo
* GetSecurityInfo() { return mSecurityInfo
; }
2214 * Get the channel that failed to load and resulted in an error page, if it
2215 * exists. This is only relevant to error pages.
2217 nsIChannel
* GetFailedChannel() const { return mFailedChannel
; }
2220 * This function checks if the document that is trying to access
2221 * GetNetErrorInfo is a trusted about net error page or not.
2223 static bool CallerIsTrustedAboutNetError(JSContext
* aCx
, JSObject
* aObject
);
2226 * This function checks if the document that is trying to access
2227 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2229 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext
* aCx
,
2233 * Get security info like error code for a failed channel. This
2234 * property is only exposed to about:neterror documents.
2236 void GetNetErrorInfo(mozilla::dom::NetErrorInfo
& aInfo
, ErrorResult
& aRv
);
2239 * This function checks if the document that is trying to access
2240 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2242 static bool CallerIsTrustedAboutCertError(JSContext
* aCx
, JSObject
* aObject
);
2245 * This function checks if the privilege storage access api is available for
2246 * the caller. We only allow privilege SSA to be called by system principal
2247 * and webcompat extension.
2249 static bool CallerCanAccessPrivilegeSSA(JSContext
* aCx
, JSObject
* aObject
);
2252 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2253 * failed Channel. This property is only exposed for about:certerror
2256 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo
& aInfo
,
2260 * Set the channel that failed to load and resulted in an error page.
2261 * This is only relevant to error pages.
2263 void SetFailedChannel(nsIChannel
* aChannel
) { mFailedChannel
= aChannel
; }
2266 * Returns the default namespace ID used for elements created in this
2269 int32_t GetDefaultNamespaceID() const { return mDefaultElementType
; }
2271 void RemoveAllProperties();
2272 void RemoveAllPropertiesFor(nsINode
* aNode
);
2274 nsPropertyTable
& PropertyTable() { return mPropertyTable
; }
2277 * Sets the ID used to identify this part of the multipart document
2279 void SetPartID(uint32_t aID
) { mPartID
= aID
; }
2282 * Return the ID used to identify this part of the multipart document
2284 uint32_t GetPartID() const { return mPartID
; }
2287 * Sanitize the document by resetting all input elements and forms that have
2288 * autocomplete=off to their default values.
2289 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2291 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Sanitize();
2294 * Enumerate all subdocuments.
2295 * The enumerator callback should return CallState::Continue to continue
2296 * enumerating, or CallState::Stop to stop. This will never get passed a null
2299 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
2300 void EnumerateSubDocuments(SubDocEnumFunc aCallback
);
2303 * Collect all the descendant documents for which |aCalback| returns true.
2304 * The callback function must not mutate any state for the given document.
2306 using nsDocTestFunc
= bool (*)(const Document
* aDocument
);
2307 void CollectDescendantDocuments(nsTArray
<RefPtr
<Document
>>& aDescendants
,
2308 nsDocTestFunc aCallback
) const;
2311 * Check whether it is safe to cache the presentation of this document
2312 * and all of its subdocuments (depending on the 3rd param). This method
2313 * checks the following conditions recursively:
2314 * - Some document types, such as plugin documents, cannot be safely cached.
2315 * - If there are any pending requests, we don't allow the presentation
2316 * to be cached. Ideally these requests would be suspended and resumed,
2317 * but that is difficult in some cases, such as XMLHttpRequest.
2318 * - If there are any beforeunload or unload listeners, we must fire them
2319 * for correctness, but this likely puts the document into a state where
2320 * it would not function correctly if restored.
2322 * |aNewRequest| should be the request for a new document which will
2323 * replace this document in the docshell. The new document's request
2324 * will be ignored when checking for active requests. If there is no
2325 * request associated with the new document, this parameter may be null.
2327 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2328 * combination is when we try to BFCache aNewRequest
2330 virtual bool CanSavePresentation(nsIRequest
* aNewRequest
,
2331 uint32_t& aBFCacheCombo
,
2332 bool aIncludeSubdocuments
,
2333 bool aAllowUnloadListeners
= true);
2336 * Pass principals if the correct ones are known when calling Init. That way
2337 * NodeInfoManager doesn't need to create a temporary null principal.
2339 virtual nsresult
Init(nsIPrincipal
* aPrincipal
,
2340 nsIPrincipal
* aPartitionedPrincipal
);
2343 * Notify the document that its associated ContentViewer is being destroyed.
2344 * This releases circular references so that the document can go away.
2345 * Destroy() is only called on documents that have a content viewer.
2347 virtual void Destroy();
2350 * Notify the document that its associated ContentViewer is no longer
2351 * the current viewer for the docshell. The document might still
2352 * be rendered in "zombie state" until the next document is ready.
2353 * The document should save form control state.
2355 void RemovedFromDocShell();
2358 * Get the layout history state that should be used to save and restore state
2359 * for nodes in this document. This may return null; if that happens state
2360 * saving and restoration is not possible.
2362 already_AddRefed
<nsILayoutHistoryState
> GetLayoutHistoryState() const;
2365 * Methods that can be used to prevent onload firing while an event that
2366 * should block onload is posted. onload is guaranteed to not fire until
2367 * either all calls to BlockOnload() have been matched by calls to
2368 * UnblockOnload() or the load has been stopped altogether (by the user
2369 * pressing the Stop button, say).
2373 * @param aFireSync whether to fire onload synchronously. If false,
2374 * onload will fire asynchronously after all onload blocks have been
2375 * removed. It will NOT fire from inside UnblockOnload. If true,
2376 * onload may fire from inside UnblockOnload.
2378 void UnblockOnload(bool aFireSync
);
2380 // Only BlockOnload should call this!
2381 void AsyncBlockOnload();
2383 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded
; }
2385 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnblockDOMContentLoaded();
2388 * Notification that the page has been shown, for documents which are loaded
2389 * into a DOM window. This corresponds to the completion of document load,
2390 * or to the page's presentation being restored into an existing DOM window.
2391 * This notification fires applicable DOM events to the content window. See
2392 * PageTransitionEvent.webidl for a description of the |aPersisted|
2393 * parameter. If aDispatchStartTarget is null, the pageshow event is
2394 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2395 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2396 * event is only dispatched to listeners in the system group.
2397 * Note: if aDispatchStartTarget isn't null, the showing state of the
2398 * document won't be altered.
2400 virtual void OnPageShow(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2401 bool aOnlySystemGroup
= false);
2404 * Notification that the page has been hidden, for documents which are loaded
2405 * into a DOM window. This corresponds to the unloading of the document, or
2406 * to the document's presentation being saved but removed from an existing
2407 * DOM window. This notification fires applicable DOM events to the content
2408 * window. See PageTransitionEvent.webidl for a description of the
2409 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2410 * event is dispatched on the ScriptGlobalObject for this document,
2411 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2412 * true, the event is only dispatched to listeners in the system group.
2413 * Note: if aDispatchStartTarget isn't null, the showing state of the
2414 * document won't be altered.
2416 void OnPageHide(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2417 bool aOnlySystemGroup
= false);
2420 * We record the set of links in the document that are relevant to
2424 * Notification that an element is a link that is relevant to style.
2426 void AddStyleRelevantLink(Link
* aLink
) {
2427 NS_ASSERTION(aLink
, "Passing in a null link. Expect crashes RSN!");
2429 NS_ASSERTION(!mStyledLinks
.Contains(aLink
),
2430 "Document already knows about this Link!");
2431 mStyledLinksCleared
= false;
2433 mStyledLinks
.Insert(aLink
);
2437 * Notification that an element is a link and its URI might have been
2438 * changed or the element removed. If the element is still a link relevant
2439 * to style, then someone must ensure that AddStyleRelevantLink is
2440 * (eventually) called on it again.
2442 void ForgetLink(Link
* aLink
) {
2443 MOZ_ASSERT(aLink
, "Passing in a null link. Expect crashes RSN!");
2444 MOZ_ASSERT(mStyledLinks
.Contains(aLink
) || mStyledLinksCleared
,
2445 "Document knows nothing about this Link!");
2446 mStyledLinks
.Remove(aLink
);
2449 // Refreshes the hrefs of all the links in the document.
2450 void RefreshLinkHrefs();
2453 * Support for window.matchMedia()
2456 already_AddRefed
<MediaQueryList
> MatchMedia(const nsACString
& aMediaQueryList
,
2457 CallerType aCallerType
);
2459 LinkedList
<MediaQueryList
>& MediaQueryLists() { return mDOMMediaQueryLists
; }
2462 * Get the compatibility mode for this document
2464 nsCompatibility
GetCompatibilityMode() const { return mCompatMode
; }
2467 * Check whether we've ever fired a DOMTitleChanged event for this
2470 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange
; }
2473 * To batch DOMSubtreeModified, document needs to be informed when
2474 * a mutation event might be dispatched, even if the event isn't actually
2475 * created because there are no listeners for it.
2477 * @param aTarget is the target for the mutation event.
2479 void MayDispatchMutationEvent(nsINode
* aTarget
) {
2480 if (mSubtreeModifiedDepth
> 0) {
2481 mSubtreeModifiedTargets
.AppendObject(aTarget
);
2486 * Marks as not-going-to-be-collected for the given generation of
2489 void MarkUncollectableForCCGeneration(uint32_t aGeneration
) {
2490 mMarkedCCGeneration
= aGeneration
;
2494 * Gets the cycle collector generation this document is marked for.
2496 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration
; }
2499 * Returns whether this document is cookie averse. See
2500 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2502 bool IsCookieAverse() const {
2503 // If we are a document that "has no browsing context."
2504 if (!GetInnerWindow()) {
2508 // If we are a document "whose URL's scheme is not a network scheme."
2509 // NB: Explicitly allow file: URIs to store cookies.
2511 return !NodePrincipal()->SchemeIs("http") &&
2512 !NodePrincipal()->SchemeIs("https") &&
2513 !NodePrincipal()->SchemeIs("file");
2516 bool IsLoadedAsData() { return mLoadedAsData
; }
2518 void SetAddedToMemoryReportAsDataDocument() {
2519 mAddedToMemoryReportingAsDataDocument
= true;
2522 void UnregisterFromMemoryReportingForDataDocument();
2524 bool MayStartLayout() { return mMayStartLayout
; }
2526 void SetMayStartLayout(bool aMayStartLayout
);
2528 already_AddRefed
<nsIDocumentEncoder
> GetCachedEncoder();
2530 void SetCachedEncoder(already_AddRefed
<nsIDocumentEncoder
> aEncoder
);
2532 // In case of failure, the document really can't initialize the frame loader.
2533 nsresult
InitializeFrameLoader(nsFrameLoader
* aLoader
);
2534 // In case of failure, the caller must handle the error, for example by
2535 // finalizing frame loader asynchronously.
2536 nsresult
FinalizeFrameLoader(nsFrameLoader
* aLoader
, nsIRunnable
* aFinalizer
);
2537 // Removes the frame loader of aShell from the initialization list.
2538 void TryCancelFrameLoaderInitialization(nsIDocShell
* aShell
);
2541 * Check whether this document is a root document that is not an
2542 * external resource.
2544 bool IsRootDisplayDocument() const {
2545 return !mParentDocument
&& !mDisplayDocument
;
2548 bool ChromeRulesEnabled() const { return mChromeRulesEnabled
; }
2550 bool IsInChromeDocShell() const {
2551 const Document
* root
= this;
2552 while (const Document
* displayDoc
= root
->GetDisplayDocument()) {
2555 return root
->mInChromeDocShell
;
2558 bool IsDevToolsDocument() const { return mIsDevToolsDocument
; }
2560 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage
; }
2562 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage
= true; }
2564 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument
; }
2566 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument
= true; }
2568 bool IsResourceDoc() const {
2569 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2570 mHasDisplayDocument
; // Are we an external resource doc?
2574 * Get the document for which this document is an external resource. This
2575 * will be null if this document is not an external resource. Otherwise,
2576 * GetDisplayDocument() will return a non-null document, and
2577 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2579 Document
* GetDisplayDocument() const { return mDisplayDocument
; }
2582 * Set the display document for this document. aDisplayDocument must not be
2585 void SetDisplayDocument(Document
* aDisplayDocument
) {
2586 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2587 "Shouldn't set mDisplayDocument on documents that already "
2588 "have a presentation or a docshell or a window");
2589 MOZ_ASSERT(aDisplayDocument
, "Must not be null");
2590 MOZ_ASSERT(aDisplayDocument
!= this, "Should be different document");
2591 MOZ_ASSERT(!aDisplayDocument
->GetDisplayDocument(),
2592 "Display documents should not nest");
2593 mDisplayDocument
= aDisplayDocument
;
2594 mHasDisplayDocument
= !!aDisplayDocument
;
2598 * Request an external resource document for aURI. This will return the
2599 * resource document if available. If one is not available yet, it will
2600 * start loading as needed, and the pending load object will be returned in
2601 * aPendingLoad so that the caller can register an observer to wait for the
2602 * load. If this function returns null and doesn't return a pending load,
2603 * that means that there is no resource document for this URI and won't be
2604 * one in the future.
2606 * @param aURI the URI to get
2607 * @param aReferrerInfo the referrerInfo of the request
2608 * @param aRequestingNode the node making the request
2609 * @param aPendingLoad the pending load for this request, if any
2611 Document
* RequestExternalResource(nsIURI
* aURI
,
2612 nsIReferrerInfo
* aReferrerInfo
,
2613 nsINode
* aRequestingNode
,
2614 ExternalResourceLoad
** aPendingLoad
);
2617 * Enumerate the external resource documents associated with this document.
2618 * The enumerator callback should return CallState::Continue to continue
2619 * enumerating, or CallState::Stop to stop. This callback will never get
2620 * passed a null aDocument.
2622 void EnumerateExternalResources(SubDocEnumFunc aCallback
);
2624 dom::ExternalResourceMap
& ExternalResourceMap() {
2625 return mExternalResourceMap
;
2629 * Return whether the document is currently showing (in the sense of
2630 * OnPageShow() having been called already and OnPageHide() not having been
2633 bool IsShowing() const { return mIsShowing
; }
2635 * Return whether the document is currently visible (in the sense of
2636 * OnPageHide having been called and OnPageShow not yet having been called)
2638 bool IsVisible() const { return mVisible
; }
2640 void SetSuppressedEventListener(EventListener
* aListener
);
2642 EventListener
* GetSuppressedEventListener() {
2643 return mSuppressedEventListener
;
2647 * Return true when this document is active, i.e., an active document
2648 * in a content viewer and not in the bfcache.
2649 * This does NOT match the "active document" concept in the WHATWG spec -
2650 * see IsCurrentActiveDocument.
2652 bool IsActive() const;
2655 * Return true if this is the current active document for its
2656 * docshell. Note that a docshell may have multiple active documents
2657 * due to the bfcache -- this should be used when you need to
2658 * differentiate the *current* active document from any active
2661 bool IsCurrentActiveDocument() const {
2662 nsPIDOMWindowInner
* inner
= GetInnerWindow();
2663 return inner
&& inner
->IsCurrentInnerWindow() && inner
->GetDoc() == this;
2667 * Returns whether this document should perform image loads.
2669 bool ShouldLoadImages() const {
2670 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2671 // images can themselves have data: URL image references.
2672 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2676 void SetHasPrintCallbacks() {
2677 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2678 mHasPrintCallbacks
= true;
2681 bool HasPrintCallbacks() const { return mHasPrintCallbacks
; }
2684 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2685 * the document's activity changes such as OnPageHide, visibility, activity.
2686 * The ActivityObserver objects can be nsIObjectLoadingContent or
2687 * nsIDocumentActivity or HTMLMEdiaElement.
2689 void RegisterActivityObserver(nsISupports
* aSupports
);
2690 bool UnregisterActivityObserver(nsISupports
* aSupports
);
2691 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2692 using ActivityObserverEnumerator
= FunctionRef
<void(nsISupports
*)>;
2693 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator
);
2695 void NotifyActivityChanged();
2697 // Indicates whether mAnimationController has been (lazily) initialized.
2698 // If this returns true, we're promising that GetAnimationController()
2699 // will have a non-null return value.
2700 bool HasAnimationController() { return !!mAnimationController
; }
2702 // Getter for this document's SMIL Animation Controller. Performs lazy
2703 // initialization, if this document supports animation and if
2704 // mAnimationController isn't yet initialized.
2706 // If HasAnimationController is true, this is guaranteed to return non-null.
2707 SMILAnimationController
* GetAnimationController();
2709 // Gets the tracker for animations that are waiting to start.
2710 // Returns nullptr if there is no pending animation tracker for this document
2711 // which will be the case if there have never been any CSS animations or
2712 // transitions on elements in the document.
2713 PendingAnimationTracker
* GetPendingAnimationTracker() {
2714 return mPendingAnimationTracker
;
2717 // Gets the tracker for animations that are waiting to start and
2718 // creates it if it doesn't already exist. As a result, the return value
2719 // will never be nullptr.
2720 PendingAnimationTracker
* GetOrCreatePendingAnimationTracker();
2722 // Gets the tracker for scroll-driven animations that are waiting to start.
2723 // Returns nullptr if there is no scroll-driven animation tracker for this
2724 // document which will be the case if there have never been any scroll-driven
2725 // animations in the document.
2726 ScrollTimelineAnimationTracker
* GetScrollTimelineAnimationTracker() {
2727 return mScrollTimelineAnimationTracker
;
2730 // Gets the tracker for scroll-driven animations that are waiting to start and
2731 // creates it if it doesn't already exist. As a result, the return value
2732 // will never be nullptr.
2733 ScrollTimelineAnimationTracker
* GetOrCreateScrollTimelineAnimationTracker();
2736 * Prevents user initiated events from being dispatched to the document and
2739 void SuppressEventHandling(uint32_t aIncrease
= 1);
2742 * Unsuppress event handling.
2743 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2746 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnsuppressEventHandlingAndFireEvents(
2749 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed
; }
2751 bool IsEventHandlingEnabled() const {
2752 return !EventHandlingSuppressed() && mScriptGlobalObject
;
2755 bool WouldScheduleFrameRequestCallbacks() const {
2756 // If this function changes to depend on some other variable, make sure to
2757 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2758 // where that variable can change.
2759 return mPresShell
&& IsEventHandlingEnabled();
2762 void DecreaseEventSuppression() {
2763 MOZ_ASSERT(mEventsSuppressed
);
2764 --mEventsSuppressed
;
2765 UpdateFrameRequestCallbackSchedulingState();
2769 * Some clipboard commands are unconditionally enabled on some documents, so
2770 * as to always dispatch copy / paste events even though you'd normally not be
2773 bool AreClipboardCommandsUnconditionallyEnabled() const;
2776 * Note a ChannelEventQueue which has been suspended on the document's behalf
2777 * to prevent XHRs from running content scripts while event handling is
2778 * suppressed. The document is responsible for resuming the queue after
2779 * event handling is unsuppressed.
2781 void AddSuspendedChannelEventQueue(net::ChannelEventQueue
* aQueue
);
2784 * Returns true if a postMessage event should be suspended instead of running.
2785 * The document is responsible for running the event later, in the order they
2788 bool SuspendPostMessageEvent(PostMessageEvent
* aEvent
);
2791 * Run any suspended postMessage events, or clear them.
2793 void FireOrClearPostMessageEvents(bool aFireEvents
);
2795 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent
= true; }
2798 * Flag whether we're about to fire the window's load event for this document.
2800 void SetLoadEventFiring(bool aFiring
) { mLoadEventFiring
= aFiring
; }
2803 * Test whether we should be firing a load event for this document after a
2804 * document.close(). This is public and on Document, instead of being private
2805 * to Document, because we need to go through the normal docloader logic
2806 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2807 * semantics of firing the load event; we just don't want to fire the load
2808 * event if this tests true. So we need the docloader to be able to access
2811 * This method should only be called at the point when the load event is about
2812 * to be fired. It resets the "skip" flag, so it is not idempotent.
2814 bool SkipLoadEventAfterClose() {
2815 bool skip
= mSkipLoadEventAfterClose
;
2816 mSkipLoadEventAfterClose
= false;
2821 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2823 void IncrementIgnoreDestructiveWritesCounter() {
2824 ++mIgnoreDestructiveWritesCounter
;
2828 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2830 void DecrementIgnoreDestructiveWritesCounter() {
2831 --mIgnoreDestructiveWritesCounter
;
2834 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch
; }
2837 * Returns true if this document is allowed to contain XUL element and
2838 * use non-builtin XBL bindings.
2840 bool AllowXULXBL() {
2841 return mAllowXULXBL
== eTriTrue
? true
2842 : mAllowXULXBL
== eTriFalse
? false
2843 : InternalAllowXULXBL();
2847 * Returns true if this document is allowed to load DTDs from UI resources
2850 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks
; }
2852 void ForceEnableXULXBL() { mAllowXULXBL
= eTriTrue
; }
2854 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks
= true; }
2857 * Returns the template content owner document that owns the content of
2858 * HTMLTemplateElement.
2860 Document
* GetTemplateContentsOwner();
2862 Document
* GetTemplateContentsOwnerIfExists() const {
2863 return mTemplateContentsOwner
.get();
2866 bool IsTemplateContentsOwner() const {
2867 // Template contents owner documents are the template contents owner of
2869 return mTemplateContentsOwner
== this;
2873 * Returns true if this document is a static clone of a normal document.
2875 * We create static clones for print preview and printing (possibly other
2876 * things in future).
2878 * Note that static documents are also "loaded as data" (if this method
2879 * returns true, IsLoadedAsData() will also return true).
2881 bool IsStaticDocument() const { return mIsStaticDocument
; }
2884 * Clones the document along with any subdocuments, stylesheet, etc.
2886 * The resulting document and everything it contains (including any
2887 * sub-documents) are created purely via cloning. The returned documents and
2888 * any sub-documents are "loaded as data" documents to preserve the state as
2889 * it was during the clone process (we don't want external resources to load
2890 * and replace the cloned resources).
2892 * @param aCloneContainer The container for the clone document.
2893 * @param aContentViewer The viewer for the clone document. Must be the viewer
2894 * of aCloneContainer, but callers must have a reference
2895 * to it already and ensure it's not null.
2896 * @param aPrintSettings The print settings for this clone.
2897 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2899 already_AddRefed
<Document
> CreateStaticClone(
2900 nsIDocShell
* aCloneContainer
, nsIContentViewer
* aContentViewer
,
2901 nsIPrintSettings
* aPrintSettings
, bool* aOutHasInProcessPrintCallbacks
);
2904 * If this document is a static clone, this returns the original
2907 Document
* GetOriginalDocument() const {
2908 MOZ_ASSERT(!mOriginalDocument
|| !mOriginalDocument
->GetOriginalDocument());
2909 return mOriginalDocument
;
2913 * If this document is a static clone, let the original document know that
2914 * we're going away and then release our reference to it.
2916 void UnlinkOriginalDocumentIfStatic();
2919 * These are called by the parser as it encounters <picture> tags, the end of
2920 * said tags, and possible picture <source srcset> sources respectively. These
2921 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2922 * expected to be marked void.
2924 * NOTE that the parser does not attempt to track the current picture nesting
2925 * level or whether the given <source> tag is within a picture -- it is only
2926 * guaranteed to order these calls properly with respect to
2927 * ResolvePreLoadImage.
2930 void PreloadPictureOpened() { mPreloadPictureDepth
++; }
2932 void PreloadPictureClosed();
2934 void PreloadPictureImageSource(const nsAString
& aSrcsetAttr
,
2935 const nsAString
& aSizesAttr
,
2936 const nsAString
& aTypeAttr
,
2937 const nsAString
& aMediaAttr
);
2940 * Called by the parser to resolve an image for preloading. The parser will
2941 * call the PreloadPicture* functions to inform us of possible <picture>
2942 * nesting and possible sources, which are used to inform URL selection
2943 * responsive <picture> or <img srcset> images. Unset attributes are expected
2944 * to be marked void.
2945 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2946 * true, false otherwise.
2948 already_AddRefed
<nsIURI
> ResolvePreloadImage(nsIURI
* aBaseURI
,
2949 const nsAString
& aSrcAttr
,
2950 const nsAString
& aSrcsetAttr
,
2951 const nsAString
& aSizesAttr
,
2954 * Called by nsParser to preload images. Can be removed and code moved
2955 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2956 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2957 * be a void string if the attr is not present.
2958 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2959 * when this image is for loading <picture> or <img srcset> images.
2961 void MaybePreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2962 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2963 bool aLinkPreload
, const TimeStamp
& aInitTimestamp
);
2964 void PreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2965 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2966 bool aLinkPreload
, uint64_t aEarlyHintPreloaderId
);
2969 * Called by images to forget an image preload when they start doing
2972 void ForgetImagePreload(nsIURI
* aURI
);
2975 * Called by the parser or the preload service to preload style sheets.
2976 * aCrossOriginAttr should be a void string if the attr is not present.
2978 SheetPreloadStatus
PreloadStyle(nsIURI
* aURI
, const Encoding
* aEncoding
,
2979 const nsAString
& aCrossOriginAttr
,
2980 ReferrerPolicyEnum aReferrerPolicy
,
2981 const nsAString
& aNonce
,
2982 const nsAString
& aIntegrity
,
2983 css::StylePreloadKind
,
2984 uint64_t aEarlyHintPreloaderId
);
2987 * Called by the chrome registry to load style sheets.
2989 * This always does a synchronous load, and parses as a normal document sheet.
2991 RefPtr
<StyleSheet
> LoadChromeSheetSync(nsIURI
* aURI
);
2994 * Returns true if the locale used for the document specifies a direction of
2995 * right to left. For chrome documents, this comes from the chrome registry.
2996 * This is used to determine the current state for the :-moz-locale-dir
2997 * pseudoclass so once can know whether a document is expected to be rendered
2998 * left-to-right or right-to-left.
3000 bool IsDocumentRightToLeft();
3003 * Called by Parser for link rel=preconnect
3005 void MaybePreconnect(nsIURI
* uri
, CORSMode aCORSMode
);
3008 * Set the document's pending state object (as serialized using structured
3011 void SetStateObject(nsIStructuredCloneContainer
* scContainer
);
3014 * Set the document's pending state object to the same state object as
3017 void SetStateObjectFrom(Document
* aDocument
) {
3018 SetStateObject(aDocument
->mStateObjectContainer
);
3022 * Returns true if there is a lightweight theme specified. This is used to
3023 * determine the state of the :-moz-lwtheme pseudo-class.
3025 bool ComputeDocumentLWTheme() const;
3026 void ResetDocumentLWTheme() {
3027 UpdateDocumentStates(DocumentState::LWTHEME
, true);
3030 // Whether we're a media document or not.
3031 enum class MediaDocumentKind
{
3038 virtual enum MediaDocumentKind
MediaDocumentKind() const {
3039 return MediaDocumentKind::NotMedia
;
3042 DocumentState
GetDocumentState() const { return mDocumentState
; }
3044 nsISupports
* GetCurrentContentSink();
3046 void ElementWithAutoFocusInserted(Element
* aAutoFocusCandidate
);
3047 MOZ_CAN_RUN_SCRIPT
void FlushAutoFocusCandidates();
3048 void ScheduleFlushAutoFocusCandidates();
3049 bool HasAutoFocusCandidates() const {
3050 return !mAutoFocusCandidates
.IsEmpty();
3053 void SetAutoFocusFired();
3055 void SetScrollToRef(nsIURI
* aDocumentURI
);
3056 MOZ_CAN_RUN_SCRIPT
void ScrollToRef();
3057 void ResetScrolledToRefAlready() { mScrolledToRefAlready
= false; }
3059 void SetChangeScrollPosWhenScrollingToRef(bool aValue
) {
3060 mChangeScrollPosWhenScrollingToRef
= aValue
;
3063 using DocumentOrShadowRoot::GetElementById
;
3064 using DocumentOrShadowRoot::GetElementsByClassName
;
3065 using DocumentOrShadowRoot::GetElementsByTagName
;
3066 using DocumentOrShadowRoot::GetElementsByTagNameNS
;
3068 DocumentTimeline
* Timeline();
3069 LinkedList
<DocumentTimeline
>& Timelines() { return mTimelines
; }
3071 SVGSVGElement
* GetSVGRootElement() const;
3073 nsresult
ScheduleFrameRequestCallback(FrameRequestCallback
& aCallback
,
3075 void CancelFrameRequestCallback(int32_t aHandle
);
3078 * Returns true if the handle refers to a callback that was canceled that
3079 * we did not find in our list of callbacks (e.g. because it is one of those
3080 * in the set of callbacks currently queued to be run).
3082 bool IsCanceledFrameRequestCallback(int32_t aHandle
) const;
3085 * Put this document's frame request callbacks into the provided
3086 * list, and forget about them.
3088 void TakeFrameRequestCallbacks(nsTArray
<FrameRequest
>& aCallbacks
);
3091 * @return true if this document's frame request callbacks should be
3092 * throttled. We throttle requestAnimationFrame for documents which aren't
3093 * visible (e.g. scrolled out of the viewport).
3095 bool ShouldThrottleFrameRequests() const;
3097 // This returns true when the document tree is being teared down.
3098 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion
; }
3100 dom::ImageTracker
* ImageTracker();
3102 // Adds an element to mResponsiveContent when the element is
3103 // added to the tree.
3104 void AddResponsiveContent(HTMLImageElement
* aContent
) {
3105 MOZ_ASSERT(aContent
);
3106 mResponsiveContent
.Insert(aContent
);
3109 // Removes an element from mResponsiveContent when the element is
3110 // removed from the tree.
3111 void RemoveResponsiveContent(HTMLImageElement
* aContent
) {
3112 MOZ_ASSERT(aContent
);
3113 mResponsiveContent
.Remove(aContent
);
3116 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement
&);
3117 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement
& aElement
) {
3118 mSVGUseElementsNeedingShadowTreeUpdate
.Remove(&aElement
);
3121 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement
& aElement
) const {
3122 return mSVGUseElementsNeedingShadowTreeUpdate
.Contains(&aElement
);
3125 using ShadowRootSet
= nsTHashSet
<ShadowRoot
*>;
3127 void AddComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3128 mComposedShadowRoots
.Insert(&aShadowRoot
);
3131 void RemoveComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3132 mComposedShadowRoots
.Remove(&aShadowRoot
);
3135 // If you're considering using this, you probably want to use
3136 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3138 bool IsComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3139 return mComposedShadowRoots
.Contains(&aShadowRoot
);
3142 const ShadowRootSet
& ComposedShadowRoots() const {
3143 return mComposedShadowRoots
;
3146 // WebIDL method for chrome code.
3147 void GetConnectedShadowRoots(nsTArray
<RefPtr
<ShadowRoot
>>&) const;
3149 // Notifies any responsive content added by AddResponsiveContent upon media
3150 // features values changing.
3151 void NotifyMediaFeatureValuesChanged();
3153 nsresult
GetStateObject(JS::MutableHandle
<JS::Value
> aState
);
3155 nsDOMNavigationTiming
* GetNavigationTiming() const { return mTiming
; }
3157 void SetNavigationTiming(nsDOMNavigationTiming
* aTiming
);
3159 nsContentList
* ImageMapList();
3161 // Add aLink to the set of links that need their status resolved.
3162 void RegisterPendingLinkUpdate(Link
* aLink
);
3164 // Update state on links in mLinksToUpdate.
3165 void FlushPendingLinkUpdates();
3167 bool HasWarnedAbout(DeprecatedOperations aOperation
) const;
3169 DeprecatedOperations aOperation
, bool asError
= false,
3170 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3172 #define DOCUMENT_WARNING(_op) e##_op,
3173 enum DocumentWarnings
{
3174 #include "nsDocumentWarningList.h"
3175 eDocumentWarningCount
3177 #undef DOCUMENT_WARNING
3178 bool HasWarnedAbout(DocumentWarnings aWarning
) const;
3180 DocumentWarnings aWarning
, bool asError
= false,
3181 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3183 // This method may fire a DOM event; if it does so it will happen
3186 // Whether the event fires is controlled by the argument.
3187 enum class DispatchVisibilityChange
{ No
, Yes
};
3188 void UpdateVisibilityState(
3189 DispatchVisibilityChange
= DispatchVisibilityChange::Yes
);
3191 // Posts an event to call UpdateVisibilityState.
3192 void PostVisibilityUpdateEvent();
3194 bool IsSyntheticDocument() const { return mIsSyntheticDocument
; }
3196 // Adds the size of a given node, which must not be a document node, to the
3197 // window sizes passed-in.
3198 static void AddSizeOfNodeTree(nsINode
&, nsWindowSizes
&);
3200 // Note: Document is a sub-class of nsINode, which has a
3201 // SizeOfExcludingThis function. However, because Document objects can
3202 // only appear at the top of the DOM tree, we have a specialized measurement
3203 // function which returns multiple sizes.
3204 virtual void DocAddSizeOfExcludingThis(nsWindowSizes
& aWindowSizes
) const;
3205 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3206 // because Document inherits from nsINode; see the comment above the
3207 // declaration of nsINode::SizeOfIncludingThis.
3208 virtual void DocAddSizeOfIncludingThis(nsWindowSizes
& aWindowSizes
) const;
3210 void ConstructUbiNode(void* storage
) override
;
3212 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers
; }
3214 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers
= true; }
3216 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers
; }
3218 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers
= true; }
3220 bool IsInSyncOperation() { return mInSyncOperationCount
!= 0; }
3222 void SetIsInSyncOperation(bool aSync
);
3224 bool CreatingStaticClone() const { return mCreatingStaticClone
; }
3227 * Creates a new element in the HTML namespace with a local name given by
3230 already_AddRefed
<Element
> CreateHTMLElement(nsAtom
* aTag
);
3233 nsIGlobalObject
* GetParentObject() const { return GetScopeObject(); }
3234 static already_AddRefed
<Document
> Constructor(const GlobalObject
& aGlobal
,
3236 DOMImplementation
* GetImplementation(ErrorResult
& rv
);
3237 [[nodiscard
]] nsresult
GetURL(nsString
& retval
) const;
3238 [[nodiscard
]] nsresult
GetDocumentURI(nsString
& retval
) const;
3239 // Return the URI for the document.
3240 // The returned value may differ if the document is loaded via XHR, and
3241 // when accessed from chrome privileged script and
3242 // from content privileged script for compatibility.
3243 void GetDocumentURIFromJS(nsString
& aDocumentURI
, CallerType aCallerType
,
3244 ErrorResult
& aRv
) const;
3245 void GetCompatMode(nsString
& retval
) const;
3246 void GetCharacterSet(nsAString
& retval
) const;
3247 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3248 // GetDoctype defined above
3249 Element
* GetDocumentElement() const { return GetRootElement(); }
3251 WindowContext
* GetTopLevelWindowContext() const;
3253 // If the top-level ancestor content document for this document is in the same
3254 // process, returns it. Otherwise, returns null. This function is not
3255 // Fission-compatible, and should not be used in new code.
3256 Document
* GetTopLevelContentDocumentIfSameProcess();
3257 const Document
* GetTopLevelContentDocumentIfSameProcess() const;
3259 // Returns the associated app window if this is a top-level chrome document,
3261 already_AddRefed
<nsIAppWindow
> GetAppWindowIfToplevelChrome() const;
3263 already_AddRefed
<Element
> CreateElement(
3264 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3266 already_AddRefed
<Element
> CreateElementNS(
3267 const nsAString
& aNamespaceURI
, const nsAString
& aQualifiedName
,
3268 const ElementCreationOptionsOrString
& aOptions
, ErrorResult
& rv
);
3269 already_AddRefed
<Element
> CreateXULElement(
3270 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3272 already_AddRefed
<DocumentFragment
> CreateDocumentFragment() const;
3273 already_AddRefed
<nsTextNode
> CreateTextNode(const nsAString
& aData
) const;
3274 already_AddRefed
<nsTextNode
> CreateEmptyTextNode() const;
3275 already_AddRefed
<Comment
> CreateComment(const nsAString
& aData
) const;
3276 already_AddRefed
<ProcessingInstruction
> CreateProcessingInstruction(
3277 const nsAString
& target
, const nsAString
& data
, ErrorResult
& rv
) const;
3278 already_AddRefed
<nsINode
> ImportNode(nsINode
& aNode
, bool aDeep
,
3279 ErrorResult
& rv
) const;
3280 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3281 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode
* AdoptNode(
3282 nsINode
& aAdoptedNode
, ErrorResult
& rv
, bool aAcceptShadowRoot
= false);
3283 already_AddRefed
<Event
> CreateEvent(const nsAString
& aEventType
,
3284 CallerType aCallerType
,
3285 ErrorResult
& rv
) const;
3286 already_AddRefed
<nsRange
> CreateRange(ErrorResult
& rv
);
3287 already_AddRefed
<NodeIterator
> CreateNodeIterator(nsINode
& aRoot
,
3288 uint32_t aWhatToShow
,
3289 NodeFilter
* aFilter
,
3290 ErrorResult
& rv
) const;
3291 already_AddRefed
<TreeWalker
> CreateTreeWalker(nsINode
& aRoot
,
3292 uint32_t aWhatToShow
,
3293 NodeFilter
* aFilter
,
3294 ErrorResult
& rv
) const;
3295 // Deprecated WebIDL bits
3296 already_AddRefed
<CDATASection
> CreateCDATASection(const nsAString
& aData
,
3298 already_AddRefed
<Attr
> CreateAttribute(const nsAString
& aName
,
3300 already_AddRefed
<Attr
> CreateAttributeNS(const nsAString
& aNamespaceURI
,
3301 const nsAString
& aQualifiedName
,
3303 void GetInputEncoding(nsAString
& aInputEncoding
) const;
3304 already_AddRefed
<Location
> GetLocation() const;
3305 void GetDomain(nsAString
& aDomain
);
3306 void SetDomain(const nsAString
& aDomain
, mozilla::ErrorResult
& rv
);
3307 void GetCookie(nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3308 void SetCookie(const nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3309 void GetReferrer(nsAString
& aReferrer
) const;
3310 void GetLastModified(nsAString
& aLastModified
) const;
3311 void GetReadyState(nsAString
& aReadyState
) const;
3313 void GetTitle(nsAString
& aTitle
);
3314 void SetTitle(const nsAString
& aTitle
, ErrorResult
& rv
);
3315 void GetDir(nsAString
& aDirection
) const;
3316 void SetDir(const nsAString
& aDirection
);
3317 nsIHTMLCollection
* Images();
3318 nsIHTMLCollection
* Embeds();
3319 nsIHTMLCollection
* Plugins() { return Embeds(); }
3320 nsIHTMLCollection
* Links();
3321 nsIHTMLCollection
* Forms();
3322 nsIHTMLCollection
* Scripts();
3323 already_AddRefed
<nsContentList
> GetElementsByName(const nsAString
& aName
) {
3324 return GetFuncStringContentList
<nsCachableElementsByNameNodeList
>(
3325 this, MatchNameAttribute
, nullptr, UseExistingNameString
, aName
);
3327 Document
* Open(const mozilla::dom::Optional
<nsAString
>& /* unused */,
3328 const mozilla::dom::Optional
<nsAString
>& /* unused */,
3329 mozilla::ErrorResult
& aError
);
3330 mozilla::dom::Nullable
<mozilla::dom::WindowProxyHolder
> Open(
3331 const nsAString
& aURL
, const nsAString
& aName
, const nsAString
& aFeatures
,
3332 mozilla::ErrorResult
& rv
);
3333 void Close(mozilla::ErrorResult
& rv
);
3334 void Write(const mozilla::dom::Sequence
<nsString
>& aText
,
3335 mozilla::ErrorResult
& rv
);
3336 void Writeln(const mozilla::dom::Sequence
<nsString
>& aText
,
3337 mozilla::ErrorResult
& rv
);
3338 Nullable
<WindowProxyHolder
> GetDefaultView() const;
3339 Element
* GetActiveElement();
3340 enum class IncludeChromeOnly
: bool { No
, Yes
};
3341 // TODO(emilio): Audit callers and remove the default argument, some seem like
3342 // they could want the IncludeChromeOnly::Yes version.
3343 nsIContent
* GetUnretargetedFocusedContent(
3344 IncludeChromeOnly
= IncludeChromeOnly::No
) const;
3346 * Return true if this document or a subdocument has focus.
3348 bool HasFocus(ErrorResult
& rv
) const;
3351 * Return true if this document itself has focus.
3353 bool ThisDocumentHasFocus() const;
3355 void GetDesignMode(nsAString
& aDesignMode
);
3356 void SetDesignMode(const nsAString
& aDesignMode
,
3357 nsIPrincipal
& aSubjectPrincipal
, mozilla::ErrorResult
& rv
);
3358 void SetDesignMode(const nsAString
& aDesignMode
,
3359 const mozilla::Maybe
<nsIPrincipal
*>& aSubjectPrincipal
,
3360 mozilla::ErrorResult
& rv
);
3362 bool ExecCommand(const nsAString
& aHTMLCommandName
, bool aShowUI
,
3363 const nsAString
& aValue
, nsIPrincipal
& aSubjectPrincipal
,
3364 mozilla::ErrorResult
& aRv
);
3365 MOZ_CAN_RUN_SCRIPT
bool QueryCommandEnabled(const nsAString
& aHTMLCommandName
,
3366 nsIPrincipal
& aSubjectPrincipal
,
3367 mozilla::ErrorResult
& aRv
);
3368 MOZ_CAN_RUN_SCRIPT
bool QueryCommandIndeterm(
3369 const nsAString
& aHTMLCommandName
, mozilla::ErrorResult
& aRv
);
3370 MOZ_CAN_RUN_SCRIPT
bool QueryCommandState(const nsAString
& aHTMLCommandName
,
3371 mozilla::ErrorResult
& aRv
);
3372 MOZ_CAN_RUN_SCRIPT
bool QueryCommandSupported(
3373 const nsAString
& aHTMLCommandName
, mozilla::dom::CallerType aCallerType
,
3374 mozilla::ErrorResult
& aRv
);
3375 MOZ_CAN_RUN_SCRIPT
void QueryCommandValue(const nsAString
& aHTMLCommandName
,
3377 mozilla::ErrorResult
& aRv
);
3378 nsIHTMLCollection
* Applets();
3379 nsIHTMLCollection
* Anchors();
3380 TimeStamp
LastFocusTime() const;
3381 void SetLastFocusTime(const TimeStamp
& aFocusTime
);
3382 // Event handlers are all on nsINode already
3383 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3384 Element
* GetCurrentScript();
3385 void ReleaseCapture() const;
3386 void MozSetImageElement(const nsAString
& aImageElementId
, Element
* aElement
);
3387 nsIURI
* GetDocumentURIObject() const;
3388 // Not const because all the fullscreen goop is not const
3389 const char* GetFullscreenError(CallerType
);
3390 bool FullscreenEnabled(CallerType aCallerType
) {
3391 return !GetFullscreenError(aCallerType
);
3394 void GetWireframeWithoutFlushing(bool aIncludeNodes
, Nullable
<Wireframe
>&);
3396 MOZ_CAN_RUN_SCRIPT
void GetWireframe(bool aIncludeNodes
,
3397 Nullable
<Wireframe
>&);
3399 // Hides all popovers until the given end point, see
3400 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3401 MOZ_CAN_RUN_SCRIPT
void HideAllPopoversUntil(nsINode
& aEndpoint
,
3402 bool aFocusPreviousElement
,
3405 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void HideAllPopoversWithoutRunningScript();
3406 // Hides the given popover element, see
3407 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3408 MOZ_CAN_RUN_SCRIPT
void HidePopover(Element
& popover
,
3409 bool aFocusPreviousElement
,
3410 bool aFireEvents
, ErrorResult
& aRv
);
3412 // Returns a list of all the elements in the Document's top layer whose
3413 // popover attribute is in the auto state.
3414 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3415 nsTArray
<Element
*> AutoPopoverList() const;
3417 // Return document's auto popover list's last element.
3419 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3420 Element
* GetTopmostAutoPopover() const;
3422 // Adds/removes an element to/from the auto popover list.
3423 void AddToAutoPopoverList(Element
&);
3424 void RemoveFromAutoPopoverList(Element
&);
3426 void AddPopoverToTopLayer(Element
&);
3427 void RemovePopoverFromTopLayer(Element
&);
3429 Element
* GetTopLayerTop();
3430 // Return the fullscreen element in the top layer
3431 Element
* GetUnretargetedFullscreenElement() const;
3432 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3433 already_AddRefed
<Promise
> ExitFullscreen(ErrorResult
&);
3434 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3435 void GetFgColor(nsAString
& aFgColor
);
3436 void SetFgColor(const nsAString
& aFgColor
);
3437 void GetLinkColor(nsAString
& aLinkColor
);
3438 void SetLinkColor(const nsAString
& aLinkColor
);
3439 void GetVlinkColor(nsAString
& aAvlinkColor
);
3440 void SetVlinkColor(const nsAString
& aVlinkColor
);
3441 void GetAlinkColor(nsAString
& aAlinkColor
);
3442 void SetAlinkColor(const nsAString
& aAlinkColor
);
3443 void GetBgColor(nsAString
& aBgColor
);
3444 void SetBgColor(const nsAString
& aBgColor
);
3445 void Clear() const {
3448 void CaptureEvents();
3449 void ReleaseEvents();
3451 mozilla::dom::HTMLAllCollection
* All();
3453 static bool DocumentSupportsL10n(JSContext
* aCx
, JSObject
* aObject
);
3454 static bool IsWebAnimationsEnabled(JSContext
* aCx
, JSObject
* aObject
);
3455 static bool IsWebAnimationsEnabled(CallerType aCallerType
);
3456 static bool IsWebAnimationsGetAnimationsEnabled(JSContext
* aCx
,
3458 static bool AreWebAnimationsImplicitKeyframesEnabled(JSContext
* aCx
,
3460 static bool AreWebAnimationsTimelinesEnabled(JSContext
* aCx
,
3462 // Checks that the caller is either chrome or some addon.
3463 static bool IsCallerChromeOrAddon(JSContext
* aCx
, JSObject
* aObject
);
3465 bool Hidden() const { return mVisibilityState
!= VisibilityState::Visible
; }
3466 dom::VisibilityState
VisibilityState() const { return mVisibilityState
; }
3469 int32_t mPictureInPictureChildElementCount
= 0;
3472 void EnableChildElementInPictureInPictureMode();
3473 void DisableChildElementInPictureInPictureMode();
3475 // True if any child element is being used in picture in picture mode.
3476 bool HasPictureInPictureChildElement() const;
3478 void GetSelectedStyleSheetSet(nsAString
& aSheetSet
);
3479 void SetSelectedStyleSheetSet(const nsAString
& aSheetSet
);
3480 void GetLastStyleSheetSet(nsAString
& aSheetSet
) {
3481 aSheetSet
= mLastStyleSheetSet
;
3483 const nsString
& GetCurrentStyleSheetSet() const {
3484 return mLastStyleSheetSet
.IsEmpty() ? mPreferredStyleSheetSet
3485 : mLastStyleSheetSet
;
3487 void SetPreferredStyleSheetSet(const nsAString
&);
3488 void GetPreferredStyleSheetSet(nsAString
& aSheetSet
) {
3489 aSheetSet
= mPreferredStyleSheetSet
;
3491 DOMStringList
* StyleSheetSets();
3492 void EnableStyleSheetsForSet(const nsAString
& aSheetSet
);
3495 * Retrieve the location of the caret position (DOM node and character
3496 * offset within that node), given a point.
3498 * @param aX Horizontal point at which to determine the caret position, in
3500 * @param aY Vertical point at which to determine the caret position, in
3503 already_AddRefed
<nsDOMCaretPosition
> CaretPositionFromPoint(float aX
,
3506 Element
* GetScrollingElement();
3507 // A way to check whether a given element is what would get returned from
3508 // GetScrollingElement. It can be faster than comparing to the return value
3509 // of GetScrollingElement() due to being able to avoid flushes in various
3510 // cases. This method assumes that null is NOT passed.
3511 bool IsScrollingElement(Element
* aElement
);
3513 // QuerySelector and QuerySelectorAll already defined on nsINode
3515 XPathExpression
* CreateExpression(const nsAString
& aExpression
,
3516 XPathNSResolver
* aResolver
,
3518 nsINode
* CreateNSResolver(nsINode
& aNodeResolver
);
3519 already_AddRefed
<XPathResult
> Evaluate(
3520 JSContext
* aCx
, const nsAString
& aExpression
, nsINode
& aContextNode
,
3521 XPathNSResolver
* aResolver
, uint16_t aType
, JS::Handle
<JSObject
*> aResult
,
3523 // Touch event handlers already on nsINode
3524 already_AddRefed
<Touch
> CreateTouch(nsGlobalWindowInner
* aView
,
3525 EventTarget
* aTarget
, int32_t aIdentifier
,
3526 int32_t aPageX
, int32_t aPageY
,
3527 int32_t aScreenX
, int32_t aScreenY
,
3528 int32_t aClientX
, int32_t aClientY
,
3529 int32_t aRadiusX
, int32_t aRadiusY
,
3530 float aRotationAngle
, float aForce
);
3531 already_AddRefed
<TouchList
> CreateTouchList();
3532 already_AddRefed
<TouchList
> CreateTouchList(
3533 Touch
& aTouch
, const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3534 already_AddRefed
<TouchList
> CreateTouchList(
3535 const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3537 void SetStyleSheetChangeEventsEnabled(bool aValue
) {
3538 mStyleSheetChangeEventsEnabled
= aValue
;
3541 bool StyleSheetChangeEventsEnabled() const {
3542 return mStyleSheetChangeEventsEnabled
;
3545 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue
) {
3546 mDevToolsAnonymousAndShadowEventsEnabled
= aValue
;
3548 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3549 return mDevToolsAnonymousAndShadowEventsEnabled
;
3552 already_AddRefed
<Promise
> BlockParsing(Promise
& aPromise
,
3553 const BlockParsingOptions
& aOptions
,
3556 already_AddRefed
<nsIURI
> GetMozDocumentURIIfNotForErrorPages();
3558 Promise
* GetDocumentReadyForIdle(ErrorResult
& aRv
);
3560 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock
) {
3564 UnblockOnload(/* aFireSync = */ false);
3568 nsIDOMXULCommandDispatcher
* GetCommandDispatcher();
3569 bool HasXULBroadcastManager() const { return mXULBroadcastManager
; };
3570 void InitializeXULBroadcastManager();
3571 XULBroadcastManager
* GetXULBroadcastManager() const {
3572 return mXULBroadcastManager
;
3574 nsINode
* GetPopupRangeParent(ErrorResult
& aRv
);
3575 int32_t GetPopupRangeOffset(ErrorResult
& aRv
);
3577 bool DevToolsWatchingDOMMutations() const {
3578 return mDevToolsWatchingDOMMutations
;
3580 void SetDevToolsWatchingDOMMutations(bool aValue
);
3582 void MaybeWarnAboutZoom();
3584 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3585 void EvaluateMediaQueriesAndReportChanges(bool aRecurse
);
3588 nsIHTMLCollection
* Children();
3589 uint32_t ChildElementCount();
3592 * Asserts IsHTMLOrXHTML, and can't return null.
3593 * Defined inline in nsHTMLDocument.h
3595 inline nsHTMLDocument
* AsHTMLDocument();
3596 inline const nsHTMLDocument
* AsHTMLDocument() const;
3599 * Asserts IsSVGDocument, and can't return null.
3600 * Defined inline in SVGDocument.h
3602 inline SVGDocument
* AsSVGDocument();
3603 inline const SVGDocument
* AsSVGDocument() const;
3606 * Asserts IsImageDocument, and can't return null.
3607 * Defined inline in ImageDocument.h
3609 inline ImageDocument
* AsImageDocument();
3610 inline const ImageDocument
* AsImageDocument() const;
3613 * Given a node, get a weak reference to it and append that reference to
3614 * mBlockedNodesByClassifier. Can be used later on to look up a node in it.
3617 void AddBlockedNodeByClassifier(nsINode
* node
) {
3622 nsWeakPtr weakNode
= do_GetWeakReference(node
);
3625 mBlockedNodesByClassifier
.AppendElement(weakNode
);
3629 gfxUserFontSet
* GetUserFontSet();
3630 void FlushUserFontSet();
3631 void MarkUserFontSetDirty();
3632 FontFaceSet
* GetFonts() { return mFontFaceSet
; }
3635 FontFaceSet
* GetFonts(ErrorResult
&) { return Fonts(); }
3636 FontFaceSet
* Fonts();
3638 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded
; }
3640 bool IsSynthesized();
3642 // Records whether we will track use counters for this document, and if so,
3643 // which top-level document that page counters will be accumulated to.
3645 // Informs the parent process that page use counters will be sent once the
3646 // document goes away.
3647 void InitUseCounters();
3649 // Reports document use counters via telemetry. This method only has an
3650 // effect once per document, and so is called during document destruction.
3651 void ReportDocumentUseCounters();
3653 // Report how lazyload performs for this document.
3654 void ReportDocumentLazyLoadCounters();
3656 // Sends page use counters to the parent process to accumulate against the
3657 // top-level document. Must be called while we still have access to our
3658 // WindowContext. This method has an effect each time it is called, and we
3659 // call it just before the document loses its window.
3660 void SendPageUseCounters();
3662 void SetUseCounter(UseCounter aUseCounter
) {
3663 mUseCounters
[aUseCounter
] = true;
3666 const StyleUseCounters
* GetStyleUseCounters() {
3667 return mStyleUseCounters
.get();
3670 // Propagate our use counters explicitly into the specified referencing
3673 // This is used for SVG image documents, which cannot be enumerated in the
3674 // referencing document's ReportUseCounters() like external resource documents
3676 void PropagateImageUseCounters(Document
* aReferencingDocument
);
3678 // Called to track whether this document has had any interaction.
3679 // This is used to track whether we should permit "beforeunload".
3680 void SetUserHasInteracted();
3681 bool UserHasInteracted() { return mUserHasInteracted
; }
3682 void ResetUserInteractionTimer();
3684 // This should be called when this document receives events which are likely
3685 // to be user interaction with the document, rather than the byproduct of
3686 // interaction with the browser (i.e. a keypress to scroll the view port,
3687 // keyboard shortcuts, etc). This is used to decide whether we should
3688 // permit autoplay audible media. This also gesture activates all other
3689 // content documents in this tab.
3690 void NotifyUserGestureActivation();
3692 // This function is used for mochitest only.
3693 void ClearUserGestureActivation();
3695 // Return true if NotifyUserGestureActivation() has been called on any
3696 // document in the document tree.
3697 bool HasBeenUserGestureActivated();
3699 // Reture timestamp of last user gesture in milliseconds relative to
3700 // navigation start timestamp.
3701 DOMHighResTimeStamp
LastUserGestureTimeStamp();
3703 // Return true if there is transient user gesture activation and it hasn't yet
3704 // timed out or hasn't been consumed.
3705 bool HasValidTransientUserGestureActivation() const;
3707 // Return true if HasValidTransientUserGestureActivation() would return true,
3708 // and consume the activation.
3709 bool ConsumeTransientUserGestureActivation();
3711 BrowsingContext
* GetBrowsingContext() const;
3713 // This document is a WebExtension page, it might be a background page, a
3714 // popup, a visible tab, a visible iframe ...e.t.c.
3715 bool IsExtensionPage() const;
3717 bool HasScriptsBlockedBySandbox() const;
3719 void ReportHasScrollLinkedEffect(const TimeStamp
& aTimeStamp
);
3720 bool HasScrollLinkedEffect() const;
3723 void AssertDocGroupMatchesKey() const;
3726 DocGroup
* GetDocGroup() const {
3728 AssertDocGroupMatchesKey();
3733 DocGroup
* GetDocGroupOrCreate();
3736 * If we're a sub-document, the parent document's layout can affect our style
3737 * and layout (due to the viewport size, viewport units, media queries...).
3739 * This function returns true if our parent document and our child document
3740 * can observe each other. If they cannot, then we don't need to synchronously
3741 * update the parent document layout every time the child document may need
3742 * up-to-date layout information.
3744 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3745 return GetInProcessParentDocument() &&
3746 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3749 void AddIntersectionObserver(DOMIntersectionObserver
* aObserver
) {
3750 MOZ_ASSERT(!mIntersectionObservers
.Contains(aObserver
),
3751 "Intersection observer already in the list");
3752 mIntersectionObservers
.Insert(aObserver
);
3755 void RemoveIntersectionObserver(DOMIntersectionObserver
* aObserver
) {
3756 mIntersectionObservers
.Remove(aObserver
);
3759 bool HasIntersectionObservers() const {
3760 return !mIntersectionObservers
.IsEmpty();
3763 void UpdateIntersectionObservations(TimeStamp aNowTime
);
3764 void ScheduleIntersectionObserverNotification();
3765 MOZ_CAN_RUN_SCRIPT
void NotifyIntersectionObservers();
3767 DOMIntersectionObserver
* GetLazyLoadImageObserver() {
3768 return mLazyLoadImageObserver
;
3770 DOMIntersectionObserver
* GetLazyLoadImageObserverViewport() {
3771 return mLazyLoadImageObserverViewport
;
3773 DOMIntersectionObserver
& EnsureLazyLoadImageObserver();
3775 DOMIntersectionObserver
* GetContentVisibilityObserver() const {
3776 return mContentVisibilityObserver
;
3778 DOMIntersectionObserver
& EnsureContentVisibilityObserver();
3779 void ObserveForContentVisibility(Element
&);
3780 void UnobserveForContentVisibility(Element
&);
3782 ResizeObserver
* GetLastRememberedSizeObserver() {
3783 return mLastRememberedSizeObserver
;
3785 ResizeObserver
& EnsureLastRememberedSizeObserver();
3786 void ObserveForLastRememberedSize(Element
&);
3787 void UnobserveForLastRememberedSize(Element
&);
3789 // Dispatch a runnable related to the document.
3790 nsresult
Dispatch(TaskCategory aCategory
,
3791 already_AddRefed
<nsIRunnable
>&& aRunnable
) final
;
3793 nsISerialEventTarget
* EventTargetFor(TaskCategory
) const override
;
3795 AbstractThread
* AbstractMainThreadFor(TaskCategory
) override
;
3797 // The URLs passed to this function should match what
3798 // JS::DescribeScriptedCaller() returns, since this API is used to
3799 // determine whether some code is being called from a tracking script.
3800 void NoteScriptTrackingStatus(const nsACString
& aURL
, bool isTracking
);
3801 // The JSContext passed to this method represents the context that we want to
3802 // determine if it belongs to a tracker.
3803 bool IsScriptTracking(JSContext
* aCx
) const;
3805 // ResizeObserver usage.
3806 void AddResizeObserver(ResizeObserver
&);
3807 void RemoveResizeObserver(ResizeObserver
&);
3808 void ScheduleResizeObserversNotification() const;
3810 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3811 PermissionDelegateHandler
* GetPermissionDelegateHandler();
3813 // Notify the document that a fetch or a XHR request has completed
3814 // succesfully in this document. This is used by the password manager to infer
3815 // whether a form is submitted.
3816 void NotifyFetchOrXHRSuccess();
3818 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3819 void SetNotifyFetchSuccess(bool aShouldNotify
);
3821 // When this is set, removing a form or a password field from DOM
3822 // sends a Chrome-only event. This is now only used by the password manager.
3823 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify
);
3825 // This function is used by HTMLFormElement and HTMLInputElement to determin
3826 // whether to send an event when it is removed from DOM.
3827 bool ShouldNotifyFormOrPasswordRemoved() const {
3828 return mShouldNotifyFormOrPasswordRemoved
;
3831 HTMLEditor
* GetHTMLEditor() const;
3836 * For more information on DocumentL10n see
3837 * intl/l10n/docs/fluent/tutorial.rst
3842 * This is a public method exposed on Document WebIDL
3843 * to chrome only documents.
3845 DocumentL10n
* GetL10n() const { return mDocumentL10n
.get(); }
3848 * Whether there's any async l10n mutation work pending.
3850 * When this turns false, we fire the L10nMutationsFinished event.
3852 bool HasPendingL10nMutations() const;
3855 * This method should be called when the container
3856 * of l10n resources parsing is completed.
3858 * It triggers initial async fetch of the resources
3859 * as early as possible.
3861 * In HTML case this is </head>.
3862 * In XUL case this is </linkset>.
3864 void OnL10nResourceContainerParsed();
3867 * This method should be called when a link element
3868 * with rel="localization" is being added to the
3869 * l10n resource container element.
3871 void LocalizationLinkAdded(Element
* aLinkElement
);
3874 * This method should be called when a link element
3875 * with rel="localization" is being removed.
3877 void LocalizationLinkRemoved(Element
* aLinkElement
);
3880 * This method should be called as soon as the
3881 * parsing of the document is completed.
3883 * In HTML/XHTML this happens when we finish parsing
3884 * the document element.
3885 * In XUL it happens at `DoneWalking`, during
3886 * `MozBeforeInitialXULLayout`.
3888 void OnParsingCompleted();
3891 * This method is called when the initial translation
3892 * of the document is completed.
3894 * It unblocks the load event if translation was blocking it.
3896 * If the `aL10nCached` is set to `true`, and the document has
3897 * a prototype, it will set the `isL10nCached` flag on it.
3899 void InitialTranslationCompleted(bool aL10nCached
);
3902 * Returns whether the document allows localization.
3904 bool AllowsL10n() const;
3907 RefPtr
<DocumentL10n
> mDocumentL10n
;
3910 * Return true when you want a document without explicitly specified viewport
3911 * dimensions/scale to be treated as if "width=device-width" had in fact been
3914 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3917 bool IsErrorPage() const;
3919 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3921 void SetCssUseCounterBits();
3923 void ParseWidthAndHeightInMetaViewport(const nsAString
& aWidthString
,
3924 const nsAString
& aHeightString
,
3927 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3928 // represents the scale property and returns the scale value if it's valid.
3929 Maybe
<LayoutDeviceToScreenScale
> ParseScaleInHeader(nsAtom
* aHeaderField
);
3931 // Parse scale values in |aViewportMetaData| and set the values in
3932 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3933 void ParseScalesInViewportMetaData(const ViewportMetaData
& aViewportMetaData
);
3935 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3936 // stored in parent iframe or container's browsingContext (cross process)
3937 already_AddRefed
<mozilla::dom::FeaturePolicy
> GetParentFeaturePolicy();
3940 const OriginTrials
& Trials() const { return mTrials
; }
3943 void DoCacheAllKnownLangPrefs();
3944 void RecomputeLanguageFromCharset();
3945 bool GetSHEntryHasUserInteraction();
3947 void AppendAutoFocusCandidateToTopDocument(Element
* aAutoFocusCandidate
);
3950 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate
= true; }
3952 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate
; }
3954 void SetSHEntryHasUserInteraction(bool aHasInteraction
);
3956 already_AddRefed
<nsAtom
> GetContentLanguageAsAtomForStyle() const;
3957 already_AddRefed
<nsAtom
> GetLanguageForStyle() const;
3960 * Fetch the user's font preferences for the given aLanguage's
3963 const LangGroupFontPrefs
* GetFontPrefsForLang(
3964 nsAtom
* aLanguage
, bool* aNeedsToCache
= nullptr) const;
3966 void ForceCacheLang(nsAtom
* aLanguage
) {
3967 if (!mLanguagesUsed
.EnsureInserted(aLanguage
)) {
3970 GetFontPrefsForLang(aLanguage
);
3973 void CacheAllKnownLangPrefs() {
3974 if (!mMayNeedFontPrefsUpdate
) {
3977 DoCacheAllKnownLangPrefs();
3980 nsINode
* GetServoRestyleRoot() const { return mServoRestyleRoot
; }
3982 uint32_t GetServoRestyleRootDirtyBits() const {
3983 MOZ_ASSERT(mServoRestyleRoot
);
3984 MOZ_ASSERT(mServoRestyleRootDirtyBits
);
3985 return mServoRestyleRootDirtyBits
;
3988 void ClearServoRestyleRoot() {
3989 mServoRestyleRoot
= nullptr;
3990 mServoRestyleRootDirtyBits
= 0;
3993 inline void SetServoRestyleRoot(nsINode
* aRoot
, uint32_t aDirtyBits
);
3994 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits
);
3996 bool ShouldThrowOnDynamicMarkupInsertion() {
3997 return mThrowOnDynamicMarkupInsertionCounter
;
4000 void IncrementThrowOnDynamicMarkupInsertionCounter() {
4001 ++mThrowOnDynamicMarkupInsertionCounter
;
4004 void DecrementThrowOnDynamicMarkupInsertionCounter() {
4005 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter
);
4006 --mThrowOnDynamicMarkupInsertionCounter
;
4009 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter
; }
4011 void IncrementIgnoreOpensDuringUnloadCounter() {
4012 ++mIgnoreOpensDuringUnloadCounter
;
4015 void DecrementIgnoreOpensDuringUnloadCounter() {
4016 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter
);
4017 --mIgnoreOpensDuringUnloadCounter
;
4020 mozilla::dom::FeaturePolicy
* FeaturePolicy() const;
4022 bool ImportMapsEnabled() const;
4025 * Find the (non-anonymous) content in this document for aFrame. It will
4026 * be aFrame's content node if that content is in this document and not
4027 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4028 * element containing the subdocument containing aFrame, and/or find the
4029 * nearest non-anonymous ancestor in this document.
4030 * Returns null if there is no such element.
4032 nsIContent
* GetContentInThisDocument(nsIFrame
* aFrame
) const;
4034 void ReportShadowDOMUsage();
4036 // Sets flags for media telemetry.
4037 void SetDocTreeHadMedia();
4039 dom::XPathEvaluator
* XPathEvaluator();
4041 void MaybeInitializeFinalizeFrameLoaders();
4043 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization
) {
4044 mDelayFrameLoaderInitialization
= aDelayFrameLoaderInitialization
;
4047 void SetPrototypeDocument(nsXULPrototypeDocument
* aPrototype
);
4049 nsIPermissionDelegateHandler
* PermDelegateHandler();
4051 // Returns whether this is a top-level about:blank page without an opener
4052 // (and thus not accessible by content).
4053 bool IsContentInaccessibleAboutBlank() const;
4055 // CSS prefers-color-scheme media feature for this document.
4056 enum class IgnoreRFP
{ No
, Yes
};
4057 ColorScheme
PreferredColorScheme(IgnoreRFP
= IgnoreRFP::No
) const;
4058 // Returns the initial color-scheme used for this document based on the
4059 // color-scheme meta tag.
4060 ColorScheme
DefaultColorScheme() const;
4062 static bool HasRecentlyStartedForegroundLoads();
4064 static bool AutomaticStorageAccessPermissionCanBeGranted(
4065 nsIPrincipal
* aPrincipal
);
4067 already_AddRefed
<Promise
> AddCertException(bool aIsTemporary
,
4068 ErrorResult
& aError
);
4070 void ReloadWithHttpsOnlyException();
4072 // Subframes need to be static cloned after the main document has been
4073 // embedded within a script global. A `PendingFrameStaticClone` is a static
4074 // clone which has not yet been performed.
4076 // The getter returns a direct reference to an internal array which is
4077 // manipulated from within printing code.
4078 struct PendingFrameStaticClone
{
4079 PendingFrameStaticClone() = default;
4080 PendingFrameStaticClone(PendingFrameStaticClone
&&) = default;
4081 PendingFrameStaticClone
& operator=(PendingFrameStaticClone
&&) = default;
4082 ~PendingFrameStaticClone();
4084 RefPtr
<nsFrameLoaderOwner
> mElement
;
4085 RefPtr
<nsFrameLoader
> mStaticCloneOf
;
4087 void AddPendingFrameStaticClone(nsFrameLoaderOwner
* aElement
,
4088 nsFrameLoader
* aStaticCloneOf
);
4090 bool ShouldAvoidNativeTheme() const;
4092 static bool IsValidDomain(nsIURI
* aOrigHost
, nsIURI
* aNewURI
);
4094 // Inform a parent document that a BrowserBridgeChild has been created for
4095 // an OOP sub-document.
4096 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4097 void OOPChildLoadStarted(BrowserBridgeChild
* aChild
);
4099 // Inform a parent document that the BrowserBridgeChild for one of its
4100 // OOP sub-documents is done calling its onload handler.
4101 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4102 void OOPChildLoadDone(BrowserBridgeChild
* aChild
);
4104 void ClearOOPChildrenLoading();
4106 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading
.IsEmpty(); }
4108 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache
= true; }
4110 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache
; }
4113 * Get the `HighlightRegistry` which contains all highlights associated
4114 * with this document.
4116 class HighlightRegistry
& HighlightRegistry();
4118 bool ShouldResistFingerprinting(RFPTarget aTarget
) const;
4120 // Recompute the current resist fingerprinting state. Returns true when
4121 // the state was changed.
4122 bool RecomputeResistFingerprinting();
4124 bool MayHaveDOMActivateListeners() const;
4127 // Returns the WindowContext for the document that we will contribute
4128 // page use counters to.
4129 WindowContext
* GetWindowContextForPageUseCounters() const;
4131 void DoUpdateSVGUseElementShadowTrees();
4133 already_AddRefed
<nsIPrincipal
> MaybeDowngradePrincipal(
4134 nsIPrincipal
* aPrincipal
);
4136 void EnsureOnloadBlocker();
4138 void SendToConsole(nsCOMArray
<nsISecurityConsoleMessage
>& aMessages
);
4140 // Returns true if the scheme for the url for this document is "about".
4141 bool IsAboutPage() const;
4143 bool ContainsEMEContent();
4144 bool ContainsMSEContent();
4147 * Returns the title element of the document as defined by the HTML
4148 * specification, or null if there isn't one. For documents whose root
4149 * element is an <svg:svg>, this is the first <svg:title> element that's a
4150 * child of the root. For other documents, it's the first HTML title element
4153 Element
* GetTitleElement();
4155 void RecordNavigationTiming(ReadyState aReadyState
);
4157 // Recomputes the visibility state but doesn't set the new value.
4158 dom::VisibilityState
ComputeVisibilityState() const;
4160 // Since we wouldn't automatically play media from non-visited page, we need
4161 // to notify window when the page was first visited.
4162 void MaybeActiveMediaComponents();
4164 // Apply the fullscreen state to the document, and trigger related
4165 // events. It returns false if the fullscreen element ready check
4166 // fails and nothing gets changed.
4167 bool ApplyFullscreen(UniquePtr
<FullscreenRequest
>);
4169 void RemoveDocStyleSheetsFromStyleSets();
4170 void ResetStylesheetsToURI(nsIURI
* aURI
);
4171 void FillStyleSet();
4172 void FillStyleSetUserAndUASheets();
4173 void FillStyleSetDocumentSheets();
4174 void CompatibilityModeChanged();
4175 bool NeedsQuirksSheet() const {
4176 // SVG documents never load quirk.css.
4177 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4178 return mCompatMode
== eCompatibility_NavQuirks
&& !IsSVGDocument();
4180 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode
);
4181 void RemoveContentEditableStyleSheets();
4182 void AddStyleSheetToStyleSets(StyleSheet
&);
4183 void RemoveStyleSheetFromStyleSets(StyleSheet
&);
4184 void NotifyStyleSheetApplicableStateChanged();
4185 // Just like EnableStyleSheetsForSet, but doesn't check whether
4186 // aSheetSet is null and allows the caller to control whether to set
4187 // aSheetSet as the preferred set in the CSSLoader.
4188 void EnableStyleSheetsForSetInternal(const nsAString
& aSheetSet
,
4189 bool aUpdateCSSLoader
);
4191 already_AddRefed
<nsIURI
> GetDomainURI();
4192 already_AddRefed
<nsIURI
> CreateInheritingURIForHost(
4193 const nsACString
& aHostString
);
4194 already_AddRefed
<nsIURI
> RegistrableDomainSuffixOfInternal(
4195 const nsAString
& aHostSuffixString
, nsIURI
* aOrigHost
);
4197 void WriteCommon(const nsAString
& aText
, bool aNewlineTerminate
,
4198 mozilla::ErrorResult
& aRv
);
4199 // A version of WriteCommon used by WebIDL bindings
4200 void WriteCommon(const mozilla::dom::Sequence
<nsString
>& aText
,
4201 bool aNewlineTerminate
, mozilla::ErrorResult
& rv
);
4203 void* GenerateParserKey(void);
4206 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4208 enum class ExecCommandParam
: uint8_t {
4209 // Always ignore it.
4211 // Treat the given parameter as-is. If the command requires it, use it.
4212 // Otherwise, ignore it.
4214 // Always treat it as boolean parameter.
4216 // Always treat it as boolean, but inverted.
4220 using GetEditorCommandFunc
= mozilla::EditorCommand
*();
4222 struct InternalCommandData
{
4223 const char* mXULCommandName
;
4224 mozilla::Command mCommand
; // uint8_t
4225 // How ConvertToInternalCommand() to treats aValue.
4226 // Its callers don't need to check this.
4227 ExecCommandParam mExecCommandParam
; // uint8_t
4228 GetEditorCommandFunc
* mGetEditorCommandFunc
;
4229 enum class CommandOnTextEditor
: uint8_t {
4232 FallThrough
, // Not disabled, but handled by HTMLEditor if there is one
4234 CommandOnTextEditor mCommandOnTextEditor
;
4236 InternalCommandData()
4237 : mXULCommandName(nullptr),
4238 mCommand(mozilla::Command::DoNothing
),
4239 mExecCommandParam(ExecCommandParam::Ignore
),
4240 mGetEditorCommandFunc(nullptr),
4241 mCommandOnTextEditor(CommandOnTextEditor::Disabled
) {}
4242 InternalCommandData(const char* aXULCommandName
, mozilla::Command aCommand
,
4243 ExecCommandParam aExecCommandParam
,
4244 GetEditorCommandFunc aGetEditorCommandFunc
,
4245 CommandOnTextEditor aCommandOnTextEditor
)
4246 : mXULCommandName(aXULCommandName
),
4248 mExecCommandParam(aExecCommandParam
),
4249 mGetEditorCommandFunc(aGetEditorCommandFunc
),
4250 mCommandOnTextEditor(aCommandOnTextEditor
) {}
4252 bool IsAvailableOnlyWhenEditable() const {
4253 return mCommand
!= mozilla::Command::Cut
&&
4254 mCommand
!= mozilla::Command::Copy
&&
4255 mCommand
!= mozilla::Command::Paste
&&
4256 mCommand
!= mozilla::Command::SetDocumentReadOnly
&&
4257 mCommand
!= mozilla::Command::SelectAll
;
4259 bool IsCutOrCopyCommand() const {
4260 return mCommand
== mozilla::Command::Cut
||
4261 mCommand
== mozilla::Command::Copy
;
4263 bool IsPasteCommand() const { return mCommand
== mozilla::Command::Paste
; }
4267 * AutoEditorCommandTarget considers which editor or global command manager
4268 * handles given command.
4270 class MOZ_RAII AutoEditorCommandTarget
{
4272 MOZ_CAN_RUN_SCRIPT
AutoEditorCommandTarget(
4273 Document
& aDocument
, const InternalCommandData
& aCommandData
);
4274 AutoEditorCommandTarget() = delete;
4275 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget
& aOther
) =
4278 bool DoNothing() const { return mDoNothing
; }
4279 MOZ_CAN_RUN_SCRIPT
bool IsEditable(Document
* aDocument
) const;
4280 bool IsEditor() const {
4281 MOZ_ASSERT_IF(mEditorCommand
, mActiveEditor
|| mHTMLEditor
);
4282 return !!mEditorCommand
;
4285 MOZ_CAN_RUN_SCRIPT
bool IsCommandEnabled() const;
4286 MOZ_CAN_RUN_SCRIPT nsresult
DoCommand(nsIPrincipal
* aPrincipal
) const;
4287 template <typename ParamType
>
4288 MOZ_CAN_RUN_SCRIPT nsresult
DoCommandParam(const ParamType
& aParam
,
4289 nsIPrincipal
* aPrincipal
) const;
4290 MOZ_CAN_RUN_SCRIPT nsresult
4291 GetCommandStateParams(nsCommandParams
& aParams
) const;
4294 // The returned editor's life is guaranteed while this instance is alive.
4295 EditorBase
* GetTargetEditor() const;
4297 RefPtr
<EditorBase
> mActiveEditor
;
4298 RefPtr
<HTMLEditor
> mHTMLEditor
;
4299 RefPtr
<EditorCommand
> mEditorCommand
;
4300 const InternalCommandData
& mCommandData
;
4301 bool mDoNothing
= false;
4305 * Helper method to initialize sInternalCommandDataHashtable.
4307 static void EnsureInitializeInternalCommandDataHashtable();
4310 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4311 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4312 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4313 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4314 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4315 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4316 * returns a copy of instance created with default constructor. I.e., its
4317 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4318 * is unsupported in such case.
4320 * @param aHTMLCommandName Command name in HTML, e.g., used by
4322 * @param aValue The value which is set to the 3rd parameter
4324 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4325 * Will be set to adjusted value for executing
4326 * the internal command.
4327 * @return Returns a copy of instance created with the
4328 * default constructor if there is no
4329 * corresponding internal command for
4330 * aHTMLCommandName or aValue is invalid for
4331 * found internal command when aAdjustedValue
4332 * is not nullptr. Otherwise, returns a copy of
4333 * instance registered in
4334 * sInternalCommandDataHashtable.
4336 static InternalCommandData
ConvertToInternalCommand(
4337 const nsAString
& aHTMLCommandName
, const nsAString
& aValue
= u
""_ns
,
4338 nsAString
* aAdjustedValue
= nullptr);
4341 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4342 * Since it's a bit field, not a bool member, therefore, we cannot use
4343 * AutoRestorer for it.
4345 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final
{
4347 AutoRunningExecCommandMarker() = delete;
4348 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker
&) =
4350 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4351 MOZ_CAN_RUN_SCRIPT
explicit AutoRunningExecCommandMarker(
4352 Document
& aDocument
)
4353 : mDocument(aDocument
),
4354 mHasBeenRunning(aDocument
.mIsRunningExecCommand
) {
4355 aDocument
.mIsRunningExecCommand
= true;
4357 ~AutoRunningExecCommandMarker() {
4358 if (!mHasBeenRunning
) {
4359 mDocument
.mIsRunningExecCommand
= false;
4364 Document
& mDocument
;
4365 bool mHasBeenRunning
;
4368 // Mapping table from HTML command name to internal command.
4369 using InternalCommandDataHashtable
=
4370 nsTHashMap
<nsStringCaseInsensitiveHashKey
, InternalCommandData
>;
4371 static InternalCommandDataHashtable
* sInternalCommandDataHashtable
;
4373 mutable std::bitset
<static_cast<size_t>(
4374 DeprecatedOperations::eDeprecatedOperationCount
)>
4375 mDeprecationWarnedAbout
;
4376 mutable std::bitset
<eDocumentWarningCount
> mDocWarningWarnedAbout
;
4378 // Lazy-initialization to have mDocGroup initialized in prior to the
4379 UniquePtr
<ServoStyleSet
> mStyleSet
;
4382 // Never ever call this. Only call GetWindow!
4383 nsPIDOMWindowOuter
* GetWindowInternal() const;
4385 // Never ever call this. Only call GetScriptHandlingObject!
4386 nsIScriptGlobalObject
* GetScriptHandlingObjectInternal() const;
4388 // Never ever call this. Only call AllowXULXBL!
4389 bool InternalAllowXULXBL();
4392 * These methods should be called before and after dispatching
4394 * To make this easy and painless, use the mozAutoSubtreeModified helper
4397 void WillDispatchMutationEvent(nsINode
* aTarget
);
4398 void MutationEventDispatched(nsINode
* aTarget
);
4399 friend class mozAutoSubtreeModified
;
4401 virtual Element
* GetNameSpaceElement() override
{ return GetRootElement(); }
4403 nsCString
GetContentTypeInternal() const { return mContentType
; }
4405 // Update our frame request callback scheduling state, if needed. This will
4406 // schedule or unschedule them, if necessary, and update
4407 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4408 // mPresShell is becoming null; in that case it will be used to get hold of
4409 // the relevant refresh driver.
4410 void UpdateFrameRequestCallbackSchedulingState(
4411 PresShell
* aOldPresShell
= nullptr);
4413 // Helper for GetScrollingElement/IsScrollingElement.
4414 bool IsPotentiallyScrollable(HTMLBodyElement
* aBody
);
4416 void MaybeAllowStorageForOpenerAfterUserInteraction();
4418 void MaybeStoreUserInteractionAsPermission();
4420 // Helpers for GetElementsByName.
4421 static bool MatchNameAttribute(Element
* aElement
, int32_t aNamespaceID
,
4422 nsAtom
* aAtom
, void* aData
);
4423 static void* UseExistingNameString(nsINode
* aRootNode
, const nsString
* aName
);
4425 void MaybeResolveReadyForIdle();
4427 using AutomaticStorageAccessPermissionGrantPromise
=
4428 MozPromise
<bool, bool, true>;
4429 [[nodiscard
]] RefPtr
<AutomaticStorageAccessPermissionGrantPromise
>
4430 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation
);
4432 static void AddToplevelLoadingDocument(Document
* aDoc
);
4433 static void RemoveToplevelLoadingDocument(Document
* aDoc
);
4434 static AutoTArray
<Document
*, 8>* sLoadingForegroundTopLevelContentDocument
;
4435 friend class cycleCollection
;
4437 nsCOMPtr
<nsIReferrerInfo
> mPreloadReferrerInfo
;
4438 nsCOMPtr
<nsIReferrerInfo
> mReferrerInfo
;
4440 nsString mLastModified
;
4442 nsCOMPtr
<nsIURI
> mDocumentURI
;
4443 nsCOMPtr
<nsIURI
> mOriginalURI
;
4444 nsCOMPtr
<nsIURI
> mChromeXHRDocURI
;
4445 nsCOMPtr
<nsIURI
> mDocumentBaseURI
;
4446 nsCOMPtr
<nsIURI
> mChromeXHRDocBaseURI
;
4448 // The base domain of the document for third-party checks.
4449 nsCString mBaseDomain
;
4451 // A lazily-constructed URL data for style system to resolve URL values.
4452 RefPtr
<URLExtraData
> mCachedURLData
;
4453 nsCOMPtr
<nsIReferrerInfo
> mCachedReferrerInfoForInternalCSSAndSVGResources
;
4455 nsWeakPtr mDocumentLoadGroup
;
4457 WeakPtr
<nsDocShell
> mDocumentContainer
;
4459 NotNull
<const Encoding
*> mCharacterSet
;
4460 int32_t mCharacterSetSource
;
4462 OriginTrials mTrials
;
4464 // This is just a weak pointer; the parent document owns its children.
4465 Document
* mParentDocument
;
4467 // A reference to the element last returned from GetRootElement().
4468 Element
* mCachedRootElement
;
4470 // This is maintained by AutoSetRestoreSVGContextPaint.
4471 const SVGContextPaint
* mCurrentContextPaint
= nullptr;
4473 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4474 // which in turn holds a strong reference to this mNodeInfoManager.
4475 nsNodeInfoManager
* mNodeInfoManager
;
4476 RefPtr
<css::Loader
> mCSSLoader
;
4477 RefPtr
<css::ImageLoader
> mStyleImageLoader
;
4479 // The object that contains link color declarations (from the <body> mapped
4480 // attributes), mapped attribute caches, and inline style attribute caches.
4481 RefPtr
<AttributeStyles
> mAttributeStyles
;
4483 // Tracking for images in the document.
4484 RefPtr
<dom::ImageTracker
> mImageTracker
;
4486 // A hashtable of ShadowRoots belonging to the composed doc.
4488 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4489 ShadowRootSet mComposedShadowRoots
;
4491 using SVGUseElementSet
= nsTHashSet
<SVGUseElement
*>;
4493 // The set of <svg:use> elements that need a shadow tree reclone because the
4494 // tree they map to has changed.
4495 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate
;
4497 // The set of all object, embed, video/audio elements or
4498 // nsIObjectLoadingContent or DocumentActivity for which this is
4499 // the owner document. (They might not be in the document.)
4501 // These are non-owning pointers, the elements are responsible for removing
4502 // themselves when they go away.
4503 UniquePtr
<nsTHashSet
<nsISupports
*>> mActivityObservers
;
4505 // A hashtable of styled links keyed by address pointer.
4506 nsTHashSet
<Link
*> mStyledLinks
;
4508 // Indicates whether mStyledLinks was cleared or not. This is used to track
4509 // state so we can provide useful assertions to consumers of ForgetLink and
4510 // AddStyleRelevantLink.
4511 bool mStyledLinksCleared
;
4514 // The array of all links that need their status resolved. Links must add
4515 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4517 static const size_t kSegmentSize
= 128;
4519 using LinksToUpdateList
=
4520 SegmentedVector
<nsCOMPtr
<Link
>, kSegmentSize
, InfallibleAllocPolicy
>;
4522 LinksToUpdateList mLinksToUpdate
;
4524 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4525 RefPtr
<SMILAnimationController
> mAnimationController
;
4527 // Table of element properties for this document.
4528 nsPropertyTable mPropertyTable
;
4530 // Our cached .children collection
4531 nsCOMPtr
<nsIHTMLCollection
> mChildrenCollection
;
4533 // Various DOM lists
4534 RefPtr
<nsContentList
> mImages
;
4535 RefPtr
<nsContentList
> mEmbeds
;
4536 RefPtr
<nsContentList
> mLinks
;
4537 RefPtr
<nsContentList
> mForms
;
4538 RefPtr
<nsContentList
> mScripts
;
4539 nsCOMPtr
<nsIHTMLCollection
> mApplets
;
4540 RefPtr
<nsContentList
> mAnchors
;
4542 // container for per-context fonts (downloadable, SVG, etc.)
4543 RefPtr
<FontFaceSet
> mFontFaceSet
;
4545 // Last time this document or a one of its sub-documents was focused. If
4546 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4547 TimeStamp mLastFocusTime
;
4549 // Last time we found any scroll linked effect in this document.
4550 TimeStamp mLastScrollLinkedEffectDetectionTime
;
4552 DocumentState mDocumentState
{DocumentState::LTR_LOCALE
};
4554 RefPtr
<Promise
> mReadyForIdle
;
4556 RefPtr
<mozilla::dom::FeaturePolicy
> mFeaturePolicy
;
4558 UniquePtr
<ResizeObserverController
> mResizeObserverController
;
4560 // Permission Delegate Handler, lazily-initialized in
4561 // GetPermissionDelegateHandler
4562 RefPtr
<PermissionDelegateHandler
> mPermissionDelegateHandler
;
4564 bool mCachedStateObjectValid
: 1;
4565 bool mBlockAllMixedContent
: 1;
4566 bool mBlockAllMixedContentPreloads
: 1;
4567 bool mUpgradeInsecureRequests
: 1;
4568 bool mUpgradeInsecurePreloads
: 1;
4569 bool mDevToolsWatchingDOMMutations
: 1;
4571 // True if BIDI is enabled.
4572 bool mBidiEnabled
: 1;
4573 // True if we may need to recompute the language prefs for this document.
4574 bool mMayNeedFontPrefsUpdate
: 1;
4575 // True if a MathML element has ever been owned by this document.
4576 bool mMathMLEnabled
: 1;
4578 // True if this document is the initial document for a window. This should
4579 // basically be true only for documents that exist in newly-opened windows or
4580 // documents created to satisfy a GetDocument() on a window when there's no
4582 bool mIsInitialDocumentInWindow
: 1;
4584 bool mIgnoreDocGroupMismatches
: 1;
4586 // True if we're loaded as data and therefor has any dangerous stuff, such
4587 // as scripts and plugins, disabled.
4588 bool mLoadedAsData
: 1;
4590 // True if the document is considered for memory reporting as a
4592 bool mAddedToMemoryReportingAsDataDocument
: 1;
4594 // If true, whoever is creating the document has gotten it to the
4595 // point where it's safe to start layout on it.
4596 bool mMayStartLayout
: 1;
4598 // True iff we've ever fired a DOMTitleChanged event for this document
4599 bool mHaveFiredTitleChange
: 1;
4601 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4602 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4603 // before the initial load completes and when we're in bfcache or unloaded,
4605 bool mIsShowing
: 1;
4607 // State for IsVisible(). mVisible starts off true. It becomes false when
4608 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4609 // it's false only when we're in bfcache or unloaded.
4612 // True if our content viewer has been removed from the docshell
4613 // (it may still be displayed, but in zombie state). Form control data
4615 bool mRemovedFromDocShell
: 1;
4617 // True iff DNS prefetch is allowed for this document. Note that if the
4618 // document has no window, DNS prefetch won't be performed no matter what.
4619 bool mAllowDNSPrefetch
: 1;
4621 // True when this document is a static clone of a normal document
4622 bool mIsStaticDocument
: 1;
4624 // True while this document is being cloned to a static document.
4625 bool mCreatingStaticClone
: 1;
4627 // True if this static document has any <canvas> element with a
4628 // mozPrintCallback property at the time of the clone.
4629 bool mHasPrintCallbacks
: 1;
4631 // True iff the document is being unlinked or deleted.
4632 bool mInUnlinkOrDeletion
: 1;
4634 // True if document has ever had script handling object.
4635 bool mHasHadScriptHandlingObject
: 1;
4637 // True if we're an SVG document being used as an image.
4638 bool mIsBeingUsedAsImage
: 1;
4640 // True if our current document URI's scheme enables privileged CSS rules.
4641 bool mChromeRulesEnabled
: 1;
4643 // True if we're loaded in a chrome docshell.
4644 bool mInChromeDocShell
: 1;
4646 // True if our current document is a DevTools document. Either the url is
4647 // about:devtools-toolbox or the parent document already has
4648 // mIsDevToolsDocument set to true.
4649 // This is used to avoid applying High Contrast mode to DevTools documents.
4651 bool mIsDevToolsDocument
: 1;
4653 // True is this document is synthetic : stand alone image, video, audio
4655 bool mIsSyntheticDocument
: 1;
4657 // True is there is a pending runnable which will call
4658 // FlushPendingLinkUpdates().
4659 bool mHasLinksToUpdateRunnable
: 1;
4661 // True if we're flushing pending link updates.
4662 bool mFlushingPendingLinkUpdates
: 1;
4664 // True if a DOMMutationObserver is perhaps attached to a node in the
4666 bool mMayHaveDOMMutationObservers
: 1;
4668 // True if an nsIAnimationObserver is perhaps attached to a node in the
4670 bool mMayHaveAnimationObservers
: 1;
4672 // True if the document has a CSP delivered throuh a header
4673 bool mHasCSPDeliveredThroughHeader
: 1;
4675 // True if DisallowBFCaching has been called on this document.
4676 bool mBFCacheDisallowed
: 1;
4678 bool mHasHadDefaultView
: 1;
4680 // Whether style sheet change events will be dispatched for this document
4681 bool mStyleSheetChangeEventsEnabled
: 1;
4683 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4684 // will be dispatched for this document.
4685 bool mDevToolsAnonymousAndShadowEventsEnabled
: 1;
4687 // Whether the document was created by a srcdoc iframe.
4688 bool mIsSrcdocDocument
: 1;
4690 // Whether this document has a display document and thus is considered to
4691 // be a resource document. Normally this is the same as !!mDisplayDocument,
4692 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4693 // valid in the document's destructor.
4694 bool mHasDisplayDocument
: 1;
4696 // Is the current mFontFaceSet valid?
4697 bool mFontFaceSetDirty
: 1;
4699 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4700 // (e.g. we're not being parsed at all).
4701 bool mDidFireDOMContentLoaded
: 1;
4703 // True if we have frame request callbacks scheduled with the refresh driver.
4704 // This should generally be updated only via
4705 // UpdateFrameRequestCallbackSchedulingState.
4706 bool mFrameRequestCallbacksScheduled
: 1;
4708 bool mIsTopLevelContentDocument
: 1;
4710 bool mIsContentDocument
: 1;
4712 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4713 bool mDidCallBeginLoad
: 1;
4715 // True if the encoding menu should be disabled.
4716 bool mEncodingMenuDisabled
: 1;
4718 // False if we've disabled link handling for elements inside this document,
4720 bool mLinksEnabled
: 1;
4722 // True if this document is for an SVG-in-OpenType font.
4723 bool mIsSVGGlyphsDocument
: 1;
4725 // True if the document is being destroyed.
4726 bool mInDestructor
: 1;
4728 // True if the document has been detached from its content viewer.
4729 bool mIsGoingAway
: 1;
4731 bool mInXBLUpdate
: 1;
4733 // Whether we have filled our style set with all the stylesheets.
4734 bool mStyleSetFilled
: 1;
4736 // Whether we have a quirks mode stylesheet in the style set.
4737 bool mQuirkSheetAdded
: 1;
4739 // Whether we have a contenteditable.css stylesheet in the style set.
4740 bool mContentEditableSheetAdded
: 1;
4742 // Whether we have a designmode.css stylesheet in the style set.
4743 bool mDesignModeSheetAdded
: 1;
4745 // True if this document has ever had an HTML or SVG <title> element
4747 bool mMayHaveTitleElement
: 1;
4749 bool mDOMLoadingSet
: 1;
4750 bool mDOMInteractiveSet
: 1;
4751 bool mDOMCompleteSet
: 1;
4752 bool mAutoFocusFired
: 1;
4754 bool mScrolledToRefAlready
: 1;
4755 bool mChangeScrollPosWhenScrollingToRef
: 1;
4757 bool mDelayFrameLoaderInitialization
: 1;
4759 bool mSynchronousDOMContentLoaded
: 1;
4761 // Set to true when the document is possibly controlled by the ServiceWorker.
4762 // Used to prevent multiple requests to ServiceWorkerManager.
4763 bool mMaybeServiceWorkerControlled
: 1;
4765 // These member variables cache information about the viewport so we don't
4766 // have to recalculate it each time.
4767 bool mAllowZoom
: 1;
4768 bool mValidScaleFloat
: 1;
4769 bool mValidMinScale
: 1;
4770 bool mValidMaxScale
: 1;
4771 bool mWidthStrEmpty
: 1;
4773 // Parser aborted. True if the parser of this document was forcibly
4774 // terminated instead of letting it finish at its own pace.
4775 bool mParserAborted
: 1;
4777 // Whether we have reported document use counters for this document with
4778 // Telemetry yet. Normally this is only done at document destruction time,
4779 // but for image documents (SVG documents) that are not guaranteed to be
4780 // destroyed, we report use counters when the image cache no longer has any
4781 // imgRequestProxys pointing to them. We track whether we ever reported use
4782 // counters so that we only report them once for the document.
4783 bool mReportedDocumentUseCounters
: 1;
4785 bool mHasReportedShadowDOMUsage
: 1;
4787 // Whether an event triggered by the refresh driver was delayed because this
4788 // document has suppressed events.
4789 bool mHasDelayedRefreshEvent
: 1;
4791 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4792 // to have the right semantics. See
4793 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4794 // flag that is set while the window's 'load' event is firing if this document
4795 // is the window's document.
4796 bool mLoadEventFiring
: 1;
4798 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4799 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4800 // What we have instead is a flag that is set if completion of our document
4801 // via document.close() should skip firing the load event. Note that this
4802 // flag is only relevant for HTML documents, but lives here for reasons that
4803 // are documented above on SkipLoadEventAfterClose().
4804 bool mSkipLoadEventAfterClose
: 1;
4806 // When false, the .cookies property is completely disabled
4807 bool mDisableCookieAccess
: 1;
4809 // When false, the document.write() API is disabled.
4810 bool mDisableDocWrite
: 1;
4812 // Has document.write() been called with a recursion depth higher than
4814 bool mTooDeepWriteRecursion
: 1;
4817 * Temporary flag that is set in EndUpdate() to ignore
4818 * MaybeEditingStateChanged() script runners from a nested scope.
4820 bool mPendingMaybeEditingStateChanged
: 1;
4822 // mHasBeenEditable is set to true when mEditingState is firstly set to
4823 // eDesignMode or eContentEditable.
4824 bool mHasBeenEditable
: 1;
4826 // Whether we've warned about the CSS zoom property.
4828 // We don't use the general deprecated operation mechanism for this because we
4829 // also record this as a `CountedUnknownProperty`.
4830 bool mHasWarnedAboutZoom
: 1;
4832 // While we're handling an execCommand call, set to true.
4833 bool mIsRunningExecCommand
: 1;
4835 // True if we should change the readystate to complete after we fire
4836 // DOMContentLoaded. This happens when we abort a load and
4837 // nsDocumentViewer::EndLoad runs while we still have things blocking
4838 // DOMContentLoaded. We wait for those to complete, and then update the
4839 // readystate when they finish.
4840 bool mSetCompleteAfterDOMContentLoaded
: 1;
4842 // Set the true if a completed cached stylesheet was created for the document.
4843 bool mDidHitCompleteSheetCache
: 1;
4845 // Whether we have initialized mShouldReportUseCounters and
4846 // mShouldSendPageUseCounters, and sent any needed message to the parent
4847 // process to indicate that use counter data will be sent at some later point.
4848 bool mUseCountersInitialized
: 1;
4850 // Whether this document should report use counters.
4851 bool mShouldReportUseCounters
: 1;
4853 // Whether this document should send page use counters. Set to true after
4854 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4855 bool mShouldSendPageUseCounters
: 1;
4857 // Whether the user has interacted with the document or not:
4858 bool mUserHasInteracted
: 1;
4860 // We constantly update the user-interaction anti-tracking permission at any
4861 // user-interaction using a timer. This boolean value is set to true when this
4862 // timer is scheduled.
4863 bool mHasUserInteractionTimerScheduled
: 1;
4865 // Whether we should resist fingerprinting.
4866 bool mShouldResistFingerprinting
: 1;
4868 uint8_t mXMLDeclarationBits
;
4870 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4871 // use uint8_t to avoid having to include a bunch of style system headers
4873 uint8_t mColorSchemeBits
= 0;
4875 // Currently active onload blockers.
4876 uint32_t mOnloadBlockCount
;
4878 // Tracks if we are currently processing any document.write calls (either
4879 // implicit or explicit). Note that if a write call writes out something which
4880 // would block the parser, then mWriteLevel will be incorrect until the parser
4881 // finishes processing that script.
4882 uint32_t mWriteLevel
;
4884 uint32_t mContentEditableCount
;
4885 EditingState mEditingState
;
4887 // Compatibility mode
4888 nsCompatibility mCompatMode
;
4891 ReadyState mReadyState
;
4893 // Ancestor's loading state
4894 bool mAncestorIsLoading
;
4896 // Our visibility state
4897 dom::VisibilityState mVisibilityState
;
4900 eUnknown
, // should never be used
4909 uint8_t mDefaultElementType
;
4911 enum Tri
{ eTriUnset
= 0, eTriFalse
, eTriTrue
};
4915 bool mSkipDTDSecurityChecks
;
4917 // The document's script global object, the object from which the
4918 // document can get its script context and scope. This is the
4919 // *inner* window object.
4920 nsCOMPtr
<nsIScriptGlobalObject
> mScriptGlobalObject
;
4922 // If mIsStaticDocument is true, mOriginalDocument points to the original
4924 RefPtr
<Document
> mOriginalDocument
;
4926 // The bidi options for this document. What this bitfield means is
4927 // defined in nsBidiUtils.h
4928 uint32_t mBidiOptions
;
4930 // The sandbox flags on the document. These reflect the value of the sandbox
4931 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4932 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4934 uint32_t mSandboxFlags
;
4936 // The embedder policy obtained from parsing the HTTP response header or from
4937 // our opener if this is the initial about:blank document.
4938 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> mEmbedderPolicy
;
4940 nsCString mContentLanguage
;
4942 // The channel that got passed to Document::StartDocumentLoad(), if any.
4943 nsCOMPtr
<nsIChannel
> mChannel
;
4945 // The CSP for every load lives in the Client within the LoadInfo. For all
4946 // document-initiated subresource loads we can use that cached version of the
4947 // CSP so we do not have to deserialize the CSP from the Client all the time.
4948 nsCOMPtr
<nsIContentSecurityPolicy
> mCSP
;
4949 nsCOMPtr
<nsIContentSecurityPolicy
> mPreloadCSP
;
4952 nsCString mContentType
;
4955 // The document's security info
4956 nsCOMPtr
<nsITransportSecurityInfo
> mSecurityInfo
;
4958 // The channel that failed to load and resulted in an error page.
4959 // This only applies to error pages. Might be null.
4960 nsCOMPtr
<nsIChannel
> mFailedChannel
;
4962 // if this document is part of a multipart document,
4963 // the ID can be used to distinguish it from the other parts.
4966 // Cycle collector generation in which we're certain that this document
4967 // won't be collected
4968 uint32_t mMarkedCCGeneration
;
4970 PresShell
* mPresShell
;
4972 nsCOMArray
<nsINode
> mSubtreeModifiedTargets
;
4973 uint32_t mSubtreeModifiedDepth
;
4975 // All images in process of being preloaded. This is a hashtable so
4976 // we can remove them as the real image loads start; that way we
4977 // make sure to not keep the image load going when no one cares
4978 // about it anymore.
4979 nsRefPtrHashtable
<nsURIHashKey
, imgIRequest
> mPreloadingImages
;
4981 // A list of preconnects initiated by the preloader. This prevents
4982 // the same uri from being used more than once, and allows the dom
4983 // builder to not repeat the work of the preloader.
4984 nsTHashMap
<nsURIHashKey
, bool> mPreloadedPreconnects
;
4986 // Current depth of picture elements from parser
4987 uint32_t mPreloadPictureDepth
;
4989 // Set if we've found a URL for the current picture
4990 nsString mPreloadPictureFoundSource
;
4992 // If we're an external resource document, this will be non-null and will
4993 // point to our "display document": the one that all resource lookups should
4995 RefPtr
<Document
> mDisplayDocument
;
4997 uint32_t mEventsSuppressed
;
4999 // Any XHR ChannelEventQueues that were suspended on this document while
5000 // events were suppressed.
5001 nsTArray
<RefPtr
<net::ChannelEventQueue
>> mSuspendedQueues
;
5003 // Any postMessage events that were suspended on this document while events
5005 nsTArray
<RefPtr
<PostMessageEvent
>> mSuspendedPostMessageEvents
;
5007 RefPtr
<EventListener
> mSuppressedEventListener
;
5010 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5012 uint32_t mIgnoreDestructiveWritesCounter
;
5014 // Count of live static clones of this document.
5015 uint32_t mStaticCloneCount
;
5017 // If the document is currently printing (or in print preview) this will point
5018 // to the current static clone of this document. This is weak since the clone
5019 // also has a reference to this document.
5020 WeakPtr
<Document
> mLatestStaticClone
;
5022 // Array of nodes that have been blocked to prevent user tracking.
5023 // They most likely have had their nsIChannel canceled by the URL
5024 // classifier. (Safebrowsing)
5026 // Weak nsINode pointers are used to allow nodes to disappear.
5027 nsTArray
<nsWeakPtr
> mBlockedNodesByClassifier
;
5029 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5030 // updated on every set of mScriptGlobalObject.
5031 nsPIDOMWindowInner
* mWindow
;
5033 nsCOMPtr
<nsIDocumentEncoder
> mCachedEncoder
;
5035 FrameRequestManager mFrameRequestManager
;
5037 // This object allows us to evict ourself from the back/forward cache. The
5038 // pointer is non-null iff we're currently in the bfcache.
5039 nsIBFCacheEntry
* mBFCacheEntry
;
5042 nsString mBaseTarget
;
5044 nsCOMPtr
<nsIStructuredCloneContainer
> mStateObjectContainer
;
5045 JS::Heap
<JS::Value
> mCachedStateObject
;
5047 uint32_t mInSyncOperationCount
;
5049 UniquePtr
<dom::XPathEvaluator
> mXPathEvaluator
;
5051 nsTArray
<RefPtr
<AnonymousContent
>> mAnonymousContents
;
5053 uint32_t mBlockDOMContentLoaded
;
5055 // Our live MediaQueryLists
5056 LinkedList
<MediaQueryList
> mDOMMediaQueryLists
;
5058 // Array of observers
5059 nsTObserverArray
<nsIDocumentObserver
*> mObservers
;
5061 // Flags for use counters used directly by this document.
5062 UseCounters mUseCounters
;
5063 // Flags for use counters from resource documents, static clones,
5064 // and SVG images referenced by this document. Those documents propagate
5065 // their use counters up to here, which then count towards the top-level
5066 // document's page use counters.
5067 UseCounters mChildDocumentUseCounters
;
5069 // The CSS property use counters.
5070 UniquePtr
<StyleUseCounters
> mStyleUseCounters
;
5072 TimeStamp mPageUnloadingEventTimeStamp
;
5074 RefPtr
<DocGroup
> mDocGroup
;
5076 RefPtr
<nsCommandManager
> mMidasCommandManager
;
5078 // The set of all the tracking script URLs. URLs are added to this set by
5079 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5080 // existing in the set means the corresponding script isn't a tracking script.
5081 nsTHashSet
<nsCString
> mTrackingScripts
;
5083 // Pointer to our parser if we're currently in the process of being
5085 nsCOMPtr
<nsIParser
> mParser
;
5087 // If the document was created from the the prototype cache there will be a
5088 // reference to the prototype document to allow tracing.
5089 RefPtr
<nsXULPrototypeDocument
> mPrototypeDocument
;
5091 // Weak reference to our sink for in case we no longer have a parser. This
5092 // will allow us to flush out any pending stuff from the sink even if
5093 // EndLoad() has already happened.
5094 nsWeakPtr mWeakSink
;
5096 // Our update nesting level
5097 uint32_t mUpdateNestLevel
;
5099 // HTTPS-Only Mode Status
5100 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5101 uint32_t mHttpsOnlyStatus
;
5103 enum ViewportType
: uint8_t {
5109 ViewportType mViewportType
;
5111 // viewport-fit described by
5112 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5113 ViewportFitType mViewportFit
;
5115 PLDHashTable
* mSubDocuments
;
5118 UniquePtr
<HeaderData
> mHeaderData
;
5120 nsTArray
<net::EarlyHintConnectArgs
> mEarlyHints
;
5122 nsRevocableEventPtr
<nsRunnableMethod
<Document
, void, false>>
5123 mPendingTitleChangeEvent
;
5125 RefPtr
<nsDOMNavigationTiming
> mTiming
;
5127 // Recorded time of change to 'loading' state.
5128 TimeStamp mLoadingTimeStamp
;
5130 // Decided to use nsTObserverArray because it allows us to
5131 // remove candidates while iterating them and this is what
5132 // the spec defines. We could implement the spec without
5133 // using nsTObserverArray, however using nsTObserverArray is more clear.
5134 nsTObserverArray
<nsWeakPtr
> mAutoFocusCandidates
;
5136 nsCString mScrollToRef
;
5138 // Weak reference to the scope object (aka the script global object)
5139 // that, unlike mScriptGlobalObject, is never unset once set. This
5140 // is a weak reference to avoid leaks due to circular references.
5141 nsWeakPtr mScopeObject
;
5143 // Array of intersection observers
5144 nsTHashSet
<DOMIntersectionObserver
*> mIntersectionObservers
;
5146 RefPtr
<DOMIntersectionObserver
> mLazyLoadImageObserver
;
5147 // Used to measure how effective the lazyload thresholds are.
5148 RefPtr
<DOMIntersectionObserver
> mLazyLoadImageObserverViewport
;
5150 // Used for detecting when `content-visibility: auto` elements are near
5151 // or far from the viewport.
5152 RefPtr
<DOMIntersectionObserver
> mContentVisibilityObserver
;
5154 // ResizeObserver for storing and removing the last remembered size.
5155 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5156 RefPtr
<ResizeObserver
> mLastRememberedSizeObserver
;
5158 // Stack of top layer elements.
5159 nsTArray
<nsWeakPtr
> mTopLayer
;
5161 // The root of the doc tree in which this document is in. This is only
5162 // non-null when this document is in fullscreen mode.
5163 nsWeakPtr mFullscreenRoot
;
5165 RefPtr
<DOMImplementation
> mDOMImplementation
;
5167 RefPtr
<nsContentList
> mImageMaps
;
5169 // A set of responsive images keyed by address pointer.
5170 nsTHashSet
<HTMLImageElement
*> mResponsiveContent
;
5172 RefPtr
<DocumentTimeline
> mDocumentTimeline
;
5173 LinkedList
<DocumentTimeline
> mTimelines
;
5175 RefPtr
<dom::ScriptLoader
> mScriptLoader
;
5177 // Tracker for animations that are waiting to start.
5178 // nullptr until GetOrCreatePendingAnimationTracker is called.
5179 RefPtr
<PendingAnimationTracker
> mPendingAnimationTracker
;
5181 // Tracker for scroll-driven animations that are waiting to start.
5182 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5183 RefPtr
<ScrollTimelineAnimationTracker
> mScrollTimelineAnimationTracker
;
5185 // A document "without a browsing context" that owns the content of
5186 // HTMLTemplateElement.
5187 RefPtr
<Document
> mTemplateContentsOwner
;
5189 dom::ExternalResourceMap mExternalResourceMap
;
5191 // ScreenOrientation "pending promise" as described by
5192 // http://www.w3.org/TR/screen-orientation/
5193 RefPtr
<Promise
> mOrientationPendingPromise
;
5195 nsTArray
<RefPtr
<nsFrameLoader
>> mInitializableFrameLoaders
;
5196 nsTArray
<nsCOMPtr
<nsIRunnable
>> mFrameLoaderFinalizers
;
5197 RefPtr
<nsRunnableMethod
<Document
>> mFrameLoaderRunner
;
5199 nsTArray
<PendingFrameStaticClone
> mPendingFrameStaticClones
;
5201 // The layout history state that should be used by nodes in this
5202 // document. We only actually store a pointer to it when:
5203 // 1) We have no script global object.
5204 // 2) We haven't had Destroy() called on us yet.
5205 nsCOMPtr
<nsILayoutHistoryState
> mLayoutHistoryState
;
5207 // The parsed viewport metadata of the last modified <meta name=viewport>
5209 UniquePtr
<ViewportMetaData
> mLastModifiedViewportMetaData
;
5211 // A tree ordered list of all color-scheme meta tags in this document.
5213 // TODO(emilio): There are other meta tags in the spec that have a similar
5214 // processing model to color-scheme. We could store all in-document meta tags
5215 // here to get sane and fast <meta> element processing.
5216 TreeOrderedArray
<HTMLMetaElement
> mColorSchemeMetaTags
;
5218 // These member variables cache information about the viewport so we don't
5219 // have to recalculate it each time.
5220 LayoutDeviceToScreenScale mScaleMinFloat
;
5221 LayoutDeviceToScreenScale mScaleMaxFloat
;
5222 LayoutDeviceToScreenScale mScaleFloat
;
5223 CSSToLayoutDeviceScale mPixelRatio
;
5227 CSSCoord mMinHeight
;
5228 CSSCoord mMaxHeight
;
5230 RefPtr
<EventListenerManager
> mListenerManager
;
5232 nsCOMPtr
<nsIRequest
> mOnloadBlocker
;
5234 // Gecko-internal sheets used for extensions and such.
5235 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5236 nsTArray
<RefPtr
<StyleSheet
>> mAdditionalSheets
[AdditionalSheetTypeCount
];
5238 // Member to store out last-selected stylesheet set.
5239 nsString mLastStyleSheetSet
;
5240 nsString mPreferredStyleSheetSet
;
5242 RefPtr
<DOMStyleSheetSetList
> mStyleSheetSetList
;
5244 // We lazily calculate declaration blocks for elements with mapped
5245 // attributes. This set contains all elements which need lazy resolution.
5246 nsTHashSet
<Element
*> mLazyPresElements
;
5248 nsTHashSet
<RefPtr
<nsAtom
>> mLanguagesUsed
;
5250 // TODO(emilio): Is this hot enough to warrant to be cached?
5251 RefPtr
<nsAtom
> mLanguageFromCharset
;
5253 // Restyle root for servo's style system.
5255 // We store this as an nsINode, rather than as an Element, so that we can
5256 // store the Document node as the restyle root if the entire document (along
5257 // with all document-level native-anonymous content) needs to be restyled.
5259 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5260 // root corresponds to.
5261 nsCOMPtr
<nsINode
> mServoRestyleRoot
;
5262 uint32_t mServoRestyleRootDirtyBits
;
5264 // Used in conjunction with the create-an-element-for-the-token algorithm to
5265 // prevent custom element constructors from being able to use document.open(),
5266 // document.close(), and document.write() when they are invoked by the parser.
5267 uint32_t mThrowOnDynamicMarkupInsertionCounter
;
5269 // Count of unload/beforeunload/pagehide operations in progress.
5270 uint32_t mIgnoreOpensDuringUnloadCounter
;
5272 nsCOMPtr
<nsIDOMXULCommandDispatcher
>
5273 mCommandDispatcher
; // [OWNER] of the focus tracker
5275 RefPtr
<XULBroadcastManager
> mXULBroadcastManager
;
5276 RefPtr
<XULPersist
> mXULPersist
;
5277 RefPtr
<ChromeObserver
> mChromeObserver
;
5279 RefPtr
<HTMLAllCollection
> mAll
;
5281 nsTHashSet
<RefPtr
<WorkerDocumentListener
>> mWorkerListeners
;
5283 // Pres shell resolution saved before entering fullscreen mode.
5284 float mSavedResolution
;
5286 // Pres shell resolution saved before creating a MobileViewportManager.
5287 float mSavedResolutionBeforeMVM
;
5289 nsCOMPtr
<nsICookieJarSettings
> mCookieJarSettings
;
5291 bool mHasStoragePermission
;
5293 // Document generation. Gets incremented everytime it changes.
5294 int32_t mGeneration
;
5296 // Cached TabSizes values for the document.
5297 int32_t mCachedTabSizeGeneration
;
5298 nsTabSizes mCachedTabSizes
;
5300 // This is equal to document's principal but with an isolation key. See
5301 // StoragePrincipalHelper.h to know more.
5302 nsCOMPtr
<nsIPrincipal
> mPartitionedPrincipal
;
5304 // The cached storage principal for this document.
5305 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5306 // which is required due to its CloneDocHelper() call site. :-(
5307 mutable nsCOMPtr
<nsIPrincipal
> mActiveStoragePrincipal
;
5309 // The cached cookie principal for this document.
5310 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5311 // which is required due to its CloneDocHelper() call site. :-(
5312 mutable nsCOMPtr
<nsIPrincipal
> mActiveCookiePrincipal
;
5314 // See GetNextFormNumber and GetNextControlNumber.
5315 int32_t mNextFormNumber
;
5316 int32_t mNextControlNumber
;
5318 uint32_t mMediaElementWithMSECount
= 0;
5320 // Scope preloads per document. This is used by speculative loading as well.
5321 PreloadService mPreloadService
;
5323 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5324 bool mShouldNotifyFetchSuccess
;
5326 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5327 bool mShouldNotifyFormOrPasswordRemoved
;
5329 // Record page load telemetry
5330 void RecordPageLoadEventTelemetry(
5331 glean::perf::PageLoadExtra
& aEventTelemetryData
);
5333 // Accumulate JS telemetry collected
5334 void AccumulateJSTelemetry(
5335 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5337 // Accumulate page load metrics
5338 void AccumulatePageLoadTelemetry(
5339 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5341 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5342 // Not holding strong refs here since we don't actually use the BBCs.
5343 nsTArray
<const BrowserBridgeChild
*> mOOPChildrenLoading
;
5345 // Registry of custom highlight definitions associated with this document.
5346 RefPtr
<class HighlightRegistry
> mHighlightRegistry
;
5349 // Needs to be public because the bindings code pokes at it.
5350 JS::ExpandoAndGeneration mExpandoAndGeneration
;
5352 bool HasPendingInitialTranslation();
5354 nsRefPtrHashtable
<nsRefPtrHashKey
<Element
>, nsXULPrototypeElement
>
5357 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM
; }
5358 void SetSavedResolutionBeforeMVM(float aResolution
) {
5359 mSavedResolutionBeforeMVM
= aResolution
;
5362 void LoadEventFired();
5365 NS_DEFINE_STATIC_IID_ACCESSOR(Document
, NS_IDOCUMENT_IID
)
5368 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5369 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5370 * object is deleted.
5372 class MOZ_STACK_CLASS mozAutoSubtreeModified
{
5375 * @param aSubTreeOwner The document in which a subtree will be modified.
5376 * @param aTarget The target of the possible DOMSubtreeModified event.
5377 * Can be nullptr, in which case mozAutoSubtreeModified
5378 * is just used to batch DOM mutations.
5380 mozAutoSubtreeModified(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5381 UpdateTarget(aSubtreeOwner
, aTarget
);
5384 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5386 void UpdateTarget(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5387 if (mSubtreeOwner
) {
5388 mSubtreeOwner
->MutationEventDispatched(mTarget
);
5392 mSubtreeOwner
= aSubtreeOwner
;
5393 if (mSubtreeOwner
) {
5394 mSubtreeOwner
->WillDispatchMutationEvent(mTarget
);
5399 nsCOMPtr
<nsINode
> mTarget
;
5400 RefPtr
<Document
> mSubtreeOwner
;
5403 enum class SyncOperationBehavior
{ eSuspendInput
, eAllowInput
};
5405 class AutoWalkBrowsingContextGroup
{
5407 virtual ~AutoWalkBrowsingContextGroup() = default;
5410 void SuppressBrowsingContext(BrowsingContext
* aContext
);
5411 void SuppressBrowsingContextGroup(BrowsingContextGroup
* aGroup
);
5412 void UnsuppressDocuments() {
5413 for (const auto& doc
: mDocuments
) {
5414 UnsuppressDocument(doc
);
5417 virtual void SuppressDocument(Document
* aDocument
) = 0;
5418 virtual void UnsuppressDocument(Document
* aDocument
) = 0;
5419 AutoTArray
<RefPtr
<Document
>, 16> mDocuments
;
5422 class MOZ_RAII nsAutoSyncOperation
: private AutoWalkBrowsingContextGroup
{
5424 explicit nsAutoSyncOperation(Document
* aDocument
,
5425 SyncOperationBehavior aSyncBehavior
);
5426 ~nsAutoSyncOperation();
5429 void SuppressDocument(Document
* aDocument
) override
;
5430 void UnsuppressDocument(Document
* aDocument
) override
;
5433 uint32_t mMicroTaskLevel
;
5434 const SyncOperationBehavior mSyncBehavior
;
5435 RefPtr
<BrowsingContext
> mBrowsingContext
;
5438 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final
{
5440 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document
* aDocument
)
5441 : mDocument(aDocument
) {
5442 mDocument
->IncrementThrowOnDynamicMarkupInsertionCounter();
5445 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5446 mDocument
->DecrementThrowOnDynamicMarkupInsertionCounter();
5450 Document
* mDocument
;
5453 class MOZ_RAII IgnoreOpensDuringUnload final
{
5455 explicit IgnoreOpensDuringUnload(Document
* aDoc
) : mDoc(aDoc
) {
5456 mDoc
->IncrementIgnoreOpensDuringUnloadCounter();
5459 ~IgnoreOpensDuringUnload() {
5460 mDoc
->DecrementIgnoreOpensDuringUnloadCounter();
5467 bool IsInFocusedTab(Document
* aDoc
);
5469 // This covers all cases covered by IsInFocusedTab, but also ensures that
5470 // focused tab is "active" meaning not occluded.
5471 bool IsInActiveTab(Document
* aDoc
);
5473 } // namespace mozilla::dom
5475 // XXX These belong somewhere else
5476 nsresult
NS_NewHTMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5477 nsIPrincipal
* aPrincipal
,
5478 nsIPrincipal
* aPartitionedPrincipal
,
5479 bool aLoadedAsData
= false);
5481 nsresult
NS_NewXMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5482 nsIPrincipal
* aPrincipal
,
5483 nsIPrincipal
* aPartitionedPrincipal
,
5484 bool aLoadedAsData
= false,
5485 bool aIsPlainDocument
= false);
5487 nsresult
NS_NewSVGDocument(mozilla::dom::Document
** aInstancePtrResult
,
5488 nsIPrincipal
* aPrincipal
,
5489 nsIPrincipal
* aPartitionedPrincipal
);
5491 nsresult
NS_NewImageDocument(mozilla::dom::Document
** aInstancePtrResult
,
5492 nsIPrincipal
* aPrincipal
,
5493 nsIPrincipal
* aPartitionedPrincipal
);
5495 nsresult
NS_NewVideoDocument(mozilla::dom::Document
** aInstancePtrResult
,
5496 nsIPrincipal
* aPrincipal
,
5497 nsIPrincipal
* aPartitionedPrincipal
);
5499 // Enum for requesting a particular type of document when creating a doc
5500 enum DocumentFlavor
{
5501 DocumentFlavorLegacyGuess
, // compat with old code until made HTML5-compliant
5502 DocumentFlavorHTML
, // HTMLDocument with HTMLness bit set to true
5503 DocumentFlavorSVG
, // SVGDocument
5504 DocumentFlavorXML
, // XMLDocument
5505 DocumentFlavorPlain
, // Just a Document
5508 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5509 // -- this method will not attempt to get a principal based on aDocumentURI.
5510 // Also, both aDocumentURI and aBaseURI must not be null.
5511 nsresult
NS_NewDOMDocument(
5512 mozilla::dom::Document
** aInstancePtrResult
, const nsAString
& aNamespaceURI
,
5513 const nsAString
& aQualifiedName
, mozilla::dom::DocumentType
* aDoctype
,
5514 nsIURI
* aDocumentURI
, nsIURI
* aBaseURI
, nsIPrincipal
* aPrincipal
,
5515 bool aLoadedAsData
, nsIGlobalObject
* aEventObject
, DocumentFlavor aFlavor
);
5517 inline mozilla::dom::Document
* nsINode::GetOwnerDocument() const {
5518 mozilla::dom::Document
* ownerDoc
= OwnerDoc();
5520 return ownerDoc
!= this ? ownerDoc
: nullptr;
5523 inline nsINode
* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5525 inline mozilla::dom::Document
* nsINode::AsDocument() {
5526 MOZ_ASSERT(IsDocument());
5527 return static_cast<mozilla::dom::Document
*>(this);
5530 inline const mozilla::dom::Document
* nsINode::AsDocument() const {
5531 MOZ_ASSERT(IsDocument());
5532 return static_cast<const mozilla::dom::Document
*>(this);
5535 inline nsISupports
* ToSupports(mozilla::dom::Document
* aDoc
) {
5536 return static_cast<nsINode
*>(aDoc
);
5539 #endif /* mozilla_dom_Document_h___ */