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/TimeStamp.h"
44 #include "mozilla/UniquePtr.h"
45 #include "mozilla/UseCounter.h"
46 #include "mozilla/WeakPtr.h"
47 #include "mozilla/css/StylePreloadKind.h"
48 #include "mozilla/dom/AnimationFrameProvider.h"
49 #include "mozilla/dom/DocumentOrShadowRoot.h"
50 #include "mozilla/dom/Element.h"
51 #include "mozilla/dom/EventTarget.h"
52 #include "mozilla/dom/Nullable.h"
53 #include "mozilla/dom/RadioGroupContainer.h"
54 #include "mozilla/dom/TreeOrderedArray.h"
55 #include "mozilla/dom/ViewportMetaData.h"
56 #include "mozilla/glean/GleanMetrics.h"
58 #include "nsCOMArray.h"
60 #include "nsClassHashtable.h"
61 #include "nsCompatibility.h"
62 #include "nsContentListDeclarations.h"
63 #include "nsCycleCollectionParticipant.h"
64 #include "nsTHashMap.h"
66 #include "nsGkAtoms.h"
67 #include "nsHashKeys.h"
68 #include "nsIChannel.h"
69 #include "nsIChannelEventSink.h"
70 #include "nsIContentViewer.h"
72 #include "nsIInterfaceRequestor.h"
73 #include "nsILoadContext.h"
74 #include "nsILoadGroup.h"
75 #include "nsILoadInfo.h"
77 #include "nsIObserver.h"
78 #include "nsIParser.h"
79 #include "nsIPrincipal.h"
80 #include "nsIProgressEventSink.h"
81 #include "nsIReferrerInfo.h"
82 #include "nsIRequestObserver.h"
83 #include "nsIScriptObjectPrincipal.h"
84 #include "nsIStreamListener.h"
85 #include "nsISupports.h"
86 #include "nsISupportsUtils.h"
87 #include "nsITransportSecurityInfo.h"
89 #include "nsIWeakReferenceUtils.h"
90 #include "nsLiteralString.h"
91 #include "nsPIDOMWindow.h"
92 #include "nsPropertyTable.h"
93 #include "nsRefPtrHashtable.h"
96 #include "nsTHashSet.h"
97 #include "nsTLiteralString.h"
98 #include "nsTObserverArray.h"
99 #include "nsThreadUtils.h"
100 #include "nsURIHashKey.h"
101 #include "nsViewportInfo.h"
102 #include "nsWeakReference.h"
103 #include "nsWindowSizes.h"
104 #include "nsXULElement.h"
107 // XXX We need to include this here to ensure that DefaultDeleter for Servo
108 // types is specialized before the template is instantiated. Probably, this
109 // should be included at some other place already that's generated by cbindgen.
110 #include "mozilla/ServoBindingTypes.h"
112 // windows.h #defines CreateEvent
117 #ifdef MOZILLA_INTERNAL_API
118 # include "mozilla/dom/DocumentBinding.h"
122 class ElementCreationOptionsOrString
;
124 } // namespace mozilla
125 #endif // MOZILLA_INTERNAL_API
127 class InfallibleAllocPolicy
;
131 class gfxUserFontSet
;
132 class mozIDOMWindowProxy
;
133 class nsCachableElementsByNameNodeList
;
134 class nsCommandManager
;
136 class nsCycleCollectionTraversalCallback
;
137 class nsDOMCaretPosition
;
138 class nsDOMNavigationTiming
;
141 class nsFrameLoaderOwner
;
142 class nsGenericHTMLElement
;
143 class nsGlobalWindowInner
;
144 class nsHTMLDocument
;
145 class nsHtml5TreeOpExecutor
;
147 class nsIAsyncVerifyRedirectCallback
;
148 class nsIBFCacheEntry
;
150 class nsIContentSecurityPolicy
;
151 class nsIContentSink
;
152 class nsICookieJarSettings
;
153 class nsIDOMXULCommandDispatcher
;
155 class nsIDocShellTreeItem
;
156 class nsIDocumentEncoder
;
157 class nsIDocumentObserver
;
158 class nsIEventTarget
;
160 class nsIGlobalObject
;
161 class nsIHTMLCollection
;
162 class nsIInputStream
;
163 class nsILayoutHistoryState
;
164 class nsIObjectLoadingContent
;
165 class nsIPermissionDelegateHandler
;
166 class nsIRadioVisitor
;
169 class nsIScriptGlobalObject
;
170 class nsISecurityConsoleMessage
;
171 class nsISerialEventTarget
;
172 class nsIStructuredCloneContainer
;
174 class nsNodeInfoManager
;
175 class nsPIWindowRoot
;
178 class nsSimpleContentList
;
181 class nsXULPrototypeDocument
;
186 class AbstractThread
;
187 class AttributeStyles
;
193 class EventListenerManager
;
194 class FullscreenExit
;
195 class FullscreenRequest
;
197 struct LangGroupFontPrefs
;
198 class PendingAnimationTracker
;
199 class PermissionDelegateHandler
;
201 class ScrollTimelineAnimationTracker
;
203 enum class StyleOrigin
: uint8_t;
204 class SMILAnimationController
;
205 enum class StyleCursorKind
: uint8_t;
206 class SVGContextPaint
;
207 enum class ColorScheme
: uint8_t;
208 enum class StyleRuleChangeKind
: uint32_t;
209 struct StyleUseCounters
;
221 class AnonymousContent
;
223 class XULBroadcastManager
;
225 class BrowserBridgeChild
;
226 class ChromeObserver
;
233 class DocumentFragment
;
234 class DocumentTimeline
;
236 class DOMImplementation
;
237 class DOMIntersectionObserver
;
241 struct FailedCertSecurityInfo
;
244 class FrameRequestCallback
;
246 class HighlightRegistry
;
247 class HTMLAllCollection
;
248 class HTMLBodyElement
;
249 class HTMLInputElement
;
250 class HTMLMetaElement
;
251 class HTMLDialogElement
;
252 class HTMLSharedElement
;
253 class HTMLImageElement
;
254 struct LifecycleCallbackArgs
;
257 class MediaQueryList
;
262 enum class OrientationType
: uint8_t;
263 class ProcessingInstruction
;
267 class ServiceWorkerDescriptor
;
277 enum class ViewportFitType
: uint8_t;
279 class WindowGlobalChild
;
280 class WindowProxyHolder
;
282 class WorkerDocumentListener
;
283 class XPathEvaluator
;
284 class XPathExpression
;
285 class XPathNSResolver
;
287 class BrowsingContext
;
289 class nsUnblockOnloadEvent
;
291 template <typename
, typename
>
292 class CallbackObjectHolder
;
294 enum class CallerType
: uint32_t;
297 NOT_ALLOWED
= 1 << 0, // Status 0
298 EVENT_HANDLING_SUPPRESSED
= 1 << 1, // Status 1
299 SUSPENDED
= 1 << 2, // Status 2
300 UNLOAD_LISTENER
= 1 << 3, // Status 3
301 REQUEST
= 1 << 4, // Status 4
302 ACTIVE_GET_USER_MEDIA
= 1 << 5, // Status 5
303 ACTIVE_PEER_CONNECTION
= 1 << 6, // Status 6
304 CONTAINS_EME_CONTENT
= 1 << 7, // Status 7
305 CONTAINS_MSE_CONTENT
= 1 << 8, // Status 8
306 HAS_ACTIVE_SPEECH_SYNTHESIS
= 1 << 9, // Status 9
307 HAS_USED_VR
= 1 << 10, // Status 10
308 CONTAINS_REMOTE_SUBFRAMES
= 1 << 11, // Status 11
309 NOT_ONLY_TOPLEVEL_IN_BCG
= 1 << 12, // Status 12
310 ABOUT_PAGE
= 1 << 13, // Status 13
311 RESTORING
= 1 << 14, // Status 14
312 BEFOREUNLOAD_LISTENER
= 1 << 15, // Status 15
313 ACTIVE_LOCK
= 1 << 16, // Status 16
314 ACTIVE_WEBTRANSPORT
= 1 << 17, // Status 17
318 } // namespace mozilla
320 namespace mozilla::net
{
321 class ChannelEventQueue
;
322 class EarlyHintConnectArgs
;
323 } // namespace mozilla::net
325 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
326 #define NS_IDOCUMENT_IID \
328 0xce1f7627, 0x7109, 0x4977, { \
329 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
333 namespace mozilla::dom
{
336 class DOMStyleSheetSetList
;
337 class ResizeObserver
;
338 class ResizeObserverController
;
339 class PostMessageEvent
;
341 #define DEPRECATED_OPERATION(_op) e##_op,
342 enum class DeprecatedOperations
: uint16_t {
343 #include "nsDeprecatedOperationList.h"
344 eDeprecatedOperationCount
346 #undef DEPRECATED_OPERATION
348 class ExternalResourceMap
{
349 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
353 * A class that represents an external resource load that has begun but
354 * doesn't have a document yet. Observers can be registered on this object,
355 * and will be notified after the document is created. Observers registered
356 * after the document has been created will NOT be notified. When observers
357 * are notified, the subject will be the newly-created document, the topic
358 * will be "external-resource-document-created", and the data will be null.
359 * If document creation fails for some reason, observers will still be
360 * notified, with a null document pointer.
362 class ExternalResourceLoad
: public nsISupports
{
364 virtual ~ExternalResourceLoad() = default;
366 void AddObserver(nsIObserver
* aObserver
) {
367 MOZ_ASSERT(aObserver
, "Must have observer");
368 mObservers
.AppendElement(aObserver
);
371 const nsTArray
<nsCOMPtr
<nsIObserver
>>& Observers() { return mObservers
; }
374 AutoTArray
<nsCOMPtr
<nsIObserver
>, 8> mObservers
;
377 ExternalResourceMap();
380 * Request an external resource document. This does exactly what
381 * Document::RequestExternalResource is documented to do.
383 Document
* RequestResource(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
384 nsINode
* aRequestingNode
,
385 Document
* aDisplayDocument
,
386 ExternalResourceLoad
** aPendingLoad
);
389 * Enumerate the resource documents. See
390 * Document::EnumerateExternalResources.
392 void EnumerateResources(SubDocEnumFunc aCallback
);
395 * Traverse ourselves for cycle-collection
397 void Traverse(nsCycleCollectionTraversalCallback
* aCallback
) const;
400 * Shut ourselves down (used for cycle-collection unlink), as well
401 * as for document destruction.
404 mPendingLoads
.Clear();
406 mHaveShutDown
= true;
409 bool HaveShutDown() const { return mHaveShutDown
; }
411 // Needs to be public so we can traverse them sanely
412 struct ExternalResource
{
414 RefPtr
<Document
> mDocument
;
415 nsCOMPtr
<nsIContentViewer
> mViewer
;
416 nsCOMPtr
<nsILoadGroup
> mLoadGroup
;
419 // Hide all our viewers
422 // Show all our viewers
426 class PendingLoad
: public ExternalResourceLoad
, public nsIStreamListener
{
427 ~PendingLoad() = default;
430 explicit PendingLoad(Document
* aDisplayDocument
)
431 : mDisplayDocument(aDisplayDocument
) {}
434 NS_DECL_NSISTREAMLISTENER
435 NS_DECL_NSIREQUESTOBSERVER
438 * Start aURI loading. This will perform the necessary security checks and
441 nsresult
StartLoad(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
442 nsINode
* aRequestingNode
);
444 * Set up an nsIContentViewer based on aRequest. This is guaranteed to
445 * put null in *aViewer and *aLoadGroup on all failures.
447 nsresult
SetupViewer(nsIRequest
* aRequest
, nsIContentViewer
** aViewer
,
448 nsILoadGroup
** aLoadGroup
);
451 RefPtr
<Document
> mDisplayDocument
;
452 nsCOMPtr
<nsIStreamListener
> mTargetListener
;
453 nsCOMPtr
<nsIURI
> mURI
;
455 friend class PendingLoad
;
457 class LoadgroupCallbacks final
: public nsIInterfaceRequestor
{
458 ~LoadgroupCallbacks() = default;
461 explicit LoadgroupCallbacks(nsIInterfaceRequestor
* aOtherCallbacks
)
462 : mCallbacks(aOtherCallbacks
) {}
464 NS_DECL_NSIINTERFACEREQUESTOR
466 // The only reason it's safe to hold a strong ref here without leaking is
467 // that the notificationCallbacks on a loadgroup aren't the docshell itself
468 // but a shim that holds a weak reference to the docshell.
469 nsCOMPtr
<nsIInterfaceRequestor
> mCallbacks
;
471 // Use shims for interfaces that docshell implements directly so that we
472 // don't hand out references to the docshell. The shims should all allow
473 // getInterface back on us, but other than that each one should only
474 // implement one interface.
476 // XXXbz I wish we could just derive the _allcaps thing from _i
477 #define DECL_SHIM(_i, _allcaps) \
478 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
482 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
483 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
484 NS_ASSERTION(mIfReq, "Expected non-null here"); \
485 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
488 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
489 NS_FORWARD_##_allcaps(mRealPtr->) private \
490 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
491 nsCOMPtr<_i> mRealPtr; \
494 DECL_SHIM(nsILoadContext
, NSILOADCONTEXT
)
495 DECL_SHIM(nsIProgressEventSink
, NSIPROGRESSEVENTSINK
)
496 DECL_SHIM(nsIChannelEventSink
, NSICHANNELEVENTSINK
)
501 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
502 * when this is called if the URI didn't result in an XML document. This
503 * function makes sure to remove the pending load for aURI, if any, from our
504 * hashtable, and to notify its observers, if any.
506 nsresult
AddExternalResource(nsIURI
* aURI
, nsIContentViewer
* aViewer
,
507 nsILoadGroup
* aLoadGroup
,
508 Document
* aDisplayDocument
);
510 nsClassHashtable
<nsURIHashKey
, ExternalResource
> mMap
;
511 nsRefPtrHashtable
<nsURIHashKey
, PendingLoad
> mPendingLoads
;
515 // The current status for a preload.
516 enum class SheetPreloadStatus
: uint8_t {
517 // There's no need to preload anything, the sheet is already in-memory.
519 // The load is in-progress. There's no guarantee that a load was started, it
520 // could be coalesced with other redundant loads.
522 // Something went wrong, and we errored out.
526 //----------------------------------------------------------------------
528 // Document interface. This is implemented by all document objects in
530 class Document
: public nsINode
,
531 public DocumentOrShadowRoot
,
532 public nsSupportsWeakReference
,
533 public nsIScriptObjectPrincipal
,
534 public SupportsWeakPtr
{
535 friend class DocumentOrShadowRoot
;
538 explicit Document(const char* aContentType
);
541 Document(const Document
&) = delete;
542 Document
& operator=(const Document
&) = delete;
545 using ExternalResourceLoad
= dom::ExternalResourceMap::ExternalResourceLoad
;
546 using ReferrerPolicyEnum
= dom::ReferrerPolicy
;
547 using AdoptedStyleSheetCloneCache
=
548 nsRefPtrHashtable
<nsPtrHashKey
<const StyleSheet
>, StyleSheet
>;
550 // nsINode overrides the new operator for DOM Arena allocation.
551 // to use the default one, we need to bring it back again
552 void* operator new(size_t aSize
) { return ::operator new(aSize
); }
555 * Called when XPCOM shutdown.
557 static void Shutdown();
559 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID
)
561 NS_DECL_ISUPPORTS_INHERITED
562 NS_IMETHOD_(void) DeleteCycleCollectable() override
;
564 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
566 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document
,
569 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
571 for (RefPtr obs : mObservers.ForwardRange()) { \
572 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
573 obs->func_ params_; \
576 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
578 if (PresShell* presShell = GetObservingPresShell()) { \
579 presShell->func_ params_; \
583 nsIPrincipal
* EffectiveCookiePrincipal() const;
585 nsIPrincipal
* EffectiveStoragePrincipal() const;
587 // nsIScriptObjectPrincipal
588 nsIPrincipal
* GetPrincipal() final
{ return NodePrincipal(); }
590 nsIPrincipal
* GetEffectiveCookiePrincipal() final
{
591 return EffectiveCookiePrincipal();
594 nsIPrincipal
* GetEffectiveStoragePrincipal() final
{
595 return EffectiveStoragePrincipal();
598 // You should probably not be using this function, since it performs no checks
599 // to ensure that the partitioned principal should really be used here. It is
600 // only designed to be used in very specific circumstances, such as when
601 // inheriting the document/storage principal.
602 nsIPrincipal
* PartitionedPrincipal() final
{ return mPartitionedPrincipal
; }
604 // Gets the appropriate principal to check the URI against a blocklist /
606 nsIPrincipal
* GetPrincipalForPrefBasedHacks() const;
608 void ClearActiveCookieAndStoragePrincipals() {
609 mActiveStoragePrincipal
= nullptr;
610 mActiveCookiePrincipal
= nullptr;
614 void GetEventTargetParent(EventChainPreVisitor
& aVisitor
) override
;
615 EventListenerManager
* GetOrCreateListenerManager() override
;
616 EventListenerManager
* GetExistingListenerManager() const override
;
618 // This helper class must be set when we dispatch beforeunload and unload
619 // events in order to avoid unterminate sync XHRs.
620 class MOZ_RAII PageUnloadingEventTimeStamp
{
621 RefPtr
<Document
> mDocument
;
625 explicit PageUnloadingEventTimeStamp(Document
* aDocument
)
626 : mDocument(aDocument
), mSet(false) {
627 MOZ_ASSERT(aDocument
);
628 if (mDocument
->mPageUnloadingEventTimeStamp
.IsNull()) {
629 mDocument
->SetPageUnloadingEventTimeStamp();
634 ~PageUnloadingEventTimeStamp() {
636 mDocument
->CleanUnloadEventsTimeStamp();
642 * Let the document know that we're starting to load data into it.
643 * @param aCommand The parser command. Must not be null.
644 * XXXbz It's odd to have that here.
645 * @param aChannel The channel the data will come from. The channel must be
646 * able to report its Content-Type.
647 * @param aLoadGroup The loadgroup this document should use from now on.
648 * Note that the document might not be the only thing using
650 * @param aContainer The container this document is in. This may be null.
651 * XXXbz maybe we should make it more explicit (eg make the
652 * container an nsIWebNavigation or nsIDocShell or
654 * @param [out] aDocListener the listener to pump data from the channel into.
655 * Generally this will be the parser this document
656 * sets up, or some sort of data-handler for media
658 * @param aReset whether the document should call Reset() on itself. If this
659 * is false, the document will NOT set its principal to the
660 * channel's owner, will not clear any event listeners that are
661 * already set on it, etc.
663 * Once this has been called, the document will return false for
664 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
665 * sure this happens is the responsibility of the caller of
666 * StartDocumentLoad().
668 * This function has an implementation, and does some setup, but does NOT set
669 * *aDocListener; this is the job of subclasses.
671 virtual nsresult
StartDocumentLoad(const char* aCommand
, nsIChannel
* aChannel
,
672 nsILoadGroup
* aLoadGroup
,
673 nsISupports
* aContainer
,
674 nsIStreamListener
** aDocListener
,
676 void StopDocumentLoad();
678 virtual void SetSuppressParserErrorElement(bool aSuppress
) {}
679 virtual bool SuppressParserErrorElement() { return false; }
681 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress
) {}
682 virtual bool SuppressParserErrorConsoleMessages() { return false; }
685 void InsertChildBefore(nsIContent
* aKid
, nsIContent
* aBeforeThis
,
686 bool aNotify
, ErrorResult
& aRv
) override
;
687 void RemoveChildNode(nsIContent
* aKid
, bool aNotify
) final
;
688 nsresult
Clone(dom::NodeInfo
* aNodeInfo
, nsINode
** aResult
) const override
{
689 return NS_ERROR_NOT_IMPLEMENTED
;
691 nsresult
CloneDocHelper(Document
* clone
) const;
693 Document
* GetLatestStaticClone() const { return mLatestStaticClone
; }
696 * Signal that the document title may have changed
697 * (see Document::GetTitle).
698 * @param aBoundTitleElement true if an HTML or SVG <title> element
699 * has just been bound to the document.
701 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement
);
704 * Return the URI for the document. May return null. If it ever stops being
705 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
706 * also never return null.
708 * The value returned corresponds to the "document's address" in
709 * HTML5. As such, it may change over the lifetime of the document, for
710 * instance as a result of the user navigating to a fragment identifier on
711 * the page, or as a result to a call to pushState() or replaceState().
713 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
715 nsIURI
* GetDocumentURI() const { return mDocumentURI
; }
718 * Return the original URI of the document. This is the same as the
719 * document's URI unless that has changed from its original value (for
720 * example, due to history.pushState() or replaceState() being invoked on the
723 * This method corresponds to the "creation URL" in HTML5 and, once set,
724 * doesn't change over the lifetime of the document.
726 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
728 nsIURI
* GetOriginalURI() const { return mOriginalURI
; }
731 * Return the base domain of the document. This has been computed using
732 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
733 * checks. When the URI of the document changes, this value is recomputed.
735 nsCString
GetBaseDomain() const { return mBaseDomain
; }
738 * Set the URI for the document. This also sets the document's original URI,
741 void SetDocumentURI(nsIURI
* aURI
);
744 * Set the URI for the document loaded via XHR, when accessed from
745 * chrome privileged script.
747 void SetChromeXHRDocURI(nsIURI
* aURI
) { mChromeXHRDocURI
= aURI
; }
750 * Set the base URI for the document loaded via XHR, when accessed from
751 * chrome privileged script.
753 void SetChromeXHRDocBaseURI(nsIURI
* aURI
) { mChromeXHRDocBaseURI
= aURI
; }
756 * The CSP in general is stored in the ClientInfo, but we also cache
757 * the CSP on the document so subresources loaded within a document
758 * can query that cached CSP instead of having to deserialize the CSP
761 * Please note that at the time of CSP parsing the Client is not
762 * available yet, hence we sync CSP of document and Client when the
763 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
765 nsIContentSecurityPolicy
* GetCsp() const;
766 void SetCsp(nsIContentSecurityPolicy
* aCSP
);
768 nsIContentSecurityPolicy
* GetPreloadCsp() const;
769 void SetPreloadCsp(nsIContentSecurityPolicy
* aPreloadCSP
);
771 void GetCspJSON(nsString
& aJSON
);
774 * Set referrer policy and upgrade-insecure-requests flags
776 void ApplySettingsFromCSP(bool aSpeculative
);
778 already_AddRefed
<nsIParser
> CreatorParserOrNull() {
779 nsCOMPtr
<nsIParser
> parser
= mParser
;
780 return parser
.forget();
784 * ReferrerInfo getter for Document.webidl.
786 nsIReferrerInfo
* ReferrerInfo() const { return GetReferrerInfo(); }
788 nsIReferrerInfo
* GetReferrerInfo() const { return mReferrerInfo
; }
790 nsIReferrerInfo
* GetPreloadReferrerInfo() const {
791 return mPreloadReferrerInfo
;
794 * Return the referrer policy of the document. Return "default" if there's no
795 * valid meta referrer tag found in the document.
796 * Referrer policy should be inherited from parent if the iframe is srcdoc
798 ReferrerPolicyEnum
GetReferrerPolicy() const;
801 * GetReferrerPolicy() for Document.webidl.
803 ReferrerPolicyEnum
ReferrerPolicy() const { return GetReferrerPolicy(); }
806 * If true, this flag indicates that all mixed content subresource
807 * loads for this document (and also embeded browsing contexts) will
810 bool GetBlockAllMixedContent(bool aPreload
) const {
812 return mBlockAllMixedContentPreloads
;
814 return mBlockAllMixedContent
;
818 * If true, this flag indicates that all subresource loads for this
819 * document need to be upgraded from http to https.
820 * This flag becomes true if the CSP of the document itself, or any
821 * of the document's ancestors up to the toplevel document makes use
822 * of the CSP directive 'upgrade-insecure-requests'.
824 bool GetUpgradeInsecureRequests(bool aPreload
) const {
826 return mUpgradeInsecurePreloads
;
828 return mUpgradeInsecureRequests
;
831 void SetReferrerInfo(nsIReferrerInfo
*);
834 * Referrer policy from <meta name="referrer" content=`policy`>
835 * will have higher priority than referrer policy from Referrer-Policy
836 * header. So override the old ReferrerInfo if we get one from meta
838 void UpdateReferrerInfoFromMeta(const nsAString
& aMetaReferrer
,
842 * Set the principals responsible for this document. Chances are, you do not
843 * want to be using this.
845 void SetPrincipals(nsIPrincipal
* aPrincipal
,
846 nsIPrincipal
* aPartitionedPrincipal
);
849 * Returns true if exempt from HTTPS-Only Mode upgrade.
851 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus
; }
854 * Return the LoadGroup for the document. May return null.
856 already_AddRefed
<nsILoadGroup
> GetDocumentLoadGroup() const {
857 nsCOMPtr
<nsILoadGroup
> group
= do_QueryReferent(mDocumentLoadGroup
);
858 return group
.forget();
862 * Return the fallback base URL for this document, as defined in the HTML
863 * specification. Note that this can return null if there is no document URI.
865 * XXXbz: This doesn't implement the bits for about:blank yet.
867 nsIURI
* GetFallbackBaseURI() const {
868 if (mIsSrcdocDocument
&& mParentDocument
) {
869 return mParentDocument
->GetDocBaseURI();
875 * Return the referrer from document URI as defined in the Referrer Policy
877 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
878 * While document is an iframe srcdoc document, let document be document's
879 * browsing context's browsing context container's node document.
880 * Then referrer should be document's URL
883 nsIURI
* GetDocumentURIAsReferrer() const {
884 if (mIsSrcdocDocument
&& mParentDocument
) {
885 return mParentDocument
->GetDocumentURIAsReferrer();
891 * Return the base URI for relative URIs in the document (the document uri
892 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
893 * returned URI could be null if there is no document URI. If the document is
894 * a srcdoc document and has no explicit base URL, return the parent
895 * document's base URL.
897 nsIURI
* GetDocBaseURI() const {
898 if (mDocumentBaseURI
) {
899 return mDocumentBaseURI
;
901 return GetFallbackBaseURI();
904 nsIURI
* GetBaseURI(bool aTryUseXHRDocBaseURI
= false) const final
;
906 void SetBaseURI(nsIURI
* aURI
);
909 * Resolves a URI based on the document's base URI.
911 Result
<OwningNonNull
<nsIURI
>, nsresult
> ResolveWithBaseURI(
912 const nsAString
& aURI
);
915 * Return the URL data which style system needs for resolving url value.
916 * This method attempts to use the cached object in mCachedURLData, but
917 * if the base URI, document URI, or principal has changed since last
918 * call to this function, or the function is called the first time for
919 * the document, a new one is created.
921 URLExtraData
* DefaultStyleAttrURLData();
922 nsIReferrerInfo
* ReferrerInfoForInternalCSSAndSVGResources();
925 * Get/Set the base target of a link in a document.
927 void GetBaseTarget(nsAString
& aBaseTarget
) const {
928 aBaseTarget
= mBaseTarget
;
931 void SetBaseTarget(const nsString
& aBaseTarget
) { mBaseTarget
= aBaseTarget
; }
934 * Return a standard name for the document's character set.
936 NotNull
<const Encoding
*> GetDocumentCharacterSet() const {
937 return mCharacterSet
;
941 * Set the document's character encoding.
943 void SetDocumentCharacterSet(NotNull
<const Encoding
*> aEncoding
);
945 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource
; }
947 // This method MUST be called before SetDocumentCharacterSet if
948 // you're planning to call both.
949 void SetDocumentCharacterSetSource(int32_t aCharsetSource
) {
950 mCharacterSetSource
= aCharsetSource
;
954 * Get the Content-Type of this document.
956 void GetContentType(nsAString
& aContentType
);
959 * Set the Content-Type of this document.
961 void SetContentType(const nsACString
& aContentType
);
964 * Return the language of this document.
966 void GetContentLanguage(nsAString
& aContentLanguage
) const {
967 CopyASCIItoUTF16(mContentLanguage
, aContentLanguage
);
970 // The states BidiEnabled and MathMLEnabled should persist across multiple
971 // views (screen, print) of the same document.
974 * Check if the document contains bidi data.
975 * If so, we have to apply the Unicode Bidi Algorithm.
977 bool GetBidiEnabled() const { return mBidiEnabled
; }
980 * Indicate the document contains bidi data.
981 * Currently, we cannot disable bidi, because once bidi is enabled,
982 * it affects a frame model irreversibly, and plays even though
983 * the document no longer contains bidi data.
985 void SetBidiEnabled() { mBidiEnabled
= true; }
987 void SetMathMLEnabled() { mMathMLEnabled
= true; }
990 * Ask this document whether it's the initial document in its window.
992 bool IsInitialDocument() const { return mIsInitialDocumentInWindow
; }
995 * Tell this document that it's the initial document in its window. See
996 * comments on mIsInitialDocumentInWindow for when this should be called.
998 void SetIsInitialDocument(bool aIsInitialDocument
);
1000 void SetLoadedAsData(bool aLoadedAsData
, bool aConsiderForMemoryReporting
);
1002 TimeStamp
GetLoadingOrRestoredFromBFCacheTimeStamp() const {
1003 return mLoadingOrRestoredFromBFCacheTimeStamp
;
1005 void SetLoadingOrRestoredFromBFCacheTimeStampToNow() {
1006 mLoadingOrRestoredFromBFCacheTimeStamp
= TimeStamp::Now();
1010 * Normally we assert if a runnable labeled with one DocGroup touches data
1011 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1012 * means that we can touch that document from any DocGroup without asserting.
1014 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches
= true; }
1017 * Get the bidi options for this document.
1018 * @see nsBidiUtils.h
1020 uint32_t GetBidiOptions() const { return mBidiOptions
; }
1023 * Set the bidi options for this document. This just sets the bits;
1024 * callers are expected to take action as needed if they want this
1025 * change to actually change anything immediately.
1026 * @see nsBidiUtils.h
1028 void SetBidiOptions(uint32_t aBidiOptions
) { mBidiOptions
= aBidiOptions
; }
1031 * Returns true if the document holds a CSP
1032 * delivered through an HTTP Header.
1034 bool GetHasCSPDeliveredThroughHeader() {
1035 return mHasCSPDeliveredThroughHeader
;
1039 * Return a promise which resolves to the content blocking events.
1041 using GetContentBlockingEventsPromise
= MozPromise
<uint32_t, bool, true>;
1042 [[nodiscard
]] RefPtr
<GetContentBlockingEventsPromise
>
1043 GetContentBlockingEvents();
1046 * Get the sandbox flags for this document.
1047 * @see nsSandboxFlags.h for the possible flags
1049 uint32_t GetSandboxFlags() const { return mSandboxFlags
; }
1051 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> GetEmbedderPolicy() const {
1052 return mEmbedderPolicy
;
1055 void SetEmbedderPolicy(
1056 const Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
>& aCOEP
) {
1057 mEmbedderPolicy
= aCOEP
;
1061 * Get string representation of sandbox flags (null if no flags are set)
1063 void GetSandboxFlagsAsString(nsAString
& aFlags
);
1066 * Set the sandbox flags for this document.
1067 * @see nsSandboxFlags.h for the possible flags
1069 void SetSandboxFlags(uint32_t sandboxFlags
) { mSandboxFlags
= sandboxFlags
; }
1072 * Called when the document was decoded as UTF-8 and decoder encountered no
1075 void EnableEncodingMenu() { mEncodingMenuDisabled
= false; }
1078 * Called to disable client access to cookies through the document.cookie API
1079 * from user JavaScript code.
1081 void DisableCookieAccess() { mDisableCookieAccess
= true; }
1083 void SetLinkHandlingEnabled(bool aValue
) { mLinksEnabled
= aValue
; }
1084 bool LinkHandlingEnabled() { return mLinksEnabled
; }
1087 * Set compatibility mode for this document
1089 void SetCompatibilityMode(nsCompatibility aMode
);
1092 * Called to disable client access to document.write() API from user
1095 void SetDocWriteDisabled(bool aDisabled
) { mDisableDocWrite
= aDisabled
; }
1098 * Whether a document.write() call is in progress.
1100 bool IsWriting() const { return mWriteLevel
!= uint32_t(0); }
1103 * Access HTTP header data (this may also get set from other
1104 * sources, like HTML META tags).
1106 void GetHeaderData(nsAtom
* aHeaderField
, nsAString
& aData
) const;
1107 void SetHeaderData(nsAtom
* aheaderField
, const nsAString
& aData
);
1110 * Set Early Hint data, moves the arrays into the function, leaving the
1111 * passed variables empty
1113 void SetEarlyHints(nsTArray
<net::EarlyHintConnectArgs
>&& aEarlyHints
);
1114 const nsTArray
<net::EarlyHintConnectArgs
>& GetEarlyHints() const {
1119 * Create a new presentation shell that will use aContext for its
1120 * presentation context (presentation contexts <b>must not</b> be
1121 * shared among multiple presentation shells). The caller of this
1122 * method is responsible for calling BeginObservingDocument() on the
1123 * presshell if the presshell should observe document mutations.
1125 MOZ_CAN_RUN_SCRIPT already_AddRefed
<PresShell
> CreatePresShell(
1126 nsPresContext
* aContext
, nsViewManager
* aViewManager
);
1127 void DeletePresShell();
1129 PresShell
* GetPresShell() const {
1130 return GetBFCacheEntry() ? nullptr : mPresShell
;
1133 inline PresShell
* GetObservingPresShell() const;
1135 // Return whether the presshell for this document is safe to flush.
1136 bool IsSafeToFlush() const;
1138 inline nsPresContext
* GetPresContext() const;
1140 bool HasShellOrBFCacheEntry() const { return mPresShell
|| mBFCacheEntry
; }
1142 // Instead using this method, what you probably want is
1143 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1144 void DisallowBFCaching(uint32_t aStatus
= BFCacheStatus::NOT_ALLOWED
);
1146 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed
; }
1148 // Accepts null to clear the BFCache entry too.
1149 void SetBFCacheEntry(nsIBFCacheEntry
* aEntry
);
1151 nsIBFCacheEntry
* GetBFCacheEntry() const { return mBFCacheEntry
; }
1153 // Removes this document from the BFCache, if it is cached, and returns
1155 bool RemoveFromBFCacheSync();
1158 * Return the parent document of this document. Will return null
1159 * unless this document is within a compound document and has a
1160 * parent. Note that this parent chain may cross chrome boundaries.
1162 Document
* GetInProcessParentDocument() const { return mParentDocument
; }
1165 * Set the parent document of this document.
1167 void SetParentDocument(Document
* aParent
) {
1168 mParentDocument
= aParent
;
1170 RecomputeResistFingerprinting();
1171 mIgnoreDocGroupMismatches
= aParent
->mIgnoreDocGroupMismatches
;
1172 if (!mIsDevToolsDocument
) {
1173 mIsDevToolsDocument
= mParentDocument
->IsDevToolsDocument();
1178 void SetCurrentContextPaint(const SVGContextPaint
* aContextPaint
) {
1179 mCurrentContextPaint
= aContextPaint
;
1182 const SVGContextPaint
* GetCurrentContextPaint() const {
1183 return mCurrentContextPaint
;
1187 * Are plugins allowed in this document ?
1189 bool GetAllowPlugins();
1192 * Set the sub document for aContent to aSubDoc.
1194 nsresult
SetSubDocumentFor(Element
* aContent
, Document
* aSubDoc
);
1197 * Get the sub document for aContent
1199 Document
* GetSubDocumentFor(nsIContent
* aContent
) const;
1202 * Get the content node for which this document is a sub document.
1204 Element
* GetEmbedderElement() const;
1207 * Return the doctype for this document.
1209 DocumentType
* GetDoctype() const;
1212 * Return the root element for this document.
1214 Element
* GetRootElement() const;
1216 Selection
* GetSelection(ErrorResult
& aRv
);
1218 void MakeBrowsingContextNonSynthetic();
1219 nsresult
HasStorageAccessSync(bool& aHasStorageAccess
);
1220 already_AddRefed
<Promise
> HasStorageAccess(ErrorResult
& aRv
);
1222 StorageAccessAPIHelper::PerformPermissionGrant
CreatePermissionGrantPromise(
1223 nsPIDOMWindowInner
* aInnerWindow
, nsIPrincipal
* aPrincipal
,
1224 bool aHasUserInteraction
, bool aRequireUserInteraction
,
1225 const Maybe
<nsCString
>& aTopLevelBaseDomain
, bool aFrameOnly
);
1227 already_AddRefed
<Promise
> RequestStorageAccess(ErrorResult
& aRv
);
1229 already_AddRefed
<Promise
> RequestStorageAccessForOrigin(
1230 const nsAString
& aThirdPartyOrigin
, const bool aRequireUserInteraction
,
1233 already_AddRefed
<Promise
> RequestStorageAccessUnderSite(
1234 const nsAString
& aSerializedSite
, ErrorResult
& aRv
);
1235 already_AddRefed
<Promise
> CompleteStorageAccessRequestFromSite(
1236 const nsAString
& aSerializedOrigin
, ErrorResult
& aRv
);
1238 bool UseRegularPrincipal() const;
1241 * Gets the event target to dispatch key events to if there is no focused
1242 * content in the document.
1244 virtual Element
* GetUnfocusedKeyEventTarget();
1247 * Retrieve information about the viewport as a data structure.
1248 * This will return information in the viewport META data section
1249 * of the document. This can be used in lieu of ProcessViewportInfo(),
1250 * which places the viewport information in the document header instead
1251 * of returning it directly.
1253 * @param aDisplaySize size of the on-screen display area for this
1254 * document, in device pixels.
1256 * NOTE: If the site is optimized for mobile (via the doctype), this
1257 * will return viewport information that specifies default information.
1259 nsViewportInfo
GetViewportInfo(const ScreenIntSize
& aDisplaySize
);
1261 void SetMetaViewportData(UniquePtr
<ViewportMetaData
> aData
);
1263 // Returns a ViewportMetaData for this document.
1264 ViewportMetaData
GetViewportMetaData() const;
1267 * True iff this doc will ignore manual character encoding overrides.
1269 virtual bool WillIgnoreCharsetOverride() { return true; }
1272 * Return whether the document was created by a srcdoc iframe.
1274 bool IsSrcdocDocument() const { return mIsSrcdocDocument
; }
1277 * Sets whether the document was created by a srcdoc iframe.
1279 void SetIsSrcdocDocument(bool aIsSrcdocDocument
) {
1280 mIsSrcdocDocument
= aIsSrcdocDocument
;
1284 * Gets the srcdoc string from within the channel (assuming both exist).
1285 * Returns a void string if this isn't a srcdoc document or if
1286 * the channel has not been set.
1288 nsresult
GetSrcdocData(nsAString
& aSrcdocData
);
1290 already_AddRefed
<AnonymousContent
> InsertAnonymousContent(bool aForce
,
1292 void RemoveAnonymousContent(AnonymousContent
&);
1294 * If aNode is a descendant of anonymous content inserted by
1295 * InsertAnonymousContent, this method returns the root element of the
1296 * inserted anonymous content (in other words, the clone of the aElement
1297 * that was passed to InsertAnonymousContent).
1299 Element
* GetAnonRootIfInAnonymousContentContainer(nsINode
* aNode
) const;
1300 nsTArray
<RefPtr
<AnonymousContent
>>& GetAnonymousContents() {
1301 return mAnonymousContents
;
1304 TimeStamp
GetPageUnloadingEventTimeStamp() const {
1305 if (!mParentDocument
) {
1306 return mPageUnloadingEventTimeStamp
;
1309 TimeStamp
parentTimeStamp(
1310 mParentDocument
->GetPageUnloadingEventTimeStamp());
1311 if (parentTimeStamp
.IsNull()) {
1312 return mPageUnloadingEventTimeStamp
;
1315 if (!mPageUnloadingEventTimeStamp
||
1316 parentTimeStamp
< mPageUnloadingEventTimeStamp
) {
1317 return parentTimeStamp
;
1320 return mPageUnloadingEventTimeStamp
;
1323 void NotifyLayerManagerRecreated();
1325 // Add an element to the list of elements that need their mapped attributes
1326 // resolved to a declaration block.
1328 // These are weak pointers, manually unschedule them when an element is
1329 // removed from the tree.
1330 void ScheduleForPresAttrEvaluation(Element
* aElement
);
1332 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1333 // generally when it's unbound from the tree.
1334 void UnscheduleForPresAttrEvaluation(Element
* aElement
);
1336 // Resolve all presentational attributes scheduled in
1337 // ScheduleForPresAttrEvaluation
1338 void ResolveScheduledPresAttrs() {
1339 if (mLazyPresElements
.IsEmpty()) {
1342 DoResolveScheduledPresAttrs();
1345 Maybe
<ClientInfo
> GetClientInfo() const;
1346 Maybe
<ClientState
> GetClientState() const;
1347 Maybe
<ServiceWorkerDescriptor
> GetController() const;
1349 // Returns the size of the mBlockedNodesByClassifier array.
1351 // This array contains nodes that have been blocked to prevent user tracking,
1352 // fingerprinting, cryptomining, etc. They most likely have had their
1353 // nsIChannel canceled by the URL classifier (Safebrowsing).
1355 // A script can subsequently use GetBlockedNodesByClassifier()
1356 // to get a list of references to these nodes.
1359 // This expresses how many tracking nodes have been blocked for this document
1360 // since its beginning, not how many of them are still around in the DOM tree.
1361 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1362 // array but they are not removed when those nodes are removed from the tree
1363 // or even garbage collected.
1364 long BlockedNodeByClassifierCount() const {
1365 return mBlockedNodesByClassifier
.Length();
1369 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1371 // This array contains nodes that have been blocked to prevent
1372 // user tracking. They most likely have had their nsIChannel
1373 // canceled by the URL classifier (Safebrowsing).
1375 already_AddRefed
<nsSimpleContentList
> BlockedNodesByClassifier() const;
1377 // Helper method that returns true if the document has storage-access sandbox
1379 bool StorageAccessSandboxed() const;
1381 // Helper method that returns true if storage access API is enabled and
1382 // the passed flag has storage-access sandbox flag.
1383 static bool StorageAccessSandboxed(uint32_t aSandboxFlags
);
1385 // Returns the cookie jar settings for this and sub contexts.
1386 nsICookieJarSettings
* CookieJarSettings();
1388 // Returns whether this document is using unpartitioned cookies
1389 bool UsingStorageAccess();
1391 // Returns whether the storage access permission of the document is granted by
1393 bool HasStorageAccessPermissionGrantedByAllowList();
1395 // Increments the document generation.
1396 inline void Changed() { ++mGeneration
; }
1398 // Returns the current generation.
1399 inline int32_t GetGeneration() const { return mGeneration
; }
1401 // Adds cached sizes values to aSizes if there's any
1402 // cached value and if the document generation hasn't
1403 // changed since the cache was created.
1404 // Returns true if sizes were added.
1405 bool GetCachedSizes(nsTabSizes
* aSizes
);
1407 // Sets the cache sizes for the current generation.
1408 void SetCachedSizes(nsTabSizes
* aSizes
);
1411 * Should be called when an element's editable changes as a result of
1412 * changing its contentEditable attribute/property.
1414 * The change should be +1 if the contentEditable attribute/property was
1415 * changed to true, -1 if it was changed to false.
1417 void ChangeContentEditableCount(Element
*, int32_t aChange
);
1418 MOZ_CAN_RUN_SCRIPT
void DeferredContentEditableCountChange(Element
*);
1420 enum class EditingState
: int8_t {
1429 * Returns the editing state of the document (not editable, contentEditable or
1432 EditingState
GetEditingState() const { return mEditingState
; }
1435 * Returns whether the document is editable.
1437 bool IsEditingOn() const {
1438 return GetEditingState() == EditingState::eDesignMode
||
1439 GetEditingState() == EditingState::eContentEditable
;
1442 class MOZ_STACK_CLASS nsAutoEditingState
{
1444 nsAutoEditingState(Document
* aDoc
, EditingState aState
)
1445 : mDoc(aDoc
), mSavedState(aDoc
->mEditingState
) {
1446 aDoc
->mEditingState
= aState
;
1448 ~nsAutoEditingState() { mDoc
->mEditingState
= mSavedState
; }
1451 RefPtr
<Document
> mDoc
;
1452 EditingState mSavedState
;
1454 friend class nsAutoEditingState
;
1457 * Set the editing state of the document. Don't use this if you want
1458 * to enable/disable editing, call EditingStateChanged() or
1461 void SetEditingState(EditingState aState
) { mEditingState
= aState
; }
1464 * Called when this Document's editor is destroyed.
1466 void TearingDownEditor();
1468 void SetKeyPressEventModel(uint16_t aKeyPressEventModel
);
1470 // Gets the next form number.
1472 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1473 // parser inserted form element.
1474 int32_t GetNextFormNumber() { return mNextFormNumber
++; }
1476 // Gets the next form control number.
1478 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1479 // parser inserted form control element.
1480 int32_t GetNextControlNumber() { return mNextControlNumber
++; }
1482 PreloadService
& Preloads() { return mPreloadService
; }
1484 bool HasThirdPartyChannel();
1486 bool ShouldIncludeInTelemetry(bool aAllowExtensionURIs
);
1488 void AddMediaElementWithMSE();
1489 void RemoveMediaElementWithMSE();
1491 void DoNotifyPossibleTitleChange();
1493 void InitFeaturePolicy();
1494 nsresult
InitFeaturePolicy(nsIChannel
* aChannel
);
1496 void EnsureNotEnteringAndExitFullscreen();
1499 friend class nsUnblockOnloadEvent
;
1501 nsresult
InitCSP(nsIChannel
* aChannel
);
1502 nsresult
InitCOEP(nsIChannel
* aChannel
);
1504 nsresult
InitReferrerInfo(nsIChannel
* aChannel
);
1506 void PostUnblockOnloadEvent();
1508 void DoUnblockOnload();
1510 void DoResolveScheduledPresAttrs();
1512 void RetrieveRelevantHeaders(nsIChannel
* aChannel
);
1514 void TryChannelCharset(nsIChannel
* aChannel
, int32_t& aCharsetSource
,
1515 NotNull
<const Encoding
*>& aEncoding
,
1516 nsHtml5TreeOpExecutor
* aExecutor
);
1518 MOZ_CAN_RUN_SCRIPT
void DispatchContentLoadedEvents();
1520 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1521 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void DispatchPageTransition(
1522 EventTarget
* aDispatchTarget
, const nsAString
& aType
, bool aInFrameSwap
,
1523 bool aPersisted
, bool aOnlySystemGroup
);
1525 // Call this before the document does something that will unbind all content.
1526 // That will stop us from doing a lot of work as each element is removed.
1527 void DestroyElementMaps();
1529 Element
* GetRootElementInternal() const;
1531 void SetPageUnloadingEventTimeStamp() {
1532 MOZ_ASSERT(!mPageUnloadingEventTimeStamp
);
1533 mPageUnloadingEventTimeStamp
= TimeStamp::NowLoRes();
1536 void CleanUnloadEventsTimeStamp() {
1537 MOZ_ASSERT(mPageUnloadingEventTimeStamp
);
1538 mPageUnloadingEventTimeStamp
= TimeStamp();
1542 * Clears any Servo element data stored on Elements in the document.
1544 void ClearStaleServoData();
1547 * Do the tree-disconnection that ResetToURI and document.open need to do.
1549 void DisconnectNodeTree();
1552 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1553 * "CheckKeyPressEventModel" event to check whether we should dispatch
1554 * keypress events in confluent model or split model. This should be
1555 * called only when mEditingState is changed to eDesignMode or
1556 * eConentEditable at first time.
1558 void MaybeDispatchCheckKeyPressEventModelEvent();
1560 /* Midas implementation */
1561 nsCommandManager
* GetMidasCommandManager();
1563 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
TurnEditingOff();
1565 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1566 // of places, and I'm pretty sure the exact ExecCommand call it
1567 // makes cannot actually run script.
1568 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
EditingStateChanged();
1570 void MaybeEditingStateChanged();
1573 // Get the root <html> element, or return null if there isn't one (e.g.
1574 // if the root isn't <html>)
1575 Element
* GetHtmlElement() const;
1576 // Returns the first child of GetHtmlContent which has the given tag,
1577 // or nullptr if that doesn't exist.
1578 Element
* GetHtmlChildElement(nsAtom
* aTag
);
1579 // Get the canonical <body> element, or return null if there isn't one (e.g.
1580 // if the root isn't <html> or if the <body> isn't there)
1581 HTMLBodyElement
* GetBodyElement();
1582 // Get the canonical <head> element, or return null if there isn't one (e.g.
1583 // if the root isn't <html> or if the <head> isn't there)
1584 Element
* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head
); }
1585 // Get the "body" in the sense of document.body: The first <body> or
1586 // <frameset> that's a child of a root <html>
1587 nsGenericHTMLElement
* GetBody();
1588 // Set the "body" in the sense of document.body.
1589 void SetBody(nsGenericHTMLElement
* aBody
, ErrorResult
& rv
);
1590 // Get the "head" element in the sense of document.head.
1591 HTMLSharedElement
* GetHead();
1593 ServoStyleSet
* StyleSetForPresShellOrMediaQueryEvaluation() const {
1594 return mStyleSet
.get();
1597 // ShadowRoot has APIs that can change styles. This notifies the shell that
1598 // stlyes applicable in the shadow tree have potentially changed.
1599 void RecordShadowStyleChange(ShadowRoot
&);
1601 // Needs to be called any time the applicable style can has changed, in order
1602 // to schedule a style flush and setup all the relevant state.
1604 // If we know the stylesheet change applies only to a shadow tree we can avoid
1605 // some work (like updating the font-face-set / counter-styles / etc, as those
1607 void ApplicableStylesChanged(bool aKnownInShadowTree
= false);
1609 // Whether we filled the style set with any style sheet. Only meant to be used
1610 // from DocumentOrShadowRoot::Traverse.
1611 bool StyleSetFilled() const { return mStyleSetFilled
; }
1614 * Accessors to the collection of stylesheets owned by this document.
1615 * Style sheets are ordered, most significant last.
1618 void InsertSheetAt(size_t aIndex
, StyleSheet
&);
1621 * Add a stylesheet to the document
1623 * TODO(emilio): This is only used by parts of editor that are no longer in
1624 * use by m-c or c-c, so remove.
1626 void AddStyleSheet(StyleSheet
* aSheet
) {
1628 InsertSheetAt(SheetCount(), *aSheet
);
1632 * Notify the document that the applicable state of the sheet changed
1633 * and that observers should be notified and style sets updated
1635 void StyleSheetApplicableStateChanged(StyleSheet
&);
1636 void PostStyleSheetApplicableStateChangeEvent(StyleSheet
&);
1637 void PostStyleSheetRemovedEvent(StyleSheet
&);
1639 enum additionalSheetType
{
1643 AdditionalSheetTypeCount
1646 nsresult
LoadAdditionalStyleSheet(additionalSheetType aType
,
1648 nsresult
AddAdditionalStyleSheet(additionalSheetType aType
,
1649 StyleSheet
* aSheet
);
1650 void RemoveAdditionalStyleSheet(additionalSheetType aType
, nsIURI
* sheetURI
);
1652 StyleSheet
* GetFirstAdditionalAuthorSheet() {
1653 return mAdditionalSheets
[eAuthorSheet
].SafeElementAt(0);
1657 * Returns the index that aSheet should be inserted at to maintain document
1660 size_t FindDocStyleSheetInsertionPoint(const StyleSheet
& aSheet
);
1663 * Get this document's CSSLoader. This is guaranteed to not return null.
1665 css::Loader
* CSSLoader() const { return mCSSLoader
; }
1668 * Get this document's StyleImageLoader. This is guaranteed to not return
1671 css::ImageLoader
* StyleImageLoader() const { return mStyleImageLoader
; }
1674 * Get the channel that was passed to StartDocumentLoad or Reset for this
1675 * document. Note that this may be null in some cases (eg if
1676 * StartDocumentLoad or Reset were never called)
1678 nsIChannel
* GetChannel() const { return mChannel
; }
1681 * Get this document's attribute stylesheet. May return null if
1684 AttributeStyles
* GetAttributeStyles() const { return mAttributeStyles
.get(); }
1686 virtual void SetScriptGlobalObject(nsIScriptGlobalObject
* aGlobalObject
);
1689 * Get/set the object from which the context for the event/script handling can
1690 * be got. Normally GetScriptHandlingObject() returns the same object as
1691 * GetScriptGlobalObject(), but if the document is loaded as data,
1692 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1693 * aHasHadScriptHandlingObject is set true if document has had the object
1694 * for event/script handling. Do not process any events/script if the method
1695 * returns null, but aHasHadScriptHandlingObject is true.
1697 nsIScriptGlobalObject
* GetScriptHandlingObject(
1698 bool& aHasHadScriptHandlingObject
) const {
1699 aHasHadScriptHandlingObject
= mHasHadScriptHandlingObject
;
1700 return mScriptGlobalObject
? mScriptGlobalObject
.get()
1701 : GetScriptHandlingObjectInternal();
1703 void SetScriptHandlingObject(nsIScriptGlobalObject
* aScriptObject
);
1706 * Get the object that is used as the scope for all of the content
1707 * wrappers whose owner document is this document. Unlike the script global
1708 * object, this will only return null when the global object for this
1709 * document is truly gone. Use this object when you're trying to find a
1710 * content wrapper in XPConnect.
1712 nsIGlobalObject
* GetScopeObject() const;
1713 void SetScopeObject(nsIGlobalObject
* aGlobal
);
1716 * Return the window containing the document (the outer window).
1718 nsPIDOMWindowOuter
* GetWindow() const {
1719 return mWindow
? mWindow
->GetOuterWindow() : GetWindowInternal();
1722 bool IsInBackgroundWindow() const {
1723 auto* outer
= mWindow
? mWindow
->GetOuterWindow() : nullptr;
1724 return outer
&& outer
->IsBackground();
1728 * Return the inner window used as the script compilation scope for
1729 * this document. If you're not absolutely sure you need this, use
1732 nsPIDOMWindowInner
* GetInnerWindow() const {
1733 return mRemovedFromDocShell
? nullptr : mWindow
;
1737 * Return the outer window ID.
1739 uint64_t OuterWindowID() const {
1740 nsPIDOMWindowOuter
* window
= GetWindow();
1741 return window
? window
->WindowID() : 0;
1745 * Return the inner window ID.
1747 uint64_t InnerWindowID() const {
1748 nsPIDOMWindowInner
* window
= GetInnerWindow();
1749 return window
? window
->WindowID() : 0;
1753 * Return WindowGlobalChild that is associated with the inner window.
1755 WindowGlobalChild
* GetWindowGlobalChild() {
1756 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1761 * Return WindowContext associated with the inner window.
1763 WindowContext
* GetWindowContext() const {
1764 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1767 bool IsTopLevelWindowInactive() const;
1770 * Get the script loader for this document
1772 dom::ScriptLoader
* ScriptLoader() { return mScriptLoader
; }
1775 * Add/Remove an element to the document's id and name hashes
1777 void AddToIdTable(Element
* aElement
, nsAtom
* aId
);
1778 void RemoveFromIdTable(Element
* aElement
, nsAtom
* aId
);
1779 void AddToNameTable(Element
* aElement
, nsAtom
* aName
);
1780 void RemoveFromNameTable(Element
* aElement
, nsAtom
* aName
);
1783 * Returns all elements in the top layer in the insertion order.
1785 nsTArray
<Element
*> GetTopLayer() const;
1787 bool TopLayerContains(Element
&) const;
1789 // Do the "fullscreen element ready check" from the fullscreen spec.
1790 // It returns true if the given element is allowed to go into fullscreen.
1791 // It is responsive to dispatch "fullscreenerror" event when necessary.
1792 bool FullscreenElementReadyCheck(FullscreenRequest
&);
1795 * When this is called on content process, this asynchronously requests that
1796 * the document make aElement the fullscreen element, and move into fullscreen
1797 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1798 * and it can be returned to fullscreen status by calling
1799 * RestorePreviousFullscreenState().
1800 * If on chrome process, this is synchronously.
1802 * Note that requesting fullscreen in a document also makes the element which
1803 * contains this document in this document's parent document fullscreen. i.e.
1804 * the <iframe> or <browser> that contains this document is also mode
1805 * fullscreen. This happens recursively in all ancestor documents.
1807 void RequestFullscreen(UniquePtr
<FullscreenRequest
> aRequest
,
1808 bool aApplyFullscreenDirectly
= false);
1811 void RequestFullscreenInContentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1812 bool aApplyFullscreenDirectly
);
1813 void RequestFullscreenInParentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1814 bool aApplyFullscreenDirectly
);
1816 // Pushes aElement onto the top layer
1817 void TopLayerPush(Element
&);
1819 // Removes the topmost element for which aPredicate returns true from the top
1820 // layer. The removed element, if any, is returned.
1821 Element
* TopLayerPop(FunctionRef
<bool(Element
*)> aPredicate
);
1823 // Removes the given element from the top layer. The removed element, if any,
1825 Element
* TopLayerPop(Element
&);
1827 MOZ_CAN_RUN_SCRIPT
bool TryAutoFocusCandidate(Element
& aElement
);
1830 // Removes all the elements with fullscreen flag set from the top layer, and
1831 // clears their fullscreen flag.
1832 void CleanupFullscreenState();
1834 // Pops the fullscreen element from the top layer and clears its
1835 // fullscreen flag. Returns whether there was any fullscreen element.
1836 enum class UpdateViewport
: bool { No
, Yes
};
1837 bool PopFullscreenElement(UpdateViewport
= UpdateViewport::Yes
);
1839 // Pushes the given element into the top of top layer and set fullscreen
1841 void SetFullscreenElement(Element
&);
1843 // Whether we has pending fullscreen request.
1844 bool HasPendingFullscreenRequests();
1847 * When Esc key is pressed, cancel the dialog element if the document is
1848 * blocked by the dialog or hide popover if popover is shown.
1850 MOZ_CAN_RUN_SCRIPT
void HandleEscKey();
1852 void AddModalDialog(HTMLDialogElement
&);
1853 void RemoveModalDialog(HTMLDialogElement
&);
1856 * Called when a frame in a child process has entered fullscreen or when a
1857 * fullscreen frame in a child process changes to another origin.
1858 * aFrameElement is the frame element which contains the child-process
1859 * fullscreen document.
1861 void RemoteFrameFullscreenChanged(Element
* aFrameElement
);
1864 * Called when a frame in a remote child document has rolled back fullscreen
1865 * so that all its top layer are empty; we must continue the
1866 * rollback in this parent process' doc tree branch which is fullscreen.
1867 * Note that only one branch of the document tree can have its documents in
1868 * fullscreen state at one time. We're in inconsistent state if a
1869 * fullscreen document has a parent and that parent isn't fullscreen. We
1870 * preserve this property across process boundaries.
1872 void RemoteFrameFullscreenReverted();
1875 * Restores the previous fullscreen element to fullscreen status. If there
1876 * is no former fullscreen element, this exits fullscreen, moving the
1877 * top-level browser window out of fullscreen mode.
1879 void RestorePreviousFullscreenState(UniquePtr
<FullscreenExit
>);
1882 * Returns true if this document is a fullscreen leaf document, i.e. it
1883 * is in fullscreen mode and has no fullscreen children.
1885 bool IsFullscreenLeaf();
1888 * Returns the document which is at the root of this document's branch
1889 * in the in-process document tree. Returns nullptr if the document isn't
1892 Document
* GetFullscreenRoot();
1894 size_t CountFullscreenElements() const;
1897 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1900 void SetFullscreenRoot(Document
* aRoot
);
1903 * Synchronously cleans up the fullscreen state on the given document.
1905 * Calling this without performing fullscreen transition could lead
1906 * to undesired effect (the transition happens after document state
1907 * flips), hence it should only be called either by nsGlobalWindow
1908 * when we have performed the transition, or when it is necessary to
1909 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1910 * should be called instead.
1912 * aDocument must not be null.
1914 static void ExitFullscreenInDocTree(Document
* aDocument
);
1917 * Ask the document to exit fullscreen state asynchronously.
1919 * Different from ExitFullscreenInDocTree(), this allows the window
1920 * to perform fullscreen transition first if any.
1922 * If aDocument is null, it will exit fullscreen from all documents
1925 static void AsyncExitFullscreen(Document
* aDocument
);
1928 * Handles any pending fullscreen in aDocument or its subdocuments.
1930 * Returns whether there is any fullscreen request handled.
1932 static bool HandlePendingFullscreenRequests(Document
* aDocument
);
1935 * Clear pending fullscreen in aDocument.
1937 static void ClearPendingFullscreenRequests(Document
* aDocument
);
1939 // ScreenOrientation related APIs
1941 void ClearOrientationPendingPromise();
1942 bool SetOrientationPendingPromise(Promise
* aPromise
);
1943 Promise
* GetOrientationPendingPromise() const {
1944 return mOrientationPendingPromise
;
1947 //----------------------------------------------------------------------
1949 // Document notification API's
1952 * Add a new observer of document change notifications. Whenever
1953 * content is changed, appended, inserted or removed the observers are
1954 * informed. An observer that is already observing the document must
1955 * not be added without being removed first.
1957 void AddObserver(nsIDocumentObserver
* aObserver
);
1960 * Remove an observer of document change notifications. This will
1961 * return false if the observer cannot be found.
1963 bool RemoveObserver(nsIDocumentObserver
* aObserver
);
1965 // Observation hooks used to propagate notifications to document observers.
1966 // BeginUpdate must be called before any batch of modifications of the
1967 // content model or of style data, EndUpdate must be called afterward.
1968 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1971 uint32_t UpdateNestingLevel() { return mUpdateNestLevel
; }
1974 virtual void EndLoad();
1977 READYSTATE_UNINITIALIZED
= 0,
1978 READYSTATE_LOADING
= 1,
1979 READYSTATE_INTERACTIVE
= 3,
1980 READYSTATE_COMPLETE
= 4
1982 // Set the readystate of the document. If aUpdateTimingInformation is true,
1983 // this will record relevant timestamps in the document's performance timing.
1984 // Some consumers (document.open is the only one right now, actually) don't
1985 // want to do that, though.
1986 void SetReadyStateInternal(ReadyState
, bool aUpdateTimingInformation
= true);
1987 ReadyState
GetReadyStateEnum() { return mReadyState
; }
1989 void NotifyLoading(bool aNewParentIsLoading
, const ReadyState
& aCurrentState
,
1990 ReadyState aNewState
);
1992 void NotifyAbortedLoad();
1994 // Notify that an element changed state. This must happen under a
1995 // scriptblocker but NOT within a begin/end update.
1996 void ElementStateChanged(Element
*, ElementState
);
1998 // Update a set of document states that may have changed.
1999 // This should only be called by callers whose state is also reflected in the
2000 // implementation of Document::GetDocumentState.
2002 // aNotify controls whether we notify our DocumentStatesChanged observers.
2003 void UpdateDocumentStates(DocumentState aMaybeChangedStates
, bool aNotify
);
2005 void ResetDocumentDirection();
2007 // Observation hooks for style data to propagate notifications
2008 // to document observers
2009 void RuleChanged(StyleSheet
&, css::Rule
*, StyleRuleChangeKind
);
2010 void RuleAdded(StyleSheet
&, css::Rule
&);
2011 void RuleRemoved(StyleSheet
&, css::Rule
&);
2012 void SheetCloned(StyleSheet
&) {}
2013 void ImportRuleLoaded(CSSImportRule
&, StyleSheet
&);
2016 * Flush notifications for this document and its parent documents
2017 * (since those may affect the layout of this one).
2019 void FlushPendingNotifications(FlushType aType
);
2022 * Another variant of the above FlushPendingNotifications. This function
2023 * takes a ChangesToFlush to specify whether throttled animations are flushed
2025 * If in doubt, use the above FlushPendingNotifications.
2027 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2028 void FlushPendingNotifications(ChangesToFlush aFlush
);
2031 * Calls FlushPendingNotifications on any external resources this document
2032 * has. If this document has no external resources or is an external resource
2033 * itself this does nothing. This should only be called with
2034 * aType >= FlushType::Style.
2036 void FlushExternalResources(FlushType aType
);
2038 void AddWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2039 void RemoveWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2041 // Triggers an update of <svg:use> element shadow trees.
2042 void UpdateSVGUseElementShadowTrees() {
2043 if (mSVGUseElementsNeedingShadowTreeUpdate
.IsEmpty()) {
2046 DoUpdateSVGUseElementShadowTrees();
2050 * Only to be used inside Gecko, you can't really do anything with the
2051 * pointer outside Gecko anyway.
2053 nsNodeInfoManager
* NodeInfoManager() const { return mNodeInfoManager
; }
2056 * Reset the document using the given channel and loadgroup. This works
2057 * like ResetToURI, but also sets the document's channel to aChannel.
2058 * The principal of the document will be set from the channel.
2060 virtual void Reset(nsIChannel
* aChannel
, nsILoadGroup
* aLoadGroup
);
2063 * Reset this document to aURI, aLoadGroup, aPrincipal and
2064 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2065 * content principal based on aURI will be used.
2067 virtual void ResetToURI(nsIURI
* aURI
, nsILoadGroup
* aLoadGroup
,
2068 nsIPrincipal
* aPrincipal
,
2069 nsIPrincipal
* aPartitionedPrincipal
);
2072 * Set the container (docshell) for this document. Virtual so that
2073 * docshell can call it.
2075 virtual void SetContainer(nsDocShell
* aContainer
);
2078 * Get the container (docshell) for this document.
2080 nsISupports
* GetContainer() const;
2083 * Get the container's load context for this document.
2085 nsILoadContext
* GetLoadContext() const;
2088 * Get docshell the for this document.
2090 nsIDocShell
* GetDocShell() const;
2093 * Set and get XML declaration. If aVersion is null there is no declaration.
2094 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2095 * was no standalone parameter in the declaration, that it was given as no,
2096 * or that it was given as yes.
2098 void SetXMLDeclaration(const char16_t
* aVersion
, const char16_t
* aEncoding
,
2099 const int32_t aStandalone
);
2100 void GetXMLDeclaration(nsAString
& aVersion
, nsAString
& aEncoding
,
2101 nsAString
& Standalone
);
2104 * Returns the bits for the color-scheme specified by the
2105 * <meta name="color-scheme">.
2107 uint8_t GetColorSchemeBits() const { return mColorSchemeBits
; }
2110 * Traverses the DOM and computes the supported color schemes as per
2111 * https://html.spec.whatwg.org/#meta-color-scheme
2113 void RecomputeColorScheme();
2114 void AddColorSchemeMeta(HTMLMetaElement
&);
2115 void RemoveColorSchemeMeta(HTMLMetaElement
&);
2118 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2119 * regular HTML document with Content-Type "text/html", image documents and
2120 * media documents). Returns false for XHTML and any other documents parsed
2121 * by the XML parser.
2123 bool IsHTMLDocument() const { return mType
== eHTML
; }
2124 bool IsHTMLOrXHTML() const { return mType
== eHTML
|| mType
== eXHTML
; }
2125 bool IsImageDocument() const {
2126 return MediaDocumentKind() == MediaDocumentKind::Image
;
2128 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2129 bool IsSVGDocument() const { return mType
== eSVG
; }
2130 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2131 bool LoadsFullXULStyleSheetUpFront() {
2132 if (IsSVGDocument()) {
2135 return AllowXULXBL();
2138 bool IsScriptEnabled() const;
2141 * Returns true if this document was created from a nsXULPrototypeDocument.
2143 bool LoadedFromPrototype() const { return mPrototypeDocument
; }
2145 * Returns the prototype the document was created from, or null if it was not
2146 * created from a prototype.
2148 nsXULPrototypeDocument
* GetPrototype() const { return mPrototypeDocument
; }
2150 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument
; }
2151 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument
) {
2152 mIsTopLevelContentDocument
= aIsTopLevelContentDocument
;
2155 bool IsContentDocument() const { return mIsContentDocument
; }
2156 void SetIsContentDocument(bool aIsContentDocument
) {
2157 mIsContentDocument
= aIsContentDocument
;
2160 void ProcessMETATag(HTMLMetaElement
* aMetaElement
);
2162 * Create an element with the specified name, prefix and namespace ID.
2163 * Returns null if element name parsing failed.
2165 already_AddRefed
<Element
> CreateElem(const nsAString
& aName
, nsAtom
* aPrefix
,
2166 int32_t aNamespaceID
,
2167 const nsAString
* aIs
= nullptr);
2170 * Get the security info (i.e. SSL state etc) that the document got
2171 * from the channel/document that created the content of the
2176 nsITransportSecurityInfo
* GetSecurityInfo() { return mSecurityInfo
; }
2179 * Get the channel that failed to load and resulted in an error page, if it
2180 * exists. This is only relevant to error pages.
2182 nsIChannel
* GetFailedChannel() const { return mFailedChannel
; }
2185 * This function checks if the document that is trying to access
2186 * GetNetErrorInfo is a trusted about net error page or not.
2188 static bool CallerIsTrustedAboutNetError(JSContext
* aCx
, JSObject
* aObject
);
2191 * This function checks if the document that is trying to access
2192 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2194 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext
* aCx
,
2198 * Get security info like error code for a failed channel. This
2199 * property is only exposed to about:neterror documents.
2201 void GetNetErrorInfo(mozilla::dom::NetErrorInfo
& aInfo
, ErrorResult
& aRv
);
2204 * This function checks if the document that is trying to access
2205 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2207 static bool CallerIsTrustedAboutCertError(JSContext
* aCx
, JSObject
* aObject
);
2210 * This function checks if the privilege storage access api is available for
2211 * the caller. We only allow privilege SSA to be called by system principal
2212 * and webcompat extension.
2214 static bool CallerCanAccessPrivilegeSSA(JSContext
* aCx
, JSObject
* aObject
);
2217 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2218 * failed Channel. This property is only exposed for about:certerror
2221 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo
& aInfo
,
2225 * Set the channel that failed to load and resulted in an error page.
2226 * This is only relevant to error pages.
2228 void SetFailedChannel(nsIChannel
* aChannel
) { mFailedChannel
= aChannel
; }
2231 * Returns the default namespace ID used for elements created in this
2234 int32_t GetDefaultNamespaceID() const { return mDefaultElementType
; }
2236 void RemoveAllProperties();
2237 void RemoveAllPropertiesFor(nsINode
* aNode
);
2239 nsPropertyTable
& PropertyTable() { return mPropertyTable
; }
2242 * Sets the ID used to identify this part of the multipart document
2244 void SetPartID(uint32_t aID
) { mPartID
= aID
; }
2247 * Return the ID used to identify this part of the multipart document
2249 uint32_t GetPartID() const { return mPartID
; }
2252 * Sanitize the document by resetting all input elements and forms that have
2253 * autocomplete=off to their default values.
2254 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2256 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Sanitize();
2259 * Enumerate all subdocuments.
2260 * The enumerator callback should return CallState::Continue to continue
2261 * enumerating, or CallState::Stop to stop. This will never get passed a null
2264 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
2265 void EnumerateSubDocuments(SubDocEnumFunc aCallback
);
2268 * Collect all the descendant documents for which |aCalback| returns true.
2269 * The callback function must not mutate any state for the given document.
2271 using nsDocTestFunc
= bool (*)(const Document
* aDocument
);
2272 void CollectDescendantDocuments(nsTArray
<RefPtr
<Document
>>& aDescendants
,
2273 nsDocTestFunc aCallback
) const;
2276 * Check whether it is safe to cache the presentation of this document
2277 * and all of its subdocuments (depending on the 3rd param). This method
2278 * checks the following conditions recursively:
2279 * - Some document types, such as plugin documents, cannot be safely cached.
2280 * - If there are any pending requests, we don't allow the presentation
2281 * to be cached. Ideally these requests would be suspended and resumed,
2282 * but that is difficult in some cases, such as XMLHttpRequest.
2283 * - If there are any beforeunload or unload listeners, we must fire them
2284 * for correctness, but this likely puts the document into a state where
2285 * it would not function correctly if restored.
2287 * |aNewRequest| should be the request for a new document which will
2288 * replace this document in the docshell. The new document's request
2289 * will be ignored when checking for active requests. If there is no
2290 * request associated with the new document, this parameter may be null.
2292 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2293 * combination is when we try to BFCache aNewRequest
2295 virtual bool CanSavePresentation(nsIRequest
* aNewRequest
,
2296 uint32_t& aBFCacheCombo
,
2297 bool aIncludeSubdocuments
,
2298 bool aAllowUnloadListeners
= true);
2301 * Pass principals if the correct ones are known when calling Init. That way
2302 * NodeInfoManager doesn't need to create a temporary null principal.
2304 virtual nsresult
Init(nsIPrincipal
* aPrincipal
,
2305 nsIPrincipal
* aPartitionedPrincipal
);
2308 * Notify the document that its associated ContentViewer is being destroyed.
2309 * This releases circular references so that the document can go away.
2310 * Destroy() is only called on documents that have a content viewer.
2312 virtual void Destroy();
2315 * Notify the document that its associated ContentViewer is no longer
2316 * the current viewer for the docshell. The document might still
2317 * be rendered in "zombie state" until the next document is ready.
2318 * The document should save form control state.
2320 void RemovedFromDocShell();
2323 * Get the layout history state that should be used to save and restore state
2324 * for nodes in this document. This may return null; if that happens state
2325 * saving and restoration is not possible.
2327 already_AddRefed
<nsILayoutHistoryState
> GetLayoutHistoryState() const;
2330 * Methods that can be used to prevent onload firing while an event that
2331 * should block onload is posted. onload is guaranteed to not fire until
2332 * either all calls to BlockOnload() have been matched by calls to
2333 * UnblockOnload() or the load has been stopped altogether (by the user
2334 * pressing the Stop button, say).
2338 * @param aFireSync whether to fire onload synchronously. If false,
2339 * onload will fire asynchronously after all onload blocks have been
2340 * removed. It will NOT fire from inside UnblockOnload. If true,
2341 * onload may fire from inside UnblockOnload.
2343 void UnblockOnload(bool aFireSync
);
2345 // Only BlockOnload should call this!
2346 void AsyncBlockOnload();
2348 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded
; }
2350 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnblockDOMContentLoaded();
2353 * Notification that the page has been shown, for documents which are loaded
2354 * into a DOM window. This corresponds to the completion of document load,
2355 * or to the page's presentation being restored into an existing DOM window.
2356 * This notification fires applicable DOM events to the content window. See
2357 * PageTransitionEvent.webidl for a description of the |aPersisted|
2358 * parameter. If aDispatchStartTarget is null, the pageshow event is
2359 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2360 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2361 * event is only dispatched to listeners in the system group.
2362 * Note: if aDispatchStartTarget isn't null, the showing state of the
2363 * document won't be altered.
2365 virtual void OnPageShow(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2366 bool aOnlySystemGroup
= false);
2369 * Notification that the page has been hidden, for documents which are loaded
2370 * into a DOM window. This corresponds to the unloading of the document, or
2371 * to the document's presentation being saved but removed from an existing
2372 * DOM window. This notification fires applicable DOM events to the content
2373 * window. See PageTransitionEvent.webidl for a description of the
2374 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2375 * event is dispatched on the ScriptGlobalObject for this document,
2376 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2377 * true, the event is only dispatched to listeners in the system group.
2378 * Note: if aDispatchStartTarget isn't null, the showing state of the
2379 * document won't be altered.
2381 void OnPageHide(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2382 bool aOnlySystemGroup
= false);
2385 * We record the set of links in the document that are relevant to
2389 * Notification that an element is a link that is relevant to style.
2391 void AddStyleRelevantLink(Link
* aLink
) {
2392 NS_ASSERTION(aLink
, "Passing in a null link. Expect crashes RSN!");
2394 NS_ASSERTION(!mStyledLinks
.Contains(aLink
),
2395 "Document already knows about this Link!");
2396 mStyledLinksCleared
= false;
2398 mStyledLinks
.Insert(aLink
);
2402 * Notification that an element is a link and its URI might have been
2403 * changed or the element removed. If the element is still a link relevant
2404 * to style, then someone must ensure that AddStyleRelevantLink is
2405 * (eventually) called on it again.
2407 void ForgetLink(Link
* aLink
) {
2408 MOZ_ASSERT(aLink
, "Passing in a null link. Expect crashes RSN!");
2409 MOZ_ASSERT(mStyledLinks
.Contains(aLink
) || mStyledLinksCleared
,
2410 "Document knows nothing about this Link!");
2411 mStyledLinks
.Remove(aLink
);
2414 // Refreshes the hrefs of all the links in the document.
2415 void RefreshLinkHrefs();
2418 * Support for window.matchMedia()
2421 already_AddRefed
<MediaQueryList
> MatchMedia(const nsACString
& aMediaQueryList
,
2422 CallerType aCallerType
);
2424 LinkedList
<MediaQueryList
>& MediaQueryLists() { return mDOMMediaQueryLists
; }
2427 * Get the compatibility mode for this document
2429 nsCompatibility
GetCompatibilityMode() const { return mCompatMode
; }
2432 * Check whether we've ever fired a DOMTitleChanged event for this
2435 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange
; }
2438 * To batch DOMSubtreeModified, document needs to be informed when
2439 * a mutation event might be dispatched, even if the event isn't actually
2440 * created because there are no listeners for it.
2442 * @param aTarget is the target for the mutation event.
2444 void MayDispatchMutationEvent(nsINode
* aTarget
) {
2445 if (mSubtreeModifiedDepth
> 0) {
2446 mSubtreeModifiedTargets
.AppendObject(aTarget
);
2451 * Marks as not-going-to-be-collected for the given generation of
2454 void MarkUncollectableForCCGeneration(uint32_t aGeneration
) {
2455 mMarkedCCGeneration
= aGeneration
;
2459 * Gets the cycle collector generation this document is marked for.
2461 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration
; }
2464 * Returns whether this document is cookie averse. See
2465 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2467 bool IsCookieAverse() const {
2468 // If we are a document that "has no browsing context."
2469 if (!GetInnerWindow()) {
2473 // If we are a document "whose URL's scheme is not a network scheme."
2474 // NB: Explicitly allow file: URIs to store cookies.
2476 return !NodePrincipal()->SchemeIs("http") &&
2477 !NodePrincipal()->SchemeIs("https") &&
2478 !NodePrincipal()->SchemeIs("file");
2481 bool IsLoadedAsData() { return mLoadedAsData
; }
2483 void SetAddedToMemoryReportAsDataDocument() {
2484 mAddedToMemoryReportingAsDataDocument
= true;
2487 void UnregisterFromMemoryReportingForDataDocument();
2489 bool MayStartLayout() { return mMayStartLayout
; }
2491 void SetMayStartLayout(bool aMayStartLayout
);
2493 already_AddRefed
<nsIDocumentEncoder
> GetCachedEncoder();
2495 void SetCachedEncoder(already_AddRefed
<nsIDocumentEncoder
> aEncoder
);
2497 // In case of failure, the document really can't initialize the frame loader.
2498 nsresult
InitializeFrameLoader(nsFrameLoader
* aLoader
);
2499 // In case of failure, the caller must handle the error, for example by
2500 // finalizing frame loader asynchronously.
2501 nsresult
FinalizeFrameLoader(nsFrameLoader
* aLoader
, nsIRunnable
* aFinalizer
);
2502 // Removes the frame loader of aShell from the initialization list.
2503 void TryCancelFrameLoaderInitialization(nsIDocShell
* aShell
);
2506 * Check whether this document is a root document that is not an
2507 * external resource.
2509 bool IsRootDisplayDocument() const {
2510 return !mParentDocument
&& !mDisplayDocument
;
2513 bool ChromeRulesEnabled() const { return mChromeRulesEnabled
; }
2515 bool IsInChromeDocShell() const {
2516 const Document
* root
= this;
2517 while (const Document
* displayDoc
= root
->GetDisplayDocument()) {
2520 return root
->mInChromeDocShell
;
2523 bool IsDevToolsDocument() const { return mIsDevToolsDocument
; }
2525 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage
; }
2527 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage
= true; }
2529 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument
; }
2531 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument
= true; }
2533 bool IsResourceDoc() const {
2534 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2535 mHasDisplayDocument
; // Are we an external resource doc?
2539 * Get the document for which this document is an external resource. This
2540 * will be null if this document is not an external resource. Otherwise,
2541 * GetDisplayDocument() will return a non-null document, and
2542 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2544 Document
* GetDisplayDocument() const { return mDisplayDocument
; }
2547 * Set the display document for this document. aDisplayDocument must not be
2550 void SetDisplayDocument(Document
* aDisplayDocument
) {
2551 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2552 "Shouldn't set mDisplayDocument on documents that already "
2553 "have a presentation or a docshell or a window");
2554 MOZ_ASSERT(aDisplayDocument
, "Must not be null");
2555 MOZ_ASSERT(aDisplayDocument
!= this, "Should be different document");
2556 MOZ_ASSERT(!aDisplayDocument
->GetDisplayDocument(),
2557 "Display documents should not nest");
2558 mDisplayDocument
= aDisplayDocument
;
2559 mHasDisplayDocument
= !!aDisplayDocument
;
2563 * Request an external resource document for aURI. This will return the
2564 * resource document if available. If one is not available yet, it will
2565 * start loading as needed, and the pending load object will be returned in
2566 * aPendingLoad so that the caller can register an observer to wait for the
2567 * load. If this function returns null and doesn't return a pending load,
2568 * that means that there is no resource document for this URI and won't be
2569 * one in the future.
2571 * @param aURI the URI to get
2572 * @param aReferrerInfo the referrerInfo of the request
2573 * @param aRequestingNode the node making the request
2574 * @param aPendingLoad the pending load for this request, if any
2576 Document
* RequestExternalResource(nsIURI
* aURI
,
2577 nsIReferrerInfo
* aReferrerInfo
,
2578 nsINode
* aRequestingNode
,
2579 ExternalResourceLoad
** aPendingLoad
);
2582 * Enumerate the external resource documents associated with this document.
2583 * The enumerator callback should return CallState::Continue to continue
2584 * enumerating, or CallState::Stop to stop. This callback will never get
2585 * passed a null aDocument.
2587 void EnumerateExternalResources(SubDocEnumFunc aCallback
);
2589 dom::ExternalResourceMap
& ExternalResourceMap() {
2590 return mExternalResourceMap
;
2594 * Return whether the document is currently showing (in the sense of
2595 * OnPageShow() having been called already and OnPageHide() not having been
2598 bool IsShowing() const { return mIsShowing
; }
2600 * Return whether the document is currently visible (in the sense of
2601 * OnPageHide having been called and OnPageShow not yet having been called)
2603 bool IsVisible() const { return mVisible
; }
2605 void SetSuppressedEventListener(EventListener
* aListener
);
2607 EventListener
* GetSuppressedEventListener() {
2608 return mSuppressedEventListener
;
2612 * Return true when this document is active, i.e., an active document
2613 * in a content viewer and not in the bfcache.
2614 * This does NOT match the "active document" concept in the WHATWG spec -
2615 * see IsCurrentActiveDocument.
2617 bool IsActive() const;
2620 * Return true if this is the current active document for its
2621 * docshell. Note that a docshell may have multiple active documents
2622 * due to the bfcache -- this should be used when you need to
2623 * differentiate the *current* active document from any active
2626 bool IsCurrentActiveDocument() const {
2627 nsPIDOMWindowInner
* inner
= GetInnerWindow();
2628 return inner
&& inner
->IsCurrentInnerWindow() && inner
->GetDoc() == this;
2632 * Returns whether this document should perform image loads.
2634 bool ShouldLoadImages() const {
2635 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2636 // images can themselves have data: URL image references.
2637 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2641 void SetHasPrintCallbacks() {
2642 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2643 mHasPrintCallbacks
= true;
2646 bool HasPrintCallbacks() const { return mHasPrintCallbacks
; }
2649 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2650 * the document's activity changes such as OnPageHide, visibility, activity.
2651 * The ActivityObserver objects can be nsIObjectLoadingContent or
2652 * nsIDocumentActivity or HTMLMEdiaElement.
2654 void RegisterActivityObserver(nsISupports
* aSupports
);
2655 bool UnregisterActivityObserver(nsISupports
* aSupports
);
2656 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2657 using ActivityObserverEnumerator
= FunctionRef
<void(nsISupports
*)>;
2658 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator
);
2660 void NotifyActivityChanged();
2662 // Indicates whether mAnimationController has been (lazily) initialized.
2663 // If this returns true, we're promising that GetAnimationController()
2664 // will have a non-null return value.
2665 bool HasAnimationController() { return !!mAnimationController
; }
2667 // Getter for this document's SMIL Animation Controller. Performs lazy
2668 // initialization, if this document supports animation and if
2669 // mAnimationController isn't yet initialized.
2671 // If HasAnimationController is true, this is guaranteed to return non-null.
2672 SMILAnimationController
* GetAnimationController();
2674 // Gets the tracker for animations that are waiting to start.
2675 // Returns nullptr if there is no pending animation tracker for this document
2676 // which will be the case if there have never been any CSS animations or
2677 // transitions on elements in the document.
2678 PendingAnimationTracker
* GetPendingAnimationTracker() {
2679 return mPendingAnimationTracker
;
2682 // Gets the tracker for animations that are waiting to start and
2683 // creates it if it doesn't already exist. As a result, the return value
2684 // will never be nullptr.
2685 PendingAnimationTracker
* GetOrCreatePendingAnimationTracker();
2687 // Gets the tracker for scroll-driven animations that are waiting to start.
2688 // Returns nullptr if there is no scroll-driven animation tracker for this
2689 // document which will be the case if there have never been any scroll-driven
2690 // animations in the document.
2691 ScrollTimelineAnimationTracker
* GetScrollTimelineAnimationTracker() {
2692 return mScrollTimelineAnimationTracker
;
2695 // Gets the tracker for scroll-driven animations that are waiting to start and
2696 // creates it if it doesn't already exist. As a result, the return value
2697 // will never be nullptr.
2698 ScrollTimelineAnimationTracker
* GetOrCreateScrollTimelineAnimationTracker();
2701 * Prevents user initiated events from being dispatched to the document and
2704 void SuppressEventHandling(uint32_t aIncrease
= 1);
2707 * Unsuppress event handling.
2708 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2711 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnsuppressEventHandlingAndFireEvents(
2714 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed
; }
2716 bool IsEventHandlingEnabled() const {
2717 return !EventHandlingSuppressed() && mScriptGlobalObject
;
2720 bool WouldScheduleFrameRequestCallbacks() const {
2721 // If this function changes to depend on some other variable, make sure to
2722 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2723 // where that variable can change.
2724 return mPresShell
&& IsEventHandlingEnabled();
2727 void DecreaseEventSuppression() {
2728 MOZ_ASSERT(mEventsSuppressed
);
2729 --mEventsSuppressed
;
2730 UpdateFrameRequestCallbackSchedulingState();
2734 * Some clipboard commands are unconditionally enabled on some documents, so
2735 * as to always dispatch copy / paste events even though you'd normally not be
2738 bool AreClipboardCommandsUnconditionallyEnabled() const;
2741 * Note a ChannelEventQueue which has been suspended on the document's behalf
2742 * to prevent XHRs from running content scripts while event handling is
2743 * suppressed. The document is responsible for resuming the queue after
2744 * event handling is unsuppressed.
2746 void AddSuspendedChannelEventQueue(net::ChannelEventQueue
* aQueue
);
2749 * Returns true if a postMessage event should be suspended instead of running.
2750 * The document is responsible for running the event later, in the order they
2753 bool SuspendPostMessageEvent(PostMessageEvent
* aEvent
);
2756 * Run any suspended postMessage events, or clear them.
2758 void FireOrClearPostMessageEvents(bool aFireEvents
);
2760 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent
= true; }
2763 * Flag whether we're about to fire the window's load event for this document.
2765 void SetLoadEventFiring(bool aFiring
) { mLoadEventFiring
= aFiring
; }
2768 * Test whether we should be firing a load event for this document after a
2769 * document.close(). This is public and on Document, instead of being private
2770 * to Document, because we need to go through the normal docloader logic
2771 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2772 * semantics of firing the load event; we just don't want to fire the load
2773 * event if this tests true. So we need the docloader to be able to access
2776 * This method should only be called at the point when the load event is about
2777 * to be fired. It resets the "skip" flag, so it is not idempotent.
2779 bool SkipLoadEventAfterClose() {
2780 bool skip
= mSkipLoadEventAfterClose
;
2781 mSkipLoadEventAfterClose
= false;
2786 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2788 void IncrementIgnoreDestructiveWritesCounter() {
2789 ++mIgnoreDestructiveWritesCounter
;
2793 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2795 void DecrementIgnoreDestructiveWritesCounter() {
2796 --mIgnoreDestructiveWritesCounter
;
2799 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch
; }
2802 * Returns true if this document is allowed to contain XUL element and
2803 * use non-builtin XBL bindings.
2805 bool AllowXULXBL() {
2806 return mAllowXULXBL
== eTriTrue
? true
2807 : mAllowXULXBL
== eTriFalse
? false
2808 : InternalAllowXULXBL();
2812 * Returns true if this document is allowed to load DTDs from UI resources
2815 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks
; }
2817 void ForceEnableXULXBL() { mAllowXULXBL
= eTriTrue
; }
2819 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks
= true; }
2822 * Returns the template content owner document that owns the content of
2823 * HTMLTemplateElement.
2825 Document
* GetTemplateContentsOwner();
2827 Document
* GetTemplateContentsOwnerIfExists() const {
2828 return mTemplateContentsOwner
.get();
2831 bool IsTemplateContentsOwner() const {
2832 // Template contents owner documents are the template contents owner of
2834 return mTemplateContentsOwner
== this;
2838 * Returns true if this document is a static clone of a normal document.
2840 * We create static clones for print preview and printing (possibly other
2841 * things in future).
2843 * Note that static documents are also "loaded as data" (if this method
2844 * returns true, IsLoadedAsData() will also return true).
2846 bool IsStaticDocument() const { return mIsStaticDocument
; }
2849 * Clones the document along with any subdocuments, stylesheet, etc.
2851 * The resulting document and everything it contains (including any
2852 * sub-documents) are created purely via cloning. The returned documents and
2853 * any sub-documents are "loaded as data" documents to preserve the state as
2854 * it was during the clone process (we don't want external resources to load
2855 * and replace the cloned resources).
2857 * @param aCloneContainer The container for the clone document.
2858 * @param aContentViewer The viewer for the clone document. Must be the viewer
2859 * of aCloneContainer, but callers must have a reference
2860 * to it already and ensure it's not null.
2861 * @param aPrintSettings The print settings for this clone.
2862 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2864 already_AddRefed
<Document
> CreateStaticClone(
2865 nsIDocShell
* aCloneContainer
, nsIContentViewer
* aContentViewer
,
2866 nsIPrintSettings
* aPrintSettings
, bool* aOutHasInProcessPrintCallbacks
);
2869 * If this document is a static clone, this returns the original
2872 Document
* GetOriginalDocument() const {
2873 MOZ_ASSERT(!mOriginalDocument
|| !mOriginalDocument
->GetOriginalDocument());
2874 return mOriginalDocument
;
2878 * If this document is a static clone, let the original document know that
2879 * we're going away and then release our reference to it.
2881 void UnlinkOriginalDocumentIfStatic();
2884 * These are called by the parser as it encounters <picture> tags, the end of
2885 * said tags, and possible picture <source srcset> sources respectively. These
2886 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2887 * expected to be marked void.
2889 * NOTE that the parser does not attempt to track the current picture nesting
2890 * level or whether the given <source> tag is within a picture -- it is only
2891 * guaranteed to order these calls properly with respect to
2892 * ResolvePreLoadImage.
2895 void PreloadPictureOpened() { mPreloadPictureDepth
++; }
2897 void PreloadPictureClosed();
2899 void PreloadPictureImageSource(const nsAString
& aSrcsetAttr
,
2900 const nsAString
& aSizesAttr
,
2901 const nsAString
& aTypeAttr
,
2902 const nsAString
& aMediaAttr
);
2905 * Called by the parser to resolve an image for preloading. The parser will
2906 * call the PreloadPicture* functions to inform us of possible <picture>
2907 * nesting and possible sources, which are used to inform URL selection
2908 * responsive <picture> or <img srcset> images. Unset attributes are expected
2909 * to be marked void.
2910 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2911 * true, false otherwise.
2913 already_AddRefed
<nsIURI
> ResolvePreloadImage(nsIURI
* aBaseURI
,
2914 const nsAString
& aSrcAttr
,
2915 const nsAString
& aSrcsetAttr
,
2916 const nsAString
& aSizesAttr
,
2919 * Called by nsParser to preload images. Can be removed and code moved
2920 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2921 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2922 * be a void string if the attr is not present.
2923 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2924 * when this image is for loading <picture> or <img srcset> images.
2926 void MaybePreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2927 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2929 void PreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2930 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2931 bool aLinkPreload
, uint64_t aEarlyHintPreloaderId
);
2934 * Called by images to forget an image preload when they start doing
2937 void ForgetImagePreload(nsIURI
* aURI
);
2940 * Called by the parser or the preload service to preload style sheets.
2941 * aCrossOriginAttr should be a void string if the attr is not present.
2943 SheetPreloadStatus
PreloadStyle(nsIURI
* aURI
, const Encoding
* aEncoding
,
2944 const nsAString
& aCrossOriginAttr
,
2945 ReferrerPolicyEnum aReferrerPolicy
,
2946 const nsAString
& aNonce
,
2947 const nsAString
& aIntegrity
,
2948 css::StylePreloadKind
,
2949 uint64_t aEarlyHintPreloaderId
);
2952 * Called by the chrome registry to load style sheets.
2954 * This always does a synchronous load, and parses as a normal document sheet.
2956 RefPtr
<StyleSheet
> LoadChromeSheetSync(nsIURI
* aURI
);
2959 * Returns true if the locale used for the document specifies a direction of
2960 * right to left. For chrome documents, this comes from the chrome registry.
2961 * This is used to determine the current state for the :-moz-locale-dir
2962 * pseudoclass so once can know whether a document is expected to be rendered
2963 * left-to-right or right-to-left.
2965 bool IsDocumentRightToLeft();
2968 * Called by Parser for link rel=preconnect
2970 void MaybePreconnect(nsIURI
* uri
, CORSMode aCORSMode
);
2973 * Set the document's pending state object (as serialized using structured
2976 void SetStateObject(nsIStructuredCloneContainer
* scContainer
);
2979 * Set the document's pending state object to the same state object as
2982 void SetStateObjectFrom(Document
* aDocument
) {
2983 SetStateObject(aDocument
->mStateObjectContainer
);
2987 * Returns true if there is a lightweight theme specified. This is used to
2988 * determine the state of the :-moz-lwtheme pseudo-class.
2990 bool ComputeDocumentLWTheme() const;
2991 void ResetDocumentLWTheme() {
2992 UpdateDocumentStates(DocumentState::LWTHEME
, true);
2995 // Whether we're a media document or not.
2996 enum class MediaDocumentKind
{
3003 virtual enum MediaDocumentKind
MediaDocumentKind() const {
3004 return MediaDocumentKind::NotMedia
;
3007 DocumentState
GetDocumentState() const { return mDocumentState
; }
3009 nsISupports
* GetCurrentContentSink();
3011 void ElementWithAutoFocusInserted(Element
* aAutoFocusCandidate
);
3012 MOZ_CAN_RUN_SCRIPT
void FlushAutoFocusCandidates();
3013 void ScheduleFlushAutoFocusCandidates();
3014 bool HasAutoFocusCandidates() const {
3015 return !mAutoFocusCandidates
.IsEmpty();
3018 void SetAutoFocusFired();
3020 void SetScrollToRef(nsIURI
* aDocumentURI
);
3021 MOZ_CAN_RUN_SCRIPT
void ScrollToRef();
3022 void ResetScrolledToRefAlready() { mScrolledToRefAlready
= false; }
3024 void SetChangeScrollPosWhenScrollingToRef(bool aValue
) {
3025 mChangeScrollPosWhenScrollingToRef
= aValue
;
3028 using DocumentOrShadowRoot::GetElementById
;
3029 using DocumentOrShadowRoot::GetElementsByClassName
;
3030 using DocumentOrShadowRoot::GetElementsByTagName
;
3031 using DocumentOrShadowRoot::GetElementsByTagNameNS
;
3033 DocumentTimeline
* Timeline();
3034 LinkedList
<DocumentTimeline
>& Timelines() { return mTimelines
; }
3036 SVGSVGElement
* GetSVGRootElement() const;
3038 nsresult
ScheduleFrameRequestCallback(FrameRequestCallback
& aCallback
,
3040 void CancelFrameRequestCallback(int32_t aHandle
);
3043 * Returns true if the handle refers to a callback that was canceled that
3044 * we did not find in our list of callbacks (e.g. because it is one of those
3045 * in the set of callbacks currently queued to be run).
3047 bool IsCanceledFrameRequestCallback(int32_t aHandle
) const;
3050 * Put this document's frame request callbacks into the provided
3051 * list, and forget about them.
3053 void TakeFrameRequestCallbacks(nsTArray
<FrameRequest
>& aCallbacks
);
3056 * @return true if this document's frame request callbacks should be
3057 * throttled. We throttle requestAnimationFrame for documents which aren't
3058 * visible (e.g. scrolled out of the viewport).
3060 bool ShouldThrottleFrameRequests() const;
3062 // This returns true when the document tree is being teared down.
3063 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion
; }
3065 dom::ImageTracker
* ImageTracker();
3067 // Adds an element to mResponsiveContent when the element is
3068 // added to the tree.
3069 void AddResponsiveContent(HTMLImageElement
* aContent
) {
3070 MOZ_ASSERT(aContent
);
3071 mResponsiveContent
.Insert(aContent
);
3074 // Removes an element from mResponsiveContent when the element is
3075 // removed from the tree.
3076 void RemoveResponsiveContent(HTMLImageElement
* aContent
) {
3077 MOZ_ASSERT(aContent
);
3078 mResponsiveContent
.Remove(aContent
);
3081 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement
&);
3082 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement
& aElement
) {
3083 mSVGUseElementsNeedingShadowTreeUpdate
.Remove(&aElement
);
3086 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement
& aElement
) const {
3087 return mSVGUseElementsNeedingShadowTreeUpdate
.Contains(&aElement
);
3090 using ShadowRootSet
= nsTHashSet
<ShadowRoot
*>;
3092 void AddComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3093 mComposedShadowRoots
.Insert(&aShadowRoot
);
3096 void RemoveComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3097 mComposedShadowRoots
.Remove(&aShadowRoot
);
3100 // If you're considering using this, you probably want to use
3101 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3103 bool IsComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3104 return mComposedShadowRoots
.Contains(&aShadowRoot
);
3107 const ShadowRootSet
& ComposedShadowRoots() const {
3108 return mComposedShadowRoots
;
3111 // WebIDL method for chrome code.
3112 void GetConnectedShadowRoots(nsTArray
<RefPtr
<ShadowRoot
>>&) const;
3114 // Notifies any responsive content added by AddResponsiveContent upon media
3115 // features values changing.
3116 void NotifyMediaFeatureValuesChanged();
3118 nsresult
GetStateObject(JS::MutableHandle
<JS::Value
> aState
);
3120 nsDOMNavigationTiming
* GetNavigationTiming() const { return mTiming
; }
3122 void SetNavigationTiming(nsDOMNavigationTiming
* aTiming
);
3124 nsContentList
* ImageMapList();
3126 // Add aLink to the set of links that need their status resolved.
3127 void RegisterPendingLinkUpdate(Link
* aLink
);
3129 // Update state on links in mLinksToUpdate.
3130 void FlushPendingLinkUpdates();
3132 bool HasWarnedAbout(DeprecatedOperations aOperation
) const;
3134 DeprecatedOperations aOperation
, bool asError
= false,
3135 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3137 #define DOCUMENT_WARNING(_op) e##_op,
3138 enum DocumentWarnings
{
3139 #include "nsDocumentWarningList.h"
3140 eDocumentWarningCount
3142 #undef DOCUMENT_WARNING
3143 bool HasWarnedAbout(DocumentWarnings aWarning
) const;
3145 DocumentWarnings aWarning
, bool asError
= false,
3146 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3148 // This method may fire a DOM event; if it does so it will happen
3151 // Whether the event fires is controlled by the argument.
3152 enum class DispatchVisibilityChange
{ No
, Yes
};
3153 void UpdateVisibilityState(
3154 DispatchVisibilityChange
= DispatchVisibilityChange::Yes
);
3156 // Posts an event to call UpdateVisibilityState.
3157 void PostVisibilityUpdateEvent();
3159 bool IsSyntheticDocument() const { return mIsSyntheticDocument
; }
3161 // Adds the size of a given node, which must not be a document node, to the
3162 // window sizes passed-in.
3163 static void AddSizeOfNodeTree(nsINode
&, nsWindowSizes
&);
3165 // Note: Document is a sub-class of nsINode, which has a
3166 // SizeOfExcludingThis function. However, because Document objects can
3167 // only appear at the top of the DOM tree, we have a specialized measurement
3168 // function which returns multiple sizes.
3169 virtual void DocAddSizeOfExcludingThis(nsWindowSizes
& aWindowSizes
) const;
3170 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3171 // because Document inherits from nsINode; see the comment above the
3172 // declaration of nsINode::SizeOfIncludingThis.
3173 virtual void DocAddSizeOfIncludingThis(nsWindowSizes
& aWindowSizes
) const;
3175 void ConstructUbiNode(void* storage
) override
;
3177 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers
; }
3179 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers
= true; }
3181 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers
; }
3183 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers
= true; }
3185 bool IsInSyncOperation() { return mInSyncOperationCount
!= 0; }
3187 void SetIsInSyncOperation(bool aSync
);
3189 bool CreatingStaticClone() const { return mCreatingStaticClone
; }
3192 * Creates a new element in the HTML namespace with a local name given by
3195 already_AddRefed
<Element
> CreateHTMLElement(nsAtom
* aTag
);
3198 nsIGlobalObject
* GetParentObject() const { return GetScopeObject(); }
3199 static already_AddRefed
<Document
> Constructor(const GlobalObject
& aGlobal
,
3201 DOMImplementation
* GetImplementation(ErrorResult
& rv
);
3202 [[nodiscard
]] nsresult
GetURL(nsString
& retval
) const;
3203 [[nodiscard
]] nsresult
GetDocumentURI(nsString
& retval
) const;
3204 // Return the URI for the document.
3205 // The returned value may differ if the document is loaded via XHR, and
3206 // when accessed from chrome privileged script and
3207 // from content privileged script for compatibility.
3208 void GetDocumentURIFromJS(nsString
& aDocumentURI
, CallerType aCallerType
,
3209 ErrorResult
& aRv
) const;
3210 void GetCompatMode(nsString
& retval
) const;
3211 void GetCharacterSet(nsAString
& retval
) const;
3212 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3213 // GetDoctype defined above
3214 Element
* GetDocumentElement() const { return GetRootElement(); }
3216 WindowContext
* GetTopLevelWindowContext() const;
3218 // If the top-level ancestor content document for this document is in the same
3219 // process, returns it. Otherwise, returns null. This function is not
3220 // Fission-compatible, and should not be used in new code.
3221 Document
* GetTopLevelContentDocumentIfSameProcess();
3222 const Document
* GetTopLevelContentDocumentIfSameProcess() const;
3224 // Returns the associated app window if this is a top-level chrome document,
3226 already_AddRefed
<nsIAppWindow
> GetAppWindowIfToplevelChrome() const;
3228 already_AddRefed
<Element
> CreateElement(
3229 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3231 already_AddRefed
<Element
> CreateElementNS(
3232 const nsAString
& aNamespaceURI
, const nsAString
& aQualifiedName
,
3233 const ElementCreationOptionsOrString
& aOptions
, ErrorResult
& rv
);
3234 already_AddRefed
<Element
> CreateXULElement(
3235 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3237 already_AddRefed
<DocumentFragment
> CreateDocumentFragment() const;
3238 already_AddRefed
<nsTextNode
> CreateTextNode(const nsAString
& aData
) const;
3239 already_AddRefed
<nsTextNode
> CreateEmptyTextNode() const;
3240 already_AddRefed
<Comment
> CreateComment(const nsAString
& aData
) const;
3241 already_AddRefed
<ProcessingInstruction
> CreateProcessingInstruction(
3242 const nsAString
& target
, const nsAString
& data
, ErrorResult
& rv
) const;
3243 already_AddRefed
<nsINode
> ImportNode(nsINode
& aNode
, bool aDeep
,
3244 ErrorResult
& rv
) const;
3245 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3246 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode
* AdoptNode(
3247 nsINode
& aAdoptedNode
, ErrorResult
& rv
, bool aAcceptShadowRoot
= false);
3248 already_AddRefed
<Event
> CreateEvent(const nsAString
& aEventType
,
3249 CallerType aCallerType
,
3250 ErrorResult
& rv
) const;
3251 already_AddRefed
<nsRange
> CreateRange(ErrorResult
& rv
);
3252 already_AddRefed
<NodeIterator
> CreateNodeIterator(nsINode
& aRoot
,
3253 uint32_t aWhatToShow
,
3254 NodeFilter
* aFilter
,
3255 ErrorResult
& rv
) const;
3256 already_AddRefed
<TreeWalker
> CreateTreeWalker(nsINode
& aRoot
,
3257 uint32_t aWhatToShow
,
3258 NodeFilter
* aFilter
,
3259 ErrorResult
& rv
) const;
3260 // Deprecated WebIDL bits
3261 already_AddRefed
<CDATASection
> CreateCDATASection(const nsAString
& aData
,
3263 already_AddRefed
<Attr
> CreateAttribute(const nsAString
& aName
,
3265 already_AddRefed
<Attr
> CreateAttributeNS(const nsAString
& aNamespaceURI
,
3266 const nsAString
& aQualifiedName
,
3268 void GetInputEncoding(nsAString
& aInputEncoding
) const;
3269 already_AddRefed
<Location
> GetLocation() const;
3270 void GetDomain(nsAString
& aDomain
);
3271 void SetDomain(const nsAString
& aDomain
, mozilla::ErrorResult
& rv
);
3272 void GetCookie(nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3273 void SetCookie(const nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3274 void GetReferrer(nsAString
& aReferrer
) const;
3275 void GetLastModified(nsAString
& aLastModified
) const;
3276 void GetReadyState(nsAString
& aReadyState
) const;
3278 void GetTitle(nsAString
& aTitle
);
3279 void SetTitle(const nsAString
& aTitle
, ErrorResult
& rv
);
3280 void GetDir(nsAString
& aDirection
) const;
3281 void SetDir(const nsAString
& aDirection
);
3282 nsIHTMLCollection
* Images();
3283 nsIHTMLCollection
* Embeds();
3284 nsIHTMLCollection
* Plugins() { return Embeds(); }
3285 nsIHTMLCollection
* Links();
3286 nsIHTMLCollection
* Forms();
3287 nsIHTMLCollection
* Scripts();
3288 already_AddRefed
<nsContentList
> GetElementsByName(const nsAString
& aName
) {
3289 return GetFuncStringContentList
<nsCachableElementsByNameNodeList
>(
3290 this, MatchNameAttribute
, nullptr, UseExistingNameString
, aName
);
3292 Document
* Open(const mozilla::dom::Optional
<nsAString
>& /* unused */,
3293 const mozilla::dom::Optional
<nsAString
>& /* unused */,
3294 mozilla::ErrorResult
& aError
);
3295 mozilla::dom::Nullable
<mozilla::dom::WindowProxyHolder
> Open(
3296 const nsAString
& aURL
, const nsAString
& aName
, const nsAString
& aFeatures
,
3297 mozilla::ErrorResult
& rv
);
3298 void Close(mozilla::ErrorResult
& rv
);
3299 void Write(const mozilla::dom::Sequence
<nsString
>& aText
,
3300 mozilla::ErrorResult
& rv
);
3301 void Writeln(const mozilla::dom::Sequence
<nsString
>& aText
,
3302 mozilla::ErrorResult
& rv
);
3303 Nullable
<WindowProxyHolder
> GetDefaultView() const;
3304 Element
* GetActiveElement();
3305 enum class IncludeChromeOnly
: bool { No
, Yes
};
3306 // TODO(emilio): Audit callers and remove the default argument, some seem like
3307 // they could want the IncludeChromeOnly::Yes version.
3308 nsIContent
* GetUnretargetedFocusedContent(
3309 IncludeChromeOnly
= IncludeChromeOnly::No
) const;
3311 * Return true if this document or a subdocument has focus.
3313 bool HasFocus(ErrorResult
& rv
) const;
3316 * Return true if this document itself has focus.
3318 bool ThisDocumentHasFocus() const;
3320 void GetDesignMode(nsAString
& aDesignMode
);
3321 void SetDesignMode(const nsAString
& aDesignMode
,
3322 nsIPrincipal
& aSubjectPrincipal
, mozilla::ErrorResult
& rv
);
3323 void SetDesignMode(const nsAString
& aDesignMode
,
3324 const mozilla::Maybe
<nsIPrincipal
*>& aSubjectPrincipal
,
3325 mozilla::ErrorResult
& rv
);
3327 bool ExecCommand(const nsAString
& aHTMLCommandName
, bool aShowUI
,
3328 const nsAString
& aValue
, nsIPrincipal
& aSubjectPrincipal
,
3329 mozilla::ErrorResult
& aRv
);
3330 MOZ_CAN_RUN_SCRIPT
bool QueryCommandEnabled(const nsAString
& aHTMLCommandName
,
3331 nsIPrincipal
& aSubjectPrincipal
,
3332 mozilla::ErrorResult
& aRv
);
3333 MOZ_CAN_RUN_SCRIPT
bool QueryCommandIndeterm(
3334 const nsAString
& aHTMLCommandName
, mozilla::ErrorResult
& aRv
);
3335 MOZ_CAN_RUN_SCRIPT
bool QueryCommandState(const nsAString
& aHTMLCommandName
,
3336 mozilla::ErrorResult
& aRv
);
3337 MOZ_CAN_RUN_SCRIPT
bool QueryCommandSupported(
3338 const nsAString
& aHTMLCommandName
, mozilla::dom::CallerType aCallerType
,
3339 mozilla::ErrorResult
& aRv
);
3340 MOZ_CAN_RUN_SCRIPT
void QueryCommandValue(const nsAString
& aHTMLCommandName
,
3342 mozilla::ErrorResult
& aRv
);
3343 nsIHTMLCollection
* Applets();
3344 nsIHTMLCollection
* Anchors();
3345 TimeStamp
LastFocusTime() const;
3346 void SetLastFocusTime(const TimeStamp
& aFocusTime
);
3347 // Event handlers are all on nsINode already
3348 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3349 Element
* GetCurrentScript();
3350 void ReleaseCapture() const;
3351 void MozSetImageElement(const nsAString
& aImageElementId
, Element
* aElement
);
3352 nsIURI
* GetDocumentURIObject() const;
3353 // Not const because all the fullscreen goop is not const
3354 const char* GetFullscreenError(CallerType
);
3355 bool FullscreenEnabled(CallerType aCallerType
) {
3356 return !GetFullscreenError(aCallerType
);
3359 void GetWireframeWithoutFlushing(bool aIncludeNodes
, Nullable
<Wireframe
>&);
3361 MOZ_CAN_RUN_SCRIPT
void GetWireframe(bool aIncludeNodes
,
3362 Nullable
<Wireframe
>&);
3364 // Hides all popovers until the given end point, see
3365 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3366 MOZ_CAN_RUN_SCRIPT
void HideAllPopoversUntil(nsINode
& aEndpoint
,
3367 bool aFocusPreviousElement
,
3370 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void HideAllPopoversWithoutRunningScript();
3371 // Hides the given popover element, see
3372 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3373 MOZ_CAN_RUN_SCRIPT
void HidePopover(Element
& popover
,
3374 bool aFocusPreviousElement
,
3375 bool aFireEvents
, ErrorResult
& aRv
);
3377 // Returns a list of all the elements in the Document's top layer whose
3378 // popover attribute is in the auto state.
3379 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3380 nsTArray
<Element
*> AutoPopoverList() const;
3382 // Return document's auto popover list's last element.
3384 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3385 Element
* GetTopmostAutoPopover() const;
3387 // Adds/removes an element to/from the auto popover list.
3388 void AddToAutoPopoverList(Element
&);
3389 void RemoveFromAutoPopoverList(Element
&);
3391 void AddPopoverToTopLayer(Element
&);
3392 void RemovePopoverFromTopLayer(Element
&);
3394 Element
* GetTopLayerTop();
3395 // Return the fullscreen element in the top layer
3396 Element
* GetUnretargetedFullscreenElement() const;
3397 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3398 already_AddRefed
<Promise
> ExitFullscreen(ErrorResult
&);
3399 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3400 void GetFgColor(nsAString
& aFgColor
);
3401 void SetFgColor(const nsAString
& aFgColor
);
3402 void GetLinkColor(nsAString
& aLinkColor
);
3403 void SetLinkColor(const nsAString
& aLinkColor
);
3404 void GetVlinkColor(nsAString
& aAvlinkColor
);
3405 void SetVlinkColor(const nsAString
& aVlinkColor
);
3406 void GetAlinkColor(nsAString
& aAlinkColor
);
3407 void SetAlinkColor(const nsAString
& aAlinkColor
);
3408 void GetBgColor(nsAString
& aBgColor
);
3409 void SetBgColor(const nsAString
& aBgColor
);
3410 void Clear() const {
3413 void CaptureEvents();
3414 void ReleaseEvents();
3416 mozilla::dom::HTMLAllCollection
* All();
3418 static bool DocumentSupportsL10n(JSContext
* aCx
, JSObject
* aObject
);
3419 static bool IsWebAnimationsGetAnimationsEnabled(JSContext
* aCx
,
3421 static bool AreWebAnimationsTimelinesEnabled(JSContext
* aCx
,
3423 // Checks that the caller is either chrome or some addon.
3424 static bool IsCallerChromeOrAddon(JSContext
* aCx
, JSObject
* aObject
);
3426 bool Hidden() const { return mVisibilityState
!= VisibilityState::Visible
; }
3427 dom::VisibilityState
VisibilityState() const { return mVisibilityState
; }
3430 void GetSelectedStyleSheetSet(nsAString
& aSheetSet
);
3431 void SetSelectedStyleSheetSet(const nsAString
& aSheetSet
);
3432 void GetLastStyleSheetSet(nsAString
& aSheetSet
) {
3433 aSheetSet
= mLastStyleSheetSet
;
3435 const nsString
& GetCurrentStyleSheetSet() const {
3436 return mLastStyleSheetSet
.IsEmpty() ? mPreferredStyleSheetSet
3437 : mLastStyleSheetSet
;
3439 void SetPreferredStyleSheetSet(const nsAString
&);
3440 void GetPreferredStyleSheetSet(nsAString
& aSheetSet
) {
3441 aSheetSet
= mPreferredStyleSheetSet
;
3443 DOMStringList
* StyleSheetSets();
3444 void EnableStyleSheetsForSet(const nsAString
& aSheetSet
);
3447 * Retrieve the location of the caret position (DOM node and character
3448 * offset within that node), given a point.
3450 * @param aX Horizontal point at which to determine the caret position, in
3452 * @param aY Vertical point at which to determine the caret position, in
3455 already_AddRefed
<nsDOMCaretPosition
> CaretPositionFromPoint(float aX
,
3458 Element
* GetScrollingElement();
3459 // A way to check whether a given element is what would get returned from
3460 // GetScrollingElement. It can be faster than comparing to the return value
3461 // of GetScrollingElement() due to being able to avoid flushes in various
3462 // cases. This method assumes that null is NOT passed.
3463 bool IsScrollingElement(Element
* aElement
);
3465 // QuerySelector and QuerySelectorAll already defined on nsINode
3467 XPathExpression
* CreateExpression(const nsAString
& aExpression
,
3468 XPathNSResolver
* aResolver
,
3470 nsINode
* CreateNSResolver(nsINode
& aNodeResolver
);
3471 already_AddRefed
<XPathResult
> Evaluate(
3472 JSContext
* aCx
, const nsAString
& aExpression
, nsINode
& aContextNode
,
3473 XPathNSResolver
* aResolver
, uint16_t aType
, JS::Handle
<JSObject
*> aResult
,
3475 // Touch event handlers already on nsINode
3476 already_AddRefed
<Touch
> CreateTouch(nsGlobalWindowInner
* aView
,
3477 EventTarget
* aTarget
, int32_t aIdentifier
,
3478 int32_t aPageX
, int32_t aPageY
,
3479 int32_t aScreenX
, int32_t aScreenY
,
3480 int32_t aClientX
, int32_t aClientY
,
3481 int32_t aRadiusX
, int32_t aRadiusY
,
3482 float aRotationAngle
, float aForce
);
3483 already_AddRefed
<TouchList
> CreateTouchList();
3484 already_AddRefed
<TouchList
> CreateTouchList(
3485 Touch
& aTouch
, const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3486 already_AddRefed
<TouchList
> CreateTouchList(
3487 const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3489 void SetStyleSheetChangeEventsEnabled(bool aValue
) {
3490 mStyleSheetChangeEventsEnabled
= aValue
;
3493 bool StyleSheetChangeEventsEnabled() const {
3494 return mStyleSheetChangeEventsEnabled
;
3497 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue
) {
3498 mDevToolsAnonymousAndShadowEventsEnabled
= aValue
;
3500 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3501 return mDevToolsAnonymousAndShadowEventsEnabled
;
3504 already_AddRefed
<Promise
> BlockParsing(Promise
& aPromise
,
3505 const BlockParsingOptions
& aOptions
,
3508 already_AddRefed
<nsIURI
> GetMozDocumentURIIfNotForErrorPages();
3510 Promise
* GetDocumentReadyForIdle(ErrorResult
& aRv
);
3512 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock
) {
3516 UnblockOnload(/* aFireSync = */ false);
3520 nsIDOMXULCommandDispatcher
* GetCommandDispatcher();
3521 bool HasXULBroadcastManager() const { return mXULBroadcastManager
; };
3522 void InitializeXULBroadcastManager();
3523 XULBroadcastManager
* GetXULBroadcastManager() const {
3524 return mXULBroadcastManager
;
3526 nsINode
* GetPopupRangeParent(ErrorResult
& aRv
);
3527 int32_t GetPopupRangeOffset(ErrorResult
& aRv
);
3529 bool DevToolsWatchingDOMMutations() const {
3530 return mDevToolsWatchingDOMMutations
;
3532 void SetDevToolsWatchingDOMMutations(bool aValue
);
3534 void MaybeWarnAboutZoom();
3536 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3537 void EvaluateMediaQueriesAndReportChanges(bool aRecurse
);
3540 nsIHTMLCollection
* Children();
3541 uint32_t ChildElementCount();
3544 * Asserts IsHTMLOrXHTML, and can't return null.
3545 * Defined inline in nsHTMLDocument.h
3547 inline nsHTMLDocument
* AsHTMLDocument();
3548 inline const nsHTMLDocument
* AsHTMLDocument() const;
3551 * Asserts IsSVGDocument, and can't return null.
3552 * Defined inline in SVGDocument.h
3554 inline SVGDocument
* AsSVGDocument();
3555 inline const SVGDocument
* AsSVGDocument() const;
3558 * Asserts IsImageDocument, and can't return null.
3559 * Defined inline in ImageDocument.h
3561 inline ImageDocument
* AsImageDocument();
3562 inline const ImageDocument
* AsImageDocument() const;
3565 * Given a node, get a weak reference to it and append that reference to
3566 * mBlockedNodesByClassifier. Can be used later on to look up a node in it.
3569 void AddBlockedNodeByClassifier(nsINode
* node
) {
3574 nsWeakPtr weakNode
= do_GetWeakReference(node
);
3577 mBlockedNodesByClassifier
.AppendElement(weakNode
);
3581 gfxUserFontSet
* GetUserFontSet();
3582 void FlushUserFontSet();
3583 void MarkUserFontSetDirty();
3584 FontFaceSet
* GetFonts() { return mFontFaceSet
; }
3587 FontFaceSet
* GetFonts(ErrorResult
&) { return Fonts(); }
3588 FontFaceSet
* Fonts();
3590 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded
; }
3592 bool IsSynthesized();
3594 // Records whether we will track use counters for this document, and if so,
3595 // which top-level document that page counters will be accumulated to.
3597 // Informs the parent process that page use counters will be sent once the
3598 // document goes away.
3599 void InitUseCounters();
3601 // Reports document use counters via telemetry. This method only has an
3602 // effect once per document, and so is called during document destruction.
3603 void ReportDocumentUseCounters();
3605 // Report how lazyload performs for this document.
3606 void ReportDocumentLazyLoadCounters();
3608 // Sends page use counters to the parent process to accumulate against the
3609 // top-level document. Must be called while we still have access to our
3610 // WindowContext. This method has an effect each time it is called, and we
3611 // call it just before the document loses its window.
3612 void SendPageUseCounters();
3614 void SetUseCounter(UseCounter aUseCounter
) {
3615 mUseCounters
[aUseCounter
] = true;
3618 const StyleUseCounters
* GetStyleUseCounters() {
3619 return mStyleUseCounters
.get();
3622 // Propagate our use counters explicitly into the specified referencing
3625 // This is used for SVG image documents, which cannot be enumerated in the
3626 // referencing document's ReportUseCounters() like external resource documents
3628 void PropagateImageUseCounters(Document
* aReferencingDocument
);
3630 // Called to track whether this document has had any interaction.
3631 // This is used to track whether we should permit "beforeunload".
3632 void SetUserHasInteracted();
3633 bool UserHasInteracted() { return mUserHasInteracted
; }
3634 void ResetUserInteractionTimer();
3636 // Whether we're cloning the contents of an SVG use element.
3637 bool CloningForSVGUse() const { return mCloningForSVGUse
; }
3639 // This should be called when this document receives events which are likely
3640 // to be user interaction with the document, rather than the byproduct of
3641 // interaction with the browser (i.e. a keypress to scroll the view port,
3642 // keyboard shortcuts, etc). This is used to decide whether we should
3643 // permit autoplay audible media. This also gesture activates all other
3644 // content documents in this tab.
3645 void NotifyUserGestureActivation();
3647 // This function is used for mochitest only.
3648 void ClearUserGestureActivation();
3650 // Return true if NotifyUserGestureActivation() has been called on any
3651 // document in the document tree.
3652 bool HasBeenUserGestureActivated();
3654 // Reture timestamp of last user gesture in milliseconds relative to
3655 // navigation start timestamp.
3656 DOMHighResTimeStamp
LastUserGestureTimeStamp();
3658 // Return true if there is transient user gesture activation and it hasn't yet
3659 // timed out or hasn't been consumed.
3660 bool HasValidTransientUserGestureActivation() const;
3662 // Return true if HasValidTransientUserGestureActivation() would return true,
3663 // and consume the activation.
3664 bool ConsumeTransientUserGestureActivation();
3666 BrowsingContext
* GetBrowsingContext() const;
3668 // This document is a WebExtension page, it might be a background page, a
3669 // popup, a visible tab, a visible iframe ...e.t.c.
3670 bool IsExtensionPage() const;
3672 bool HasScriptsBlockedBySandbox() const;
3674 void ReportHasScrollLinkedEffect(const TimeStamp
& aTimeStamp
);
3675 bool HasScrollLinkedEffect() const;
3678 void AssertDocGroupMatchesKey() const;
3681 DocGroup
* GetDocGroup() const {
3683 AssertDocGroupMatchesKey();
3688 DocGroup
* GetDocGroupOrCreate();
3691 * If we're a sub-document, the parent document's layout can affect our style
3692 * and layout (due to the viewport size, viewport units, media queries...).
3694 * This function returns true if our parent document and our child document
3695 * can observe each other. If they cannot, then we don't need to synchronously
3696 * update the parent document layout every time the child document may need
3697 * up-to-date layout information.
3699 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3700 return GetInProcessParentDocument() &&
3701 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3704 void AddIntersectionObserver(DOMIntersectionObserver
* aObserver
) {
3705 MOZ_ASSERT(!mIntersectionObservers
.Contains(aObserver
),
3706 "Intersection observer already in the list");
3707 mIntersectionObservers
.Insert(aObserver
);
3710 void RemoveIntersectionObserver(DOMIntersectionObserver
* aObserver
) {
3711 mIntersectionObservers
.Remove(aObserver
);
3714 bool HasIntersectionObservers() const {
3715 return !mIntersectionObservers
.IsEmpty();
3718 void UpdateIntersectionObservations(TimeStamp aNowTime
);
3719 void ScheduleIntersectionObserverNotification();
3720 MOZ_CAN_RUN_SCRIPT
void NotifyIntersectionObservers();
3722 DOMIntersectionObserver
* GetLazyLoadImageObserver() {
3723 return mLazyLoadImageObserver
;
3725 DOMIntersectionObserver
* GetLazyLoadImageObserverViewport() {
3726 return mLazyLoadImageObserverViewport
;
3728 DOMIntersectionObserver
& EnsureLazyLoadImageObserver();
3730 DOMIntersectionObserver
* GetContentVisibilityObserver() const {
3731 return mContentVisibilityObserver
;
3733 DOMIntersectionObserver
& EnsureContentVisibilityObserver();
3734 void ObserveForContentVisibility(Element
&);
3735 void UnobserveForContentVisibility(Element
&);
3737 ResizeObserver
* GetLastRememberedSizeObserver() {
3738 return mLastRememberedSizeObserver
;
3740 ResizeObserver
& EnsureLastRememberedSizeObserver();
3741 void ObserveForLastRememberedSize(Element
&);
3742 void UnobserveForLastRememberedSize(Element
&);
3744 // Dispatch a runnable related to the document.
3745 nsresult
Dispatch(already_AddRefed
<nsIRunnable
>&& aRunnable
) const;
3747 // The URLs passed to this function should match what
3748 // JS::DescribeScriptedCaller() returns, since this API is used to
3749 // determine whether some code is being called from a tracking script.
3750 void NoteScriptTrackingStatus(const nsACString
& aURL
, bool isTracking
);
3751 // The JSContext passed to this method represents the context that we want to
3752 // determine if it belongs to a tracker.
3753 bool IsScriptTracking(JSContext
* aCx
) const;
3755 // ResizeObserver usage.
3756 void AddResizeObserver(ResizeObserver
&);
3757 void RemoveResizeObserver(ResizeObserver
&);
3758 void ScheduleResizeObserversNotification() const;
3759 bool HasResizeObservers() const { return !mResizeObservers
.IsEmpty(); }
3761 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3762 * All observations in each ResizeObserver with element's depth more than
3763 * aDepth will be gathered.
3765 void GatherAllActiveResizeObservations(uint32_t aDepth
);
3767 * Calls BroadcastActiveObservations() for all ResizeObservers.
3768 * It also returns the shallowest depth of observed target elements with
3769 * active observations from all ResizeObservers or
3770 * numeric_limits<uint32_t>::max() if there aren't any active observations
3773 MOZ_CAN_RUN_SCRIPT
uint32_t BroadcastAllActiveResizeObservations();
3775 * Returns whether there is any ResizeObserver that has active
3778 bool HasAnyActiveResizeObservations() const;
3780 * Returns whether there is any ResizeObserver that has skipped observations.
3782 bool HasAnySkippedResizeObservations() const;
3783 MOZ_CAN_RUN_SCRIPT
void NotifyResizeObservers();
3785 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3786 PermissionDelegateHandler
* GetPermissionDelegateHandler();
3788 // Notify the document that a fetch or a XHR request has completed
3789 // succesfully in this document. This is used by the password manager to infer
3790 // whether a form is submitted.
3791 void NotifyFetchOrXHRSuccess();
3793 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3794 void SetNotifyFetchSuccess(bool aShouldNotify
);
3796 // When this is set, removing a form or a password field from DOM
3797 // sends a Chrome-only event. This is now only used by the password manager.
3798 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify
);
3800 // This function is used by HTMLFormElement and HTMLInputElement to determin
3801 // whether to send an event when it is removed from DOM.
3802 bool ShouldNotifyFormOrPasswordRemoved() const {
3803 return mShouldNotifyFormOrPasswordRemoved
;
3806 HTMLEditor
* GetHTMLEditor() const;
3811 * For more information on DocumentL10n see
3812 * intl/l10n/docs/fluent/tutorial.rst
3817 * This is a public method exposed on Document WebIDL
3818 * to chrome only documents.
3820 DocumentL10n
* GetL10n() const { return mDocumentL10n
.get(); }
3823 * Whether there's any async l10n mutation work pending.
3825 * When this turns false, we fire the L10nMutationsFinished event.
3827 bool HasPendingL10nMutations() const;
3830 * This method should be called when the container
3831 * of l10n resources parsing is completed.
3833 * It triggers initial async fetch of the resources
3834 * as early as possible.
3836 * In HTML case this is </head>.
3837 * In XUL case this is </linkset>.
3839 void OnL10nResourceContainerParsed();
3842 * This method should be called when a link element
3843 * with rel="localization" is being added to the
3844 * l10n resource container element.
3846 void LocalizationLinkAdded(Element
* aLinkElement
);
3849 * This method should be called when a link element
3850 * with rel="localization" is being removed.
3852 void LocalizationLinkRemoved(Element
* aLinkElement
);
3855 * This method should be called as soon as the
3856 * parsing of the document is completed.
3858 * In HTML/XHTML this happens when we finish parsing
3859 * the document element.
3860 * In XUL it happens at `DoneWalking`, during
3861 * `MozBeforeInitialXULLayout`.
3863 void OnParsingCompleted();
3866 * This method is called when the initial translation
3867 * of the document is completed.
3869 * It unblocks the load event if translation was blocking it.
3871 * If the `aL10nCached` is set to `true`, and the document has
3872 * a prototype, it will set the `isL10nCached` flag on it.
3874 void InitialTranslationCompleted(bool aL10nCached
);
3877 * Returns whether the document allows localization.
3879 bool AllowsL10n() const;
3882 RefPtr
<DocumentL10n
> mDocumentL10n
;
3885 * Return true when you want a document without explicitly specified viewport
3886 * dimensions/scale to be treated as if "width=device-width" had in fact been
3889 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3892 bool IsErrorPage() const;
3894 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3896 void SetCssUseCounterBits();
3898 void ParseWidthAndHeightInMetaViewport(const nsAString
& aWidthString
,
3899 const nsAString
& aHeightString
,
3902 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3903 // represents the scale property and returns the scale value if it's valid.
3904 Maybe
<LayoutDeviceToScreenScale
> ParseScaleInHeader(nsAtom
* aHeaderField
);
3906 // Parse scale values in |aViewportMetaData| and set the values in
3907 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3908 void ParseScalesInViewportMetaData(const ViewportMetaData
& aViewportMetaData
);
3910 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3911 // stored in parent iframe or container's browsingContext (cross process)
3912 already_AddRefed
<mozilla::dom::FeaturePolicy
> GetParentFeaturePolicy();
3915 const OriginTrials
& Trials() const { return mTrials
; }
3918 void DoCacheAllKnownLangPrefs();
3919 void RecomputeLanguageFromCharset();
3920 bool GetSHEntryHasUserInteraction();
3922 void AppendAutoFocusCandidateToTopDocument(Element
* aAutoFocusCandidate
);
3925 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate
= true; }
3927 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate
; }
3929 void SetSHEntryHasUserInteraction(bool aHasInteraction
);
3931 already_AddRefed
<nsAtom
> GetContentLanguageAsAtomForStyle() const;
3932 already_AddRefed
<nsAtom
> GetLanguageForStyle() const;
3935 * Fetch the user's font preferences for the given aLanguage's
3938 const LangGroupFontPrefs
* GetFontPrefsForLang(
3939 nsAtom
* aLanguage
, bool* aNeedsToCache
= nullptr) const;
3941 void ForceCacheLang(nsAtom
* aLanguage
) {
3942 if (!mLanguagesUsed
.EnsureInserted(aLanguage
)) {
3945 GetFontPrefsForLang(aLanguage
);
3948 void CacheAllKnownLangPrefs() {
3949 if (!mMayNeedFontPrefsUpdate
) {
3952 DoCacheAllKnownLangPrefs();
3955 nsINode
* GetServoRestyleRoot() const { return mServoRestyleRoot
; }
3957 uint32_t GetServoRestyleRootDirtyBits() const {
3958 MOZ_ASSERT(mServoRestyleRoot
);
3959 MOZ_ASSERT(mServoRestyleRootDirtyBits
);
3960 return mServoRestyleRootDirtyBits
;
3963 void ClearServoRestyleRoot() {
3964 mServoRestyleRoot
= nullptr;
3965 mServoRestyleRootDirtyBits
= 0;
3968 inline void SetServoRestyleRoot(nsINode
* aRoot
, uint32_t aDirtyBits
);
3969 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits
);
3971 bool ShouldThrowOnDynamicMarkupInsertion() {
3972 return mThrowOnDynamicMarkupInsertionCounter
;
3975 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3976 ++mThrowOnDynamicMarkupInsertionCounter
;
3979 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3980 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter
);
3981 --mThrowOnDynamicMarkupInsertionCounter
;
3984 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter
; }
3986 void IncrementIgnoreOpensDuringUnloadCounter() {
3987 ++mIgnoreOpensDuringUnloadCounter
;
3990 void DecrementIgnoreOpensDuringUnloadCounter() {
3991 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter
);
3992 --mIgnoreOpensDuringUnloadCounter
;
3995 mozilla::dom::FeaturePolicy
* FeaturePolicy() const;
3997 bool ImportMapsEnabled() const;
4000 * Find the (non-anonymous) content in this document for aFrame. It will
4001 * be aFrame's content node if that content is in this document and not
4002 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4003 * element containing the subdocument containing aFrame, and/or find the
4004 * nearest non-anonymous ancestor in this document.
4005 * Returns null if there is no such element.
4007 nsIContent
* GetContentInThisDocument(nsIFrame
* aFrame
) const;
4009 void ReportShadowDOMUsage();
4011 // Sets flags for media telemetry.
4012 void SetDocTreeHadMedia();
4014 dom::XPathEvaluator
* XPathEvaluator();
4016 void MaybeInitializeFinalizeFrameLoaders();
4018 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization
) {
4019 mDelayFrameLoaderInitialization
= aDelayFrameLoaderInitialization
;
4022 void SetPrototypeDocument(nsXULPrototypeDocument
* aPrototype
);
4024 nsIPermissionDelegateHandler
* PermDelegateHandler();
4026 // Returns whether this is a top-level about:blank page without an opener
4027 // (and thus not accessible by content).
4028 bool IsContentInaccessibleAboutBlank() const;
4030 // CSS prefers-color-scheme media feature for this document.
4031 enum class IgnoreRFP
{ No
, Yes
};
4032 ColorScheme
PreferredColorScheme(IgnoreRFP
= IgnoreRFP::No
) const;
4033 // Returns the initial color-scheme used for this document based on the
4034 // color-scheme meta tag.
4035 ColorScheme
DefaultColorScheme() const;
4037 static bool HasRecentlyStartedForegroundLoads();
4039 static bool AutomaticStorageAccessPermissionCanBeGranted(
4040 nsIPrincipal
* aPrincipal
);
4042 already_AddRefed
<Promise
> AddCertException(bool aIsTemporary
,
4043 ErrorResult
& aError
);
4045 void ReloadWithHttpsOnlyException();
4047 // Subframes need to be static cloned after the main document has been
4048 // embedded within a script global. A `PendingFrameStaticClone` is a static
4049 // clone which has not yet been performed.
4051 // The getter returns a direct reference to an internal array which is
4052 // manipulated from within printing code.
4053 struct PendingFrameStaticClone
{
4054 PendingFrameStaticClone() = default;
4055 PendingFrameStaticClone(PendingFrameStaticClone
&&) = default;
4056 PendingFrameStaticClone
& operator=(PendingFrameStaticClone
&&) = default;
4057 ~PendingFrameStaticClone();
4059 RefPtr
<nsFrameLoaderOwner
> mElement
;
4060 RefPtr
<nsFrameLoader
> mStaticCloneOf
;
4062 void AddPendingFrameStaticClone(nsFrameLoaderOwner
* aElement
,
4063 nsFrameLoader
* aStaticCloneOf
);
4065 bool ShouldAvoidNativeTheme() const;
4067 static bool IsValidDomain(nsIURI
* aOrigHost
, nsIURI
* aNewURI
);
4069 // Inform a parent document that a BrowserBridgeChild has been created for
4070 // an OOP sub-document.
4071 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4072 void OOPChildLoadStarted(BrowserBridgeChild
* aChild
);
4074 // Inform a parent document that the BrowserBridgeChild for one of its
4075 // OOP sub-documents is done calling its onload handler.
4076 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4077 void OOPChildLoadDone(BrowserBridgeChild
* aChild
);
4079 void ClearOOPChildrenLoading();
4081 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading
.IsEmpty(); }
4083 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache
= true; }
4085 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache
; }
4088 * Get the `HighlightRegistry` which contains all highlights associated
4089 * with this document.
4091 class HighlightRegistry
& HighlightRegistry();
4093 bool ShouldResistFingerprinting(RFPTarget aTarget
) const;
4095 // Recompute the current resist fingerprinting state. Returns true when
4096 // the state was changed.
4097 bool RecomputeResistFingerprinting();
4099 bool MayHaveDOMActivateListeners() const;
4102 // Returns the WindowContext for the document that we will contribute
4103 // page use counters to.
4104 WindowContext
* GetWindowContextForPageUseCounters() const;
4106 void DoUpdateSVGUseElementShadowTrees();
4108 already_AddRefed
<nsIPrincipal
> MaybeDowngradePrincipal(
4109 nsIPrincipal
* aPrincipal
);
4111 void EnsureOnloadBlocker();
4113 void SendToConsole(nsCOMArray
<nsISecurityConsoleMessage
>& aMessages
);
4115 // Returns true if the scheme for the url for this document is "about".
4116 bool IsAboutPage() const;
4118 bool ContainsEMEContent();
4119 bool ContainsMSEContent();
4122 * Returns the title element of the document as defined by the HTML
4123 * specification, or null if there isn't one. For documents whose root
4124 * element is an <svg:svg>, this is the first <svg:title> element that's a
4125 * child of the root. For other documents, it's the first HTML title element
4128 Element
* GetTitleElement();
4130 void RecordNavigationTiming(ReadyState aReadyState
);
4132 // Recomputes the visibility state but doesn't set the new value.
4133 dom::VisibilityState
ComputeVisibilityState() const;
4135 // Since we wouldn't automatically play media from non-visited page, we need
4136 // to notify window when the page was first visited.
4137 void MaybeActiveMediaComponents();
4139 // Apply the fullscreen state to the document, and trigger related
4140 // events. It returns false if the fullscreen element ready check
4141 // fails and nothing gets changed.
4142 bool ApplyFullscreen(UniquePtr
<FullscreenRequest
>);
4144 void RemoveDocStyleSheetsFromStyleSets();
4145 void ResetStylesheetsToURI(nsIURI
* aURI
);
4146 void FillStyleSet();
4147 void FillStyleSetUserAndUASheets();
4148 void FillStyleSetDocumentSheets();
4149 void CompatibilityModeChanged();
4150 bool NeedsQuirksSheet() const {
4151 // SVG documents never load quirk.css.
4152 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4153 return mCompatMode
== eCompatibility_NavQuirks
&& !IsSVGDocument();
4155 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode
);
4156 void RemoveContentEditableStyleSheets();
4157 void AddStyleSheetToStyleSets(StyleSheet
&);
4158 void RemoveStyleSheetFromStyleSets(StyleSheet
&);
4159 void NotifyStyleSheetApplicableStateChanged();
4160 // Just like EnableStyleSheetsForSet, but doesn't check whether
4161 // aSheetSet is null and allows the caller to control whether to set
4162 // aSheetSet as the preferred set in the CSSLoader.
4163 void EnableStyleSheetsForSetInternal(const nsAString
& aSheetSet
,
4164 bool aUpdateCSSLoader
);
4166 already_AddRefed
<nsIURI
> GetDomainURI();
4167 already_AddRefed
<nsIURI
> CreateInheritingURIForHost(
4168 const nsACString
& aHostString
);
4169 already_AddRefed
<nsIURI
> RegistrableDomainSuffixOfInternal(
4170 const nsAString
& aHostSuffixString
, nsIURI
* aOrigHost
);
4172 void WriteCommon(const nsAString
& aText
, bool aNewlineTerminate
,
4173 mozilla::ErrorResult
& aRv
);
4174 // A version of WriteCommon used by WebIDL bindings
4175 void WriteCommon(const mozilla::dom::Sequence
<nsString
>& aText
,
4176 bool aNewlineTerminate
, mozilla::ErrorResult
& rv
);
4178 void* GenerateParserKey(void);
4181 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4183 enum class ExecCommandParam
: uint8_t {
4184 // Always ignore it.
4186 // Treat the given parameter as-is. If the command requires it, use it.
4187 // Otherwise, ignore it.
4189 // Always treat it as boolean parameter.
4191 // Always treat it as boolean, but inverted.
4195 using GetEditorCommandFunc
= mozilla::EditorCommand
*();
4197 struct InternalCommandData
{
4198 const char* mXULCommandName
;
4199 mozilla::Command mCommand
; // uint8_t
4200 // How ConvertToInternalCommand() to treats aValue.
4201 // Its callers don't need to check this.
4202 ExecCommandParam mExecCommandParam
; // uint8_t
4203 GetEditorCommandFunc
* mGetEditorCommandFunc
;
4204 enum class CommandOnTextEditor
: uint8_t {
4207 FallThrough
, // Not disabled, but handled by HTMLEditor if there is one
4209 CommandOnTextEditor mCommandOnTextEditor
;
4211 InternalCommandData()
4212 : mXULCommandName(nullptr),
4213 mCommand(mozilla::Command::DoNothing
),
4214 mExecCommandParam(ExecCommandParam::Ignore
),
4215 mGetEditorCommandFunc(nullptr),
4216 mCommandOnTextEditor(CommandOnTextEditor::Disabled
) {}
4217 InternalCommandData(const char* aXULCommandName
, mozilla::Command aCommand
,
4218 ExecCommandParam aExecCommandParam
,
4219 GetEditorCommandFunc aGetEditorCommandFunc
,
4220 CommandOnTextEditor aCommandOnTextEditor
)
4221 : mXULCommandName(aXULCommandName
),
4223 mExecCommandParam(aExecCommandParam
),
4224 mGetEditorCommandFunc(aGetEditorCommandFunc
),
4225 mCommandOnTextEditor(aCommandOnTextEditor
) {}
4227 bool IsAvailableOnlyWhenEditable() const {
4228 return mCommand
!= mozilla::Command::Cut
&&
4229 mCommand
!= mozilla::Command::Copy
&&
4230 mCommand
!= mozilla::Command::Paste
&&
4231 mCommand
!= mozilla::Command::SetDocumentReadOnly
&&
4232 mCommand
!= mozilla::Command::SelectAll
;
4234 bool IsCutOrCopyCommand() const {
4235 return mCommand
== mozilla::Command::Cut
||
4236 mCommand
== mozilla::Command::Copy
;
4238 bool IsPasteCommand() const { return mCommand
== mozilla::Command::Paste
; }
4242 * AutoEditorCommandTarget considers which editor or global command manager
4243 * handles given command.
4245 class MOZ_RAII AutoEditorCommandTarget
{
4247 MOZ_CAN_RUN_SCRIPT
AutoEditorCommandTarget(
4248 Document
& aDocument
, const InternalCommandData
& aCommandData
);
4249 AutoEditorCommandTarget() = delete;
4250 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget
& aOther
) =
4253 bool DoNothing() const { return mDoNothing
; }
4254 MOZ_CAN_RUN_SCRIPT
bool IsEditable(Document
* aDocument
) const;
4255 bool IsEditor() const {
4256 MOZ_ASSERT_IF(mEditorCommand
, mActiveEditor
|| mHTMLEditor
);
4257 return !!mEditorCommand
;
4260 MOZ_CAN_RUN_SCRIPT
bool IsCommandEnabled() const;
4261 MOZ_CAN_RUN_SCRIPT nsresult
DoCommand(nsIPrincipal
* aPrincipal
) const;
4262 template <typename ParamType
>
4263 MOZ_CAN_RUN_SCRIPT nsresult
DoCommandParam(const ParamType
& aParam
,
4264 nsIPrincipal
* aPrincipal
) const;
4265 MOZ_CAN_RUN_SCRIPT nsresult
4266 GetCommandStateParams(nsCommandParams
& aParams
) const;
4269 // The returned editor's life is guaranteed while this instance is alive.
4270 EditorBase
* GetTargetEditor() const;
4272 RefPtr
<EditorBase
> mActiveEditor
;
4273 RefPtr
<HTMLEditor
> mHTMLEditor
;
4274 RefPtr
<EditorCommand
> mEditorCommand
;
4275 const InternalCommandData
& mCommandData
;
4276 bool mDoNothing
= false;
4280 * Helper method to initialize sInternalCommandDataHashtable.
4282 static void EnsureInitializeInternalCommandDataHashtable();
4285 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4286 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4287 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4288 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4289 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4290 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4291 * returns a copy of instance created with default constructor. I.e., its
4292 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4293 * is unsupported in such case.
4295 * @param aHTMLCommandName Command name in HTML, e.g., used by
4297 * @param aValue The value which is set to the 3rd parameter
4299 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4300 * Will be set to adjusted value for executing
4301 * the internal command.
4302 * @return Returns a copy of instance created with the
4303 * default constructor if there is no
4304 * corresponding internal command for
4305 * aHTMLCommandName or aValue is invalid for
4306 * found internal command when aAdjustedValue
4307 * is not nullptr. Otherwise, returns a copy of
4308 * instance registered in
4309 * sInternalCommandDataHashtable.
4311 static InternalCommandData
ConvertToInternalCommand(
4312 const nsAString
& aHTMLCommandName
, const nsAString
& aValue
= u
""_ns
,
4313 nsAString
* aAdjustedValue
= nullptr);
4316 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4317 * Since it's a bit field, not a bool member, therefore, we cannot use
4318 * AutoRestorer for it.
4320 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final
{
4322 AutoRunningExecCommandMarker() = delete;
4323 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker
&) =
4325 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4326 MOZ_CAN_RUN_SCRIPT
explicit AutoRunningExecCommandMarker(
4327 Document
& aDocument
)
4328 : mDocument(aDocument
),
4329 mHasBeenRunning(aDocument
.mIsRunningExecCommand
) {
4330 aDocument
.mIsRunningExecCommand
= true;
4332 ~AutoRunningExecCommandMarker() {
4333 if (!mHasBeenRunning
) {
4334 mDocument
.mIsRunningExecCommand
= false;
4339 Document
& mDocument
;
4340 bool mHasBeenRunning
;
4343 // Mapping table from HTML command name to internal command.
4344 using InternalCommandDataHashtable
=
4345 nsTHashMap
<nsStringCaseInsensitiveHashKey
, InternalCommandData
>;
4346 static InternalCommandDataHashtable
* sInternalCommandDataHashtable
;
4348 mutable std::bitset
<static_cast<size_t>(
4349 DeprecatedOperations::eDeprecatedOperationCount
)>
4350 mDeprecationWarnedAbout
;
4351 mutable std::bitset
<eDocumentWarningCount
> mDocWarningWarnedAbout
;
4353 // Lazy-initialization to have mDocGroup initialized in prior to the
4354 UniquePtr
<ServoStyleSet
> mStyleSet
;
4357 // Never ever call this. Only call GetWindow!
4358 nsPIDOMWindowOuter
* GetWindowInternal() const;
4360 // Never ever call this. Only call GetScriptHandlingObject!
4361 nsIScriptGlobalObject
* GetScriptHandlingObjectInternal() const;
4363 // Never ever call this. Only call AllowXULXBL!
4364 bool InternalAllowXULXBL();
4367 * These methods should be called before and after dispatching
4369 * To make this easy and painless, use the mozAutoSubtreeModified helper
4372 void WillDispatchMutationEvent(nsINode
* aTarget
);
4373 void MutationEventDispatched(nsINode
* aTarget
);
4374 friend class mozAutoSubtreeModified
;
4376 virtual Element
* GetNameSpaceElement() override
{ return GetRootElement(); }
4378 nsCString
GetContentTypeInternal() const { return mContentType
; }
4380 // Update our frame request callback scheduling state, if needed. This will
4381 // schedule or unschedule them, if necessary, and update
4382 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4383 // mPresShell is becoming null; in that case it will be used to get hold of
4384 // the relevant refresh driver.
4385 void UpdateFrameRequestCallbackSchedulingState(
4386 PresShell
* aOldPresShell
= nullptr);
4388 // Helper for GetScrollingElement/IsScrollingElement.
4389 bool IsPotentiallyScrollable(HTMLBodyElement
* aBody
);
4391 void MaybeAllowStorageForOpenerAfterUserInteraction();
4393 void MaybeStoreUserInteractionAsPermission();
4395 // Helpers for GetElementsByName.
4396 static bool MatchNameAttribute(Element
* aElement
, int32_t aNamespaceID
,
4397 nsAtom
* aAtom
, void* aData
);
4398 static void* UseExistingNameString(nsINode
* aRootNode
, const nsString
* aName
);
4400 void MaybeResolveReadyForIdle();
4402 using AutomaticStorageAccessPermissionGrantPromise
=
4403 MozPromise
<bool, bool, true>;
4404 [[nodiscard
]] RefPtr
<AutomaticStorageAccessPermissionGrantPromise
>
4405 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation
);
4407 static void AddToplevelLoadingDocument(Document
* aDoc
);
4408 static void RemoveToplevelLoadingDocument(Document
* aDoc
);
4409 static AutoTArray
<Document
*, 8>* sLoadingForegroundTopLevelContentDocument
;
4410 friend class cycleCollection
;
4412 nsCOMPtr
<nsIReferrerInfo
> mPreloadReferrerInfo
;
4413 nsCOMPtr
<nsIReferrerInfo
> mReferrerInfo
;
4415 nsString mLastModified
;
4417 nsCOMPtr
<nsIURI
> mDocumentURI
;
4418 nsCOMPtr
<nsIURI
> mOriginalURI
;
4419 nsCOMPtr
<nsIURI
> mChromeXHRDocURI
;
4420 nsCOMPtr
<nsIURI
> mDocumentBaseURI
;
4421 nsCOMPtr
<nsIURI
> mChromeXHRDocBaseURI
;
4423 // The base domain of the document for third-party checks.
4424 nsCString mBaseDomain
;
4426 // A lazily-constructed URL data for style system to resolve URL values.
4427 RefPtr
<URLExtraData
> mCachedURLData
;
4428 nsCOMPtr
<nsIReferrerInfo
> mCachedReferrerInfoForInternalCSSAndSVGResources
;
4430 nsWeakPtr mDocumentLoadGroup
;
4432 WeakPtr
<nsDocShell
> mDocumentContainer
;
4434 NotNull
<const Encoding
*> mCharacterSet
;
4435 int32_t mCharacterSetSource
;
4437 OriginTrials mTrials
;
4439 // This is just a weak pointer; the parent document owns its children.
4440 Document
* mParentDocument
;
4442 // A reference to the element last returned from GetRootElement().
4443 Element
* mCachedRootElement
;
4445 // This is maintained by AutoSetRestoreSVGContextPaint.
4446 const SVGContextPaint
* mCurrentContextPaint
= nullptr;
4448 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4449 // which in turn holds a strong reference to this mNodeInfoManager.
4450 nsNodeInfoManager
* mNodeInfoManager
;
4451 RefPtr
<css::Loader
> mCSSLoader
;
4452 RefPtr
<css::ImageLoader
> mStyleImageLoader
;
4454 // The object that contains link color declarations (from the <body> mapped
4455 // attributes), mapped attribute caches, and inline style attribute caches.
4456 RefPtr
<AttributeStyles
> mAttributeStyles
;
4458 // Tracking for images in the document.
4459 RefPtr
<dom::ImageTracker
> mImageTracker
;
4461 // A hashtable of ShadowRoots belonging to the composed doc.
4463 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4464 ShadowRootSet mComposedShadowRoots
;
4466 using SVGUseElementSet
= nsTHashSet
<SVGUseElement
*>;
4468 // The set of <svg:use> elements that need a shadow tree reclone because the
4469 // tree they map to has changed.
4470 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate
;
4472 // The set of all object, embed, video/audio elements or
4473 // nsIObjectLoadingContent or DocumentActivity for which this is
4474 // the owner document. (They might not be in the document.)
4476 // These are non-owning pointers, the elements are responsible for removing
4477 // themselves when they go away.
4478 UniquePtr
<nsTHashSet
<nsISupports
*>> mActivityObservers
;
4480 // A hashtable of styled links keyed by address pointer.
4481 nsTHashSet
<Link
*> mStyledLinks
;
4483 // Indicates whether mStyledLinks was cleared or not. This is used to track
4484 // state so we can provide useful assertions to consumers of ForgetLink and
4485 // AddStyleRelevantLink.
4486 bool mStyledLinksCleared
;
4489 // The array of all links that need their status resolved. Links must add
4490 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4492 static const size_t kSegmentSize
= 128;
4494 using LinksToUpdateList
=
4495 SegmentedVector
<nsCOMPtr
<Link
>, kSegmentSize
, InfallibleAllocPolicy
>;
4497 LinksToUpdateList mLinksToUpdate
;
4499 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4500 RefPtr
<SMILAnimationController
> mAnimationController
;
4502 // Table of element properties for this document.
4503 nsPropertyTable mPropertyTable
;
4505 // Our cached .children collection
4506 nsCOMPtr
<nsIHTMLCollection
> mChildrenCollection
;
4508 // Various DOM lists
4509 RefPtr
<nsContentList
> mImages
;
4510 RefPtr
<nsContentList
> mEmbeds
;
4511 RefPtr
<nsContentList
> mLinks
;
4512 RefPtr
<nsContentList
> mForms
;
4513 RefPtr
<nsContentList
> mScripts
;
4514 nsCOMPtr
<nsIHTMLCollection
> mApplets
;
4515 RefPtr
<nsContentList
> mAnchors
;
4517 // container for per-context fonts (downloadable, SVG, etc.)
4518 RefPtr
<FontFaceSet
> mFontFaceSet
;
4520 // Last time this document or a one of its sub-documents was focused. If
4521 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4522 TimeStamp mLastFocusTime
;
4524 // Last time we found any scroll linked effect in this document.
4525 TimeStamp mLastScrollLinkedEffectDetectionTime
;
4527 DocumentState mDocumentState
{DocumentState::LTR_LOCALE
};
4529 RefPtr
<Promise
> mReadyForIdle
;
4531 RefPtr
<mozilla::dom::FeaturePolicy
> mFeaturePolicy
;
4533 // Permission Delegate Handler, lazily-initialized in
4534 // GetPermissionDelegateHandler
4535 RefPtr
<PermissionDelegateHandler
> mPermissionDelegateHandler
;
4537 bool mCachedStateObjectValid
: 1;
4538 bool mBlockAllMixedContent
: 1;
4539 bool mBlockAllMixedContentPreloads
: 1;
4540 bool mUpgradeInsecureRequests
: 1;
4541 bool mUpgradeInsecurePreloads
: 1;
4542 bool mDevToolsWatchingDOMMutations
: 1;
4544 // True if BIDI is enabled.
4545 bool mBidiEnabled
: 1;
4546 // True if we may need to recompute the language prefs for this document.
4547 bool mMayNeedFontPrefsUpdate
: 1;
4548 // True if a MathML element has ever been owned by this document.
4549 bool mMathMLEnabled
: 1;
4551 // True if this document is the initial document for a window. This should
4552 // basically be true only for documents that exist in newly-opened windows or
4553 // documents created to satisfy a GetDocument() on a window when there's no
4555 bool mIsInitialDocumentInWindow
: 1;
4557 bool mIgnoreDocGroupMismatches
: 1;
4559 // True if we're loaded as data and therefor has any dangerous stuff, such
4560 // as scripts and plugins, disabled.
4561 bool mLoadedAsData
: 1;
4563 // True if the document is considered for memory reporting as a
4565 bool mAddedToMemoryReportingAsDataDocument
: 1;
4567 // If true, whoever is creating the document has gotten it to the
4568 // point where it's safe to start layout on it.
4569 bool mMayStartLayout
: 1;
4571 // True iff we've ever fired a DOMTitleChanged event for this document
4572 bool mHaveFiredTitleChange
: 1;
4574 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4575 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4576 // before the initial load completes and when we're in bfcache or unloaded,
4578 bool mIsShowing
: 1;
4580 // State for IsVisible(). mVisible starts off true. It becomes false when
4581 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4582 // it's false only when we're in bfcache or unloaded.
4585 // True if our content viewer has been removed from the docshell
4586 // (it may still be displayed, but in zombie state). Form control data
4588 bool mRemovedFromDocShell
: 1;
4590 // True iff DNS prefetch is allowed for this document. Note that if the
4591 // document has no window, DNS prefetch won't be performed no matter what.
4592 bool mAllowDNSPrefetch
: 1;
4594 // True when this document is a static clone of a normal document
4595 bool mIsStaticDocument
: 1;
4597 // True while this document is being cloned to a static document.
4598 bool mCreatingStaticClone
: 1;
4600 // True if this static document has any <canvas> element with a
4601 // mozPrintCallback property at the time of the clone.
4602 bool mHasPrintCallbacks
: 1;
4604 // True iff the document is being unlinked or deleted.
4605 bool mInUnlinkOrDeletion
: 1;
4607 // True if document has ever had script handling object.
4608 bool mHasHadScriptHandlingObject
: 1;
4610 // True if we're an SVG document being used as an image.
4611 bool mIsBeingUsedAsImage
: 1;
4613 // True if our current document URI's scheme enables privileged CSS rules.
4614 bool mChromeRulesEnabled
: 1;
4616 // True if we're loaded in a chrome docshell.
4617 bool mInChromeDocShell
: 1;
4619 // True if our current document is a DevTools document. Either the url is
4620 // about:devtools-toolbox or the parent document already has
4621 // mIsDevToolsDocument set to true.
4622 // This is used to avoid applying High Contrast mode to DevTools documents.
4624 bool mIsDevToolsDocument
: 1;
4626 // True is this document is synthetic : stand alone image, video, audio
4628 bool mIsSyntheticDocument
: 1;
4630 // True is there is a pending runnable which will call
4631 // FlushPendingLinkUpdates().
4632 bool mHasLinksToUpdateRunnable
: 1;
4634 // True if we're flushing pending link updates.
4635 bool mFlushingPendingLinkUpdates
: 1;
4637 // True if a DOMMutationObserver is perhaps attached to a node in the
4639 bool mMayHaveDOMMutationObservers
: 1;
4641 // True if an nsIAnimationObserver is perhaps attached to a node in the
4643 bool mMayHaveAnimationObservers
: 1;
4645 // True if the document has a CSP delivered throuh a header
4646 bool mHasCSPDeliveredThroughHeader
: 1;
4648 // True if DisallowBFCaching has been called on this document.
4649 bool mBFCacheDisallowed
: 1;
4651 bool mHasHadDefaultView
: 1;
4653 // Whether style sheet change events will be dispatched for this document
4654 bool mStyleSheetChangeEventsEnabled
: 1;
4656 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4657 // will be dispatched for this document.
4658 bool mDevToolsAnonymousAndShadowEventsEnabled
: 1;
4660 // Whether the document was created by a srcdoc iframe.
4661 bool mIsSrcdocDocument
: 1;
4663 // Whether this document has a display document and thus is considered to
4664 // be a resource document. Normally this is the same as !!mDisplayDocument,
4665 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4666 // valid in the document's destructor.
4667 bool mHasDisplayDocument
: 1;
4669 // Is the current mFontFaceSet valid?
4670 bool mFontFaceSetDirty
: 1;
4672 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4673 // (e.g. we're not being parsed at all).
4674 bool mDidFireDOMContentLoaded
: 1;
4676 // True if we have frame request callbacks scheduled with the refresh driver.
4677 // This should generally be updated only via
4678 // UpdateFrameRequestCallbackSchedulingState.
4679 bool mFrameRequestCallbacksScheduled
: 1;
4681 bool mIsTopLevelContentDocument
: 1;
4683 bool mIsContentDocument
: 1;
4685 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4686 bool mDidCallBeginLoad
: 1;
4688 // True if the encoding menu should be disabled.
4689 bool mEncodingMenuDisabled
: 1;
4691 // False if we've disabled link handling for elements inside this document,
4693 bool mLinksEnabled
: 1;
4695 // True if this document is for an SVG-in-OpenType font.
4696 bool mIsSVGGlyphsDocument
: 1;
4698 // True if the document is being destroyed.
4699 bool mInDestructor
: 1;
4701 // True if the document has been detached from its content viewer.
4702 bool mIsGoingAway
: 1;
4704 bool mInXBLUpdate
: 1;
4706 // Whether we have filled our style set with all the stylesheets.
4707 bool mStyleSetFilled
: 1;
4709 // Whether we have a quirks mode stylesheet in the style set.
4710 bool mQuirkSheetAdded
: 1;
4712 // Whether we have a contenteditable.css stylesheet in the style set.
4713 bool mContentEditableSheetAdded
: 1;
4715 // Whether we have a designmode.css stylesheet in the style set.
4716 bool mDesignModeSheetAdded
: 1;
4718 // True if this document has ever had an HTML or SVG <title> element
4720 bool mMayHaveTitleElement
: 1;
4722 bool mDOMLoadingSet
: 1;
4723 bool mDOMInteractiveSet
: 1;
4724 bool mDOMCompleteSet
: 1;
4725 bool mAutoFocusFired
: 1;
4727 bool mScrolledToRefAlready
: 1;
4728 bool mChangeScrollPosWhenScrollingToRef
: 1;
4730 bool mDelayFrameLoaderInitialization
: 1;
4732 bool mSynchronousDOMContentLoaded
: 1;
4734 // Set to true when the document is possibly controlled by the ServiceWorker.
4735 // Used to prevent multiple requests to ServiceWorkerManager.
4736 bool mMaybeServiceWorkerControlled
: 1;
4738 // These member variables cache information about the viewport so we don't
4739 // have to recalculate it each time.
4740 bool mAllowZoom
: 1;
4741 bool mValidScaleFloat
: 1;
4742 bool mValidMinScale
: 1;
4743 bool mValidMaxScale
: 1;
4744 bool mWidthStrEmpty
: 1;
4746 // Parser aborted. True if the parser of this document was forcibly
4747 // terminated instead of letting it finish at its own pace.
4748 bool mParserAborted
: 1;
4750 // Whether we have reported document use counters for this document with
4751 // Telemetry yet. Normally this is only done at document destruction time,
4752 // but for image documents (SVG documents) that are not guaranteed to be
4753 // destroyed, we report use counters when the image cache no longer has any
4754 // imgRequestProxys pointing to them. We track whether we ever reported use
4755 // counters so that we only report them once for the document.
4756 bool mReportedDocumentUseCounters
: 1;
4758 bool mHasReportedShadowDOMUsage
: 1;
4760 // Whether an event triggered by the refresh driver was delayed because this
4761 // document has suppressed events.
4762 bool mHasDelayedRefreshEvent
: 1;
4764 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4765 // to have the right semantics. See
4766 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4767 // flag that is set while the window's 'load' event is firing if this document
4768 // is the window's document.
4769 bool mLoadEventFiring
: 1;
4771 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4772 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4773 // What we have instead is a flag that is set if completion of our document
4774 // via document.close() should skip firing the load event. Note that this
4775 // flag is only relevant for HTML documents, but lives here for reasons that
4776 // are documented above on SkipLoadEventAfterClose().
4777 bool mSkipLoadEventAfterClose
: 1;
4779 // When false, the .cookies property is completely disabled
4780 bool mDisableCookieAccess
: 1;
4782 // When false, the document.write() API is disabled.
4783 bool mDisableDocWrite
: 1;
4785 // Has document.write() been called with a recursion depth higher than
4787 bool mTooDeepWriteRecursion
: 1;
4790 * Temporary flag that is set in EndUpdate() to ignore
4791 * MaybeEditingStateChanged() script runners from a nested scope.
4793 bool mPendingMaybeEditingStateChanged
: 1;
4795 // mHasBeenEditable is set to true when mEditingState is firstly set to
4796 // eDesignMode or eContentEditable.
4797 bool mHasBeenEditable
: 1;
4799 // Whether we've warned about the CSS zoom property.
4801 // We don't use the general deprecated operation mechanism for this because we
4802 // also record this as a `CountedUnknownProperty`.
4803 bool mHasWarnedAboutZoom
: 1;
4805 // While we're handling an execCommand call, set to true.
4806 bool mIsRunningExecCommand
: 1;
4808 // True if we should change the readystate to complete after we fire
4809 // DOMContentLoaded. This happens when we abort a load and
4810 // nsDocumentViewer::EndLoad runs while we still have things blocking
4811 // DOMContentLoaded. We wait for those to complete, and then update the
4812 // readystate when they finish.
4813 bool mSetCompleteAfterDOMContentLoaded
: 1;
4815 // Set the true if a completed cached stylesheet was created for the document.
4816 bool mDidHitCompleteSheetCache
: 1;
4818 // Whether we have initialized mShouldReportUseCounters and
4819 // mShouldSendPageUseCounters, and sent any needed message to the parent
4820 // process to indicate that use counter data will be sent at some later point.
4821 bool mUseCountersInitialized
: 1;
4823 // Whether this document should report use counters.
4824 bool mShouldReportUseCounters
: 1;
4826 // Whether this document should send page use counters. Set to true after
4827 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4828 bool mShouldSendPageUseCounters
: 1;
4830 // Whether the user has interacted with the document or not:
4831 bool mUserHasInteracted
: 1;
4833 // We constantly update the user-interaction anti-tracking permission at any
4834 // user-interaction using a timer. This boolean value is set to true when this
4835 // timer is scheduled.
4836 bool mHasUserInteractionTimerScheduled
: 1;
4838 // Whether we should resist fingerprinting.
4839 bool mShouldResistFingerprinting
: 1;
4841 // Whether we're cloning the contents of an SVG use element.
4842 bool mCloningForSVGUse
: 1;
4844 uint8_t mXMLDeclarationBits
;
4846 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4847 // use uint8_t to avoid having to include a bunch of style system headers
4849 uint8_t mColorSchemeBits
= 0;
4851 // Currently active onload blockers.
4852 uint32_t mOnloadBlockCount
;
4854 // Tracks if we are currently processing any document.write calls (either
4855 // implicit or explicit). Note that if a write call writes out something which
4856 // would block the parser, then mWriteLevel will be incorrect until the parser
4857 // finishes processing that script.
4858 uint32_t mWriteLevel
;
4860 uint32_t mContentEditableCount
;
4861 EditingState mEditingState
;
4863 // Compatibility mode
4864 nsCompatibility mCompatMode
;
4867 ReadyState mReadyState
;
4869 // Ancestor's loading state
4870 bool mAncestorIsLoading
;
4872 // Our visibility state
4873 dom::VisibilityState mVisibilityState
;
4876 eUnknown
, // should never be used
4885 uint8_t mDefaultElementType
;
4887 enum Tri
{ eTriUnset
= 0, eTriFalse
, eTriTrue
};
4891 bool mSkipDTDSecurityChecks
;
4893 // The document's script global object, the object from which the
4894 // document can get its script context and scope. This is the
4895 // *inner* window object.
4896 nsCOMPtr
<nsIScriptGlobalObject
> mScriptGlobalObject
;
4898 // If mIsStaticDocument is true, mOriginalDocument points to the original
4900 RefPtr
<Document
> mOriginalDocument
;
4902 // The bidi options for this document. What this bitfield means is
4903 // defined in nsBidiUtils.h
4904 uint32_t mBidiOptions
;
4906 // The sandbox flags on the document. These reflect the value of the sandbox
4907 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4908 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4910 uint32_t mSandboxFlags
;
4912 // The embedder policy obtained from parsing the HTTP response header or from
4913 // our opener if this is the initial about:blank document.
4914 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> mEmbedderPolicy
;
4916 nsCString mContentLanguage
;
4918 // The channel that got passed to Document::StartDocumentLoad(), if any.
4919 nsCOMPtr
<nsIChannel
> mChannel
;
4921 // The CSP for every load lives in the Client within the LoadInfo. For all
4922 // document-initiated subresource loads we can use that cached version of the
4923 // CSP so we do not have to deserialize the CSP from the Client all the time.
4924 nsCOMPtr
<nsIContentSecurityPolicy
> mCSP
;
4925 nsCOMPtr
<nsIContentSecurityPolicy
> mPreloadCSP
;
4928 nsCString mContentType
;
4931 // The document's security info
4932 nsCOMPtr
<nsITransportSecurityInfo
> mSecurityInfo
;
4934 // The channel that failed to load and resulted in an error page.
4935 // This only applies to error pages. Might be null.
4936 nsCOMPtr
<nsIChannel
> mFailedChannel
;
4938 // if this document is part of a multipart document,
4939 // the ID can be used to distinguish it from the other parts.
4942 // Cycle collector generation in which we're certain that this document
4943 // won't be collected
4944 uint32_t mMarkedCCGeneration
;
4946 PresShell
* mPresShell
;
4948 nsCOMArray
<nsINode
> mSubtreeModifiedTargets
;
4949 uint32_t mSubtreeModifiedDepth
;
4951 // All images in process of being preloaded. This is a hashtable so
4952 // we can remove them as the real image loads start; that way we
4953 // make sure to not keep the image load going when no one cares
4954 // about it anymore.
4955 nsRefPtrHashtable
<nsURIHashKey
, imgIRequest
> mPreloadingImages
;
4957 // A list of preconnects initiated by the preloader. This prevents
4958 // the same uri from being used more than once, and allows the dom
4959 // builder to not repeat the work of the preloader.
4960 nsTHashMap
<nsURIHashKey
, bool> mPreloadedPreconnects
;
4962 // Current depth of picture elements from parser
4963 uint32_t mPreloadPictureDepth
;
4965 // Set if we've found a URL for the current picture
4966 nsString mPreloadPictureFoundSource
;
4968 // If we're an external resource document, this will be non-null and will
4969 // point to our "display document": the one that all resource lookups should
4971 RefPtr
<Document
> mDisplayDocument
;
4973 uint32_t mEventsSuppressed
;
4975 // Any XHR ChannelEventQueues that were suspended on this document while
4976 // events were suppressed.
4977 nsTArray
<RefPtr
<net::ChannelEventQueue
>> mSuspendedQueues
;
4979 // Any postMessage events that were suspended on this document while events
4981 nsTArray
<RefPtr
<PostMessageEvent
>> mSuspendedPostMessageEvents
;
4983 RefPtr
<EventListener
> mSuppressedEventListener
;
4986 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
4988 uint32_t mIgnoreDestructiveWritesCounter
;
4990 // Count of live static clones of this document.
4991 uint32_t mStaticCloneCount
;
4993 // If the document is currently printing (or in print preview) this will point
4994 // to the current static clone of this document. This is weak since the clone
4995 // also has a reference to this document.
4996 WeakPtr
<Document
> mLatestStaticClone
;
4998 // Array of nodes that have been blocked to prevent user tracking.
4999 // They most likely have had their nsIChannel canceled by the URL
5000 // classifier. (Safebrowsing)
5002 // Weak nsINode pointers are used to allow nodes to disappear.
5003 nsTArray
<nsWeakPtr
> mBlockedNodesByClassifier
;
5005 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5006 // updated on every set of mScriptGlobalObject.
5007 nsPIDOMWindowInner
* mWindow
;
5009 nsCOMPtr
<nsIDocumentEncoder
> mCachedEncoder
;
5011 FrameRequestManager mFrameRequestManager
;
5013 // This object allows us to evict ourself from the back/forward cache. The
5014 // pointer is non-null iff we're currently in the bfcache.
5015 nsIBFCacheEntry
* mBFCacheEntry
;
5018 nsString mBaseTarget
;
5020 nsCOMPtr
<nsIStructuredCloneContainer
> mStateObjectContainer
;
5021 JS::Heap
<JS::Value
> mCachedStateObject
;
5023 uint32_t mInSyncOperationCount
;
5025 UniquePtr
<dom::XPathEvaluator
> mXPathEvaluator
;
5027 nsTArray
<RefPtr
<AnonymousContent
>> mAnonymousContents
;
5029 uint32_t mBlockDOMContentLoaded
;
5031 // Our live MediaQueryLists
5032 LinkedList
<MediaQueryList
> mDOMMediaQueryLists
;
5034 // Array of observers
5035 nsTObserverArray
<nsIDocumentObserver
*> mObservers
;
5037 // Flags for use counters used directly by this document.
5038 UseCounters mUseCounters
;
5039 // Flags for use counters from resource documents, static clones,
5040 // and SVG images referenced by this document. Those documents propagate
5041 // their use counters up to here, which then count towards the top-level
5042 // document's page use counters.
5043 UseCounters mChildDocumentUseCounters
;
5045 // The CSS property use counters.
5046 UniquePtr
<StyleUseCounters
> mStyleUseCounters
;
5048 TimeStamp mPageUnloadingEventTimeStamp
;
5050 RefPtr
<DocGroup
> mDocGroup
;
5052 RefPtr
<nsCommandManager
> mMidasCommandManager
;
5054 // The set of all the tracking script URLs. URLs are added to this set by
5055 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5056 // existing in the set means the corresponding script isn't a tracking script.
5057 nsTHashSet
<nsCString
> mTrackingScripts
;
5059 // Pointer to our parser if we're currently in the process of being
5061 nsCOMPtr
<nsIParser
> mParser
;
5063 // If the document was created from the the prototype cache there will be a
5064 // reference to the prototype document to allow tracing.
5065 RefPtr
<nsXULPrototypeDocument
> mPrototypeDocument
;
5067 // Weak reference to our sink for in case we no longer have a parser. This
5068 // will allow us to flush out any pending stuff from the sink even if
5069 // EndLoad() has already happened.
5070 nsWeakPtr mWeakSink
;
5072 // Our update nesting level
5073 uint32_t mUpdateNestLevel
;
5075 // HTTPS-Only Mode Status
5076 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5077 uint32_t mHttpsOnlyStatus
;
5079 enum ViewportType
: uint8_t {
5085 ViewportType mViewportType
;
5087 // viewport-fit described by
5088 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5089 ViewportFitType mViewportFit
;
5091 PLDHashTable
* mSubDocuments
;
5094 UniquePtr
<HeaderData
> mHeaderData
;
5096 nsTArray
<net::EarlyHintConnectArgs
> mEarlyHints
;
5098 nsRevocableEventPtr
<nsRunnableMethod
<Document
, void, false>>
5099 mPendingTitleChangeEvent
;
5101 RefPtr
<nsDOMNavigationTiming
> mTiming
;
5103 // Recorded time of change to 'loading' state
5104 // or time of the page gets restored from BFCache.
5105 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp
;
5107 // Decided to use nsTObserverArray because it allows us to
5108 // remove candidates while iterating them and this is what
5109 // the spec defines. We could implement the spec without
5110 // using nsTObserverArray, however using nsTObserverArray is more clear.
5111 nsTObserverArray
<nsWeakPtr
> mAutoFocusCandidates
;
5113 nsCString mScrollToRef
;
5115 // Weak reference to the scope object (aka the script global object)
5116 // that, unlike mScriptGlobalObject, is never unset once set. This
5117 // is a weak reference to avoid leaks due to circular references.
5118 nsWeakPtr mScopeObject
;
5120 // Array of intersection observers
5121 nsTHashSet
<DOMIntersectionObserver
*> mIntersectionObservers
;
5123 // Array of resize observers
5124 nsTArray
<ResizeObserver
*> mResizeObservers
;
5126 RefPtr
<DOMIntersectionObserver
> mLazyLoadImageObserver
;
5127 // Used to measure how effective the lazyload thresholds are.
5128 RefPtr
<DOMIntersectionObserver
> mLazyLoadImageObserverViewport
;
5130 // Used for detecting when `content-visibility: auto` elements are near
5131 // or far from the viewport.
5132 RefPtr
<DOMIntersectionObserver
> mContentVisibilityObserver
;
5134 // ResizeObserver for storing and removing the last remembered size.
5135 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5136 RefPtr
<ResizeObserver
> mLastRememberedSizeObserver
;
5138 // Stack of top layer elements.
5139 nsTArray
<nsWeakPtr
> mTopLayer
;
5141 // The root of the doc tree in which this document is in. This is only
5142 // non-null when this document is in fullscreen mode.
5143 nsWeakPtr mFullscreenRoot
;
5145 RefPtr
<DOMImplementation
> mDOMImplementation
;
5147 RefPtr
<nsContentList
> mImageMaps
;
5149 // A set of responsive images keyed by address pointer.
5150 nsTHashSet
<HTMLImageElement
*> mResponsiveContent
;
5152 RefPtr
<DocumentTimeline
> mDocumentTimeline
;
5153 LinkedList
<DocumentTimeline
> mTimelines
;
5155 RefPtr
<dom::ScriptLoader
> mScriptLoader
;
5157 // Tracker for animations that are waiting to start.
5158 // nullptr until GetOrCreatePendingAnimationTracker is called.
5159 RefPtr
<PendingAnimationTracker
> mPendingAnimationTracker
;
5161 // Tracker for scroll-driven animations that are waiting to start.
5162 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5163 RefPtr
<ScrollTimelineAnimationTracker
> mScrollTimelineAnimationTracker
;
5165 // A document "without a browsing context" that owns the content of
5166 // HTMLTemplateElement.
5167 RefPtr
<Document
> mTemplateContentsOwner
;
5169 dom::ExternalResourceMap mExternalResourceMap
;
5171 // ScreenOrientation "pending promise" as described by
5172 // http://www.w3.org/TR/screen-orientation/
5173 RefPtr
<Promise
> mOrientationPendingPromise
;
5175 nsTArray
<RefPtr
<nsFrameLoader
>> mInitializableFrameLoaders
;
5176 nsTArray
<nsCOMPtr
<nsIRunnable
>> mFrameLoaderFinalizers
;
5177 RefPtr
<nsRunnableMethod
<Document
>> mFrameLoaderRunner
;
5179 nsTArray
<PendingFrameStaticClone
> mPendingFrameStaticClones
;
5181 // The layout history state that should be used by nodes in this
5182 // document. We only actually store a pointer to it when:
5183 // 1) We have no script global object.
5184 // 2) We haven't had Destroy() called on us yet.
5185 nsCOMPtr
<nsILayoutHistoryState
> mLayoutHistoryState
;
5187 // The parsed viewport metadata of the last modified <meta name=viewport>
5189 UniquePtr
<ViewportMetaData
> mLastModifiedViewportMetaData
;
5191 // A tree ordered list of all color-scheme meta tags in this document.
5193 // TODO(emilio): There are other meta tags in the spec that have a similar
5194 // processing model to color-scheme. We could store all in-document meta tags
5195 // here to get sane and fast <meta> element processing.
5196 TreeOrderedArray
<HTMLMetaElement
> mColorSchemeMetaTags
;
5198 // These member variables cache information about the viewport so we don't
5199 // have to recalculate it each time.
5200 LayoutDeviceToScreenScale mScaleMinFloat
;
5201 LayoutDeviceToScreenScale mScaleMaxFloat
;
5202 LayoutDeviceToScreenScale mScaleFloat
;
5203 CSSToLayoutDeviceScale mPixelRatio
;
5207 CSSCoord mMinHeight
;
5208 CSSCoord mMaxHeight
;
5210 RefPtr
<EventListenerManager
> mListenerManager
;
5212 nsCOMPtr
<nsIRequest
> mOnloadBlocker
;
5214 // Gecko-internal sheets used for extensions and such.
5215 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5216 nsTArray
<RefPtr
<StyleSheet
>> mAdditionalSheets
[AdditionalSheetTypeCount
];
5218 // Member to store out last-selected stylesheet set.
5219 nsString mLastStyleSheetSet
;
5220 nsString mPreferredStyleSheetSet
;
5222 RefPtr
<DOMStyleSheetSetList
> mStyleSheetSetList
;
5224 // We lazily calculate declaration blocks for elements with mapped
5225 // attributes. This set contains all elements which need lazy resolution.
5226 nsTHashSet
<Element
*> mLazyPresElements
;
5228 nsTHashSet
<RefPtr
<nsAtom
>> mLanguagesUsed
;
5230 // TODO(emilio): Is this hot enough to warrant to be cached?
5231 RefPtr
<nsAtom
> mLanguageFromCharset
;
5233 // Restyle root for servo's style system.
5235 // We store this as an nsINode, rather than as an Element, so that we can
5236 // store the Document node as the restyle root if the entire document (along
5237 // with all document-level native-anonymous content) needs to be restyled.
5239 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5240 // root corresponds to.
5241 nsCOMPtr
<nsINode
> mServoRestyleRoot
;
5242 uint32_t mServoRestyleRootDirtyBits
;
5244 // Used in conjunction with the create-an-element-for-the-token algorithm to
5245 // prevent custom element constructors from being able to use document.open(),
5246 // document.close(), and document.write() when they are invoked by the parser.
5247 uint32_t mThrowOnDynamicMarkupInsertionCounter
;
5249 // Count of unload/beforeunload/pagehide operations in progress.
5250 uint32_t mIgnoreOpensDuringUnloadCounter
;
5252 nsCOMPtr
<nsIDOMXULCommandDispatcher
>
5253 mCommandDispatcher
; // [OWNER] of the focus tracker
5255 RefPtr
<XULBroadcastManager
> mXULBroadcastManager
;
5256 RefPtr
<XULPersist
> mXULPersist
;
5257 RefPtr
<ChromeObserver
> mChromeObserver
;
5259 RefPtr
<HTMLAllCollection
> mAll
;
5261 nsTHashSet
<RefPtr
<WorkerDocumentListener
>> mWorkerListeners
;
5263 // Pres shell resolution saved before entering fullscreen mode.
5264 float mSavedResolution
;
5266 // Pres shell resolution saved before creating a MobileViewportManager.
5267 float mSavedResolutionBeforeMVM
;
5269 nsCOMPtr
<nsICookieJarSettings
> mCookieJarSettings
;
5271 bool mHasStoragePermission
;
5273 // Document generation. Gets incremented everytime it changes.
5274 int32_t mGeneration
;
5276 // Cached TabSizes values for the document.
5277 int32_t mCachedTabSizeGeneration
;
5278 nsTabSizes mCachedTabSizes
;
5280 // This is equal to document's principal but with an isolation key. See
5281 // StoragePrincipalHelper.h to know more.
5282 nsCOMPtr
<nsIPrincipal
> mPartitionedPrincipal
;
5284 // The cached storage principal for this document.
5285 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5286 // which is required due to its CloneDocHelper() call site. :-(
5287 mutable nsCOMPtr
<nsIPrincipal
> mActiveStoragePrincipal
;
5289 // The cached cookie principal for this document.
5290 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5291 // which is required due to its CloneDocHelper() call site. :-(
5292 mutable nsCOMPtr
<nsIPrincipal
> mActiveCookiePrincipal
;
5294 // See GetNextFormNumber and GetNextControlNumber.
5295 int32_t mNextFormNumber
;
5296 int32_t mNextControlNumber
;
5298 uint32_t mMediaElementWithMSECount
= 0;
5300 // Scope preloads per document. This is used by speculative loading as well.
5301 PreloadService mPreloadService
;
5303 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5304 bool mShouldNotifyFetchSuccess
;
5306 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5307 bool mShouldNotifyFormOrPasswordRemoved
;
5309 // Record page load telemetry
5310 void RecordPageLoadEventTelemetry(
5311 glean::perf::PageLoadExtra
& aEventTelemetryData
);
5313 // Accumulate JS telemetry collected
5314 void AccumulateJSTelemetry(
5315 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5317 // Accumulate page load metrics
5318 void AccumulatePageLoadTelemetry(
5319 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5321 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5322 // Not holding strong refs here since we don't actually use the BBCs.
5323 nsTArray
<const BrowserBridgeChild
*> mOOPChildrenLoading
;
5325 // Registry of custom highlight definitions associated with this document.
5326 RefPtr
<class HighlightRegistry
> mHighlightRegistry
;
5328 UniquePtr
<RadioGroupContainer
> mRadioGroupContainer
;
5331 // Needs to be public because the bindings code pokes at it.
5332 JS::ExpandoAndGeneration mExpandoAndGeneration
;
5334 bool HasPendingInitialTranslation();
5336 nsRefPtrHashtable
<nsRefPtrHashKey
<Element
>, nsXULPrototypeElement
>
5339 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM
; }
5340 void SetSavedResolutionBeforeMVM(float aResolution
) {
5341 mSavedResolutionBeforeMVM
= aResolution
;
5344 void LoadEventFired();
5346 RadioGroupContainer
& OwnedRadioGroupContainer();
5349 NS_DEFINE_STATIC_IID_ACCESSOR(Document
, NS_IDOCUMENT_IID
)
5352 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5353 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5354 * object is deleted.
5356 class MOZ_STACK_CLASS mozAutoSubtreeModified
{
5359 * @param aSubTreeOwner The document in which a subtree will be modified.
5360 * @param aTarget The target of the possible DOMSubtreeModified event.
5361 * Can be nullptr, in which case mozAutoSubtreeModified
5362 * is just used to batch DOM mutations.
5364 mozAutoSubtreeModified(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5365 UpdateTarget(aSubtreeOwner
, aTarget
);
5368 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5370 void UpdateTarget(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5371 if (mSubtreeOwner
) {
5372 mSubtreeOwner
->MutationEventDispatched(mTarget
);
5376 mSubtreeOwner
= aSubtreeOwner
;
5377 if (mSubtreeOwner
) {
5378 mSubtreeOwner
->WillDispatchMutationEvent(mTarget
);
5383 nsCOMPtr
<nsINode
> mTarget
;
5384 RefPtr
<Document
> mSubtreeOwner
;
5387 enum class SyncOperationBehavior
{ eSuspendInput
, eAllowInput
};
5389 class AutoWalkBrowsingContextGroup
{
5391 virtual ~AutoWalkBrowsingContextGroup() = default;
5394 void SuppressBrowsingContext(BrowsingContext
* aContext
);
5395 void SuppressBrowsingContextGroup(BrowsingContextGroup
* aGroup
);
5396 void UnsuppressDocuments() {
5397 for (const auto& doc
: mDocuments
) {
5398 UnsuppressDocument(doc
);
5401 virtual void SuppressDocument(Document
* aDocument
) = 0;
5402 virtual void UnsuppressDocument(Document
* aDocument
) = 0;
5403 AutoTArray
<RefPtr
<Document
>, 16> mDocuments
;
5406 class MOZ_RAII nsAutoSyncOperation
: private AutoWalkBrowsingContextGroup
{
5408 explicit nsAutoSyncOperation(Document
* aDocument
,
5409 SyncOperationBehavior aSyncBehavior
);
5410 ~nsAutoSyncOperation();
5413 void SuppressDocument(Document
* aDocument
) override
;
5414 void UnsuppressDocument(Document
* aDocument
) override
;
5417 uint32_t mMicroTaskLevel
;
5418 const SyncOperationBehavior mSyncBehavior
;
5419 RefPtr
<BrowsingContext
> mBrowsingContext
;
5422 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final
{
5424 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document
* aDocument
)
5425 : mDocument(aDocument
) {
5426 mDocument
->IncrementThrowOnDynamicMarkupInsertionCounter();
5429 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5430 mDocument
->DecrementThrowOnDynamicMarkupInsertionCounter();
5434 Document
* mDocument
;
5437 class MOZ_RAII IgnoreOpensDuringUnload final
{
5439 explicit IgnoreOpensDuringUnload(Document
* aDoc
) : mDoc(aDoc
) {
5440 mDoc
->IncrementIgnoreOpensDuringUnloadCounter();
5443 ~IgnoreOpensDuringUnload() {
5444 mDoc
->DecrementIgnoreOpensDuringUnloadCounter();
5451 bool IsInFocusedTab(Document
* aDoc
);
5453 // This covers all cases covered by IsInFocusedTab, but also ensures that
5454 // focused tab is "active" meaning not occluded.
5455 bool IsInActiveTab(Document
* aDoc
);
5457 } // namespace mozilla::dom
5459 NON_VIRTUAL_ADDREF_RELEASE(mozilla::dom::Document
)
5461 // XXX These belong somewhere else
5462 nsresult
NS_NewHTMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5463 nsIPrincipal
* aPrincipal
,
5464 nsIPrincipal
* aPartitionedPrincipal
,
5465 bool aLoadedAsData
= false);
5467 nsresult
NS_NewXMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5468 nsIPrincipal
* aPrincipal
,
5469 nsIPrincipal
* aPartitionedPrincipal
,
5470 bool aLoadedAsData
= false,
5471 bool aIsPlainDocument
= false);
5473 nsresult
NS_NewSVGDocument(mozilla::dom::Document
** aInstancePtrResult
,
5474 nsIPrincipal
* aPrincipal
,
5475 nsIPrincipal
* aPartitionedPrincipal
);
5477 nsresult
NS_NewImageDocument(mozilla::dom::Document
** aInstancePtrResult
,
5478 nsIPrincipal
* aPrincipal
,
5479 nsIPrincipal
* aPartitionedPrincipal
);
5481 nsresult
NS_NewVideoDocument(mozilla::dom::Document
** aInstancePtrResult
,
5482 nsIPrincipal
* aPrincipal
,
5483 nsIPrincipal
* aPartitionedPrincipal
);
5485 // Enum for requesting a particular type of document when creating a doc
5486 enum DocumentFlavor
{
5487 DocumentFlavorLegacyGuess
, // compat with old code until made HTML5-compliant
5488 DocumentFlavorHTML
, // HTMLDocument with HTMLness bit set to true
5489 DocumentFlavorSVG
, // SVGDocument
5490 DocumentFlavorXML
, // XMLDocument
5491 DocumentFlavorPlain
, // Just a Document
5494 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5495 // -- this method will not attempt to get a principal based on aDocumentURI.
5496 // Also, both aDocumentURI and aBaseURI must not be null.
5497 nsresult
NS_NewDOMDocument(
5498 mozilla::dom::Document
** aInstancePtrResult
, const nsAString
& aNamespaceURI
,
5499 const nsAString
& aQualifiedName
, mozilla::dom::DocumentType
* aDoctype
,
5500 nsIURI
* aDocumentURI
, nsIURI
* aBaseURI
, nsIPrincipal
* aPrincipal
,
5501 bool aLoadedAsData
, nsIGlobalObject
* aEventObject
, DocumentFlavor aFlavor
);
5503 inline mozilla::dom::Document
* nsINode::GetOwnerDocument() const {
5504 mozilla::dom::Document
* ownerDoc
= OwnerDoc();
5506 return ownerDoc
!= this ? ownerDoc
: nullptr;
5509 inline nsINode
* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5511 inline mozilla::dom::Document
* nsINode::AsDocument() {
5512 MOZ_ASSERT(IsDocument());
5513 return static_cast<mozilla::dom::Document
*>(this);
5516 inline const mozilla::dom::Document
* nsINode::AsDocument() const {
5517 MOZ_ASSERT(IsDocument());
5518 return static_cast<const mozilla::dom::Document
*>(this);
5521 inline nsISupports
* ToSupports(mozilla::dom::Document
* aDoc
) {
5522 return static_cast<nsINode
*>(aDoc
);
5525 #endif /* mozilla_dom_Document_h___ */