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/ServoStyleSet.h"
43 #include "mozilla/StorageAccessAPIHelper.h"
44 #include "mozilla/TimeStamp.h"
45 #include "mozilla/UniquePtr.h"
46 #include "mozilla/UseCounter.h"
47 #include "mozilla/WeakPtr.h"
48 #include "mozilla/css/StylePreloadKind.h"
49 #include "mozilla/dom/AnimationFrameProvider.h"
50 #include "mozilla/dom/DocumentOrShadowRoot.h"
51 #include "mozilla/dom/Element.h"
52 #include "mozilla/dom/EventTarget.h"
53 #include "mozilla/dom/Nullable.h"
54 #include "mozilla/dom/RadioGroupContainer.h"
55 #include "mozilla/dom/TreeOrderedArray.h"
56 #include "mozilla/dom/ViewportMetaData.h"
57 #include "mozilla/dom/LargestContentfulPaint.h"
58 #include "mozilla/dom/UserActivation.h"
59 #include "mozilla/dom/WakeLockBinding.h"
61 #include "nsCOMArray.h"
63 #include "nsClassHashtable.h"
64 #include "nsCompatibility.h"
65 #include "nsContentListDeclarations.h"
66 #include "nsCycleCollectionParticipant.h"
67 #include "nsTHashMap.h"
69 #include "nsGkAtoms.h"
70 #include "nsHashKeys.h"
71 #include "nsIChannel.h"
72 #include "nsIChannelEventSink.h"
74 #include "nsIDocumentViewer.h"
75 #include "nsIInterfaceRequestor.h"
76 #include "nsILoadContext.h"
77 #include "nsILoadGroup.h"
78 #include "nsILoadInfo.h"
80 #include "nsIObserver.h"
81 #include "nsIParser.h"
82 #include "nsIPrincipal.h"
83 #include "nsIProgressEventSink.h"
84 #include "nsIReferrerInfo.h"
85 #include "nsIRequestObserver.h"
86 #include "nsIScriptObjectPrincipal.h"
87 #include "nsIStreamListener.h"
88 #include "nsISupports.h"
89 #include "nsISupportsUtils.h"
90 #include "nsITransportSecurityInfo.h"
92 #include "nsIWeakReferenceUtils.h"
93 #include "nsLiteralString.h"
94 #include "nsPIDOMWindow.h"
95 #include "nsPropertyTable.h"
96 #include "nsRefPtrHashtable.h"
99 #include "nsTHashSet.h"
100 #include "nsTLiteralString.h"
101 #include "nsTObserverArray.h"
102 #include "nsThreadUtils.h"
103 #include "nsURIHashKey.h"
104 #include "nsViewportInfo.h"
105 #include "nsWeakReference.h"
106 #include "nsWindowSizes.h"
107 #include "nsXULElement.h"
110 // XXX We need to include this here to ensure that DefaultDeleter for Servo
111 // types is specialized before the template is instantiated. Probably, this
112 // should be included at some other place already that's generated by cbindgen.
113 #include "mozilla/ServoBindingTypes.h"
115 // windows.h #defines CreateEvent
120 #ifdef MOZILLA_INTERNAL_API
121 # include "mozilla/dom/DocumentBinding.h"
125 class ElementCreationOptionsOrString
;
127 } // namespace mozilla
128 #endif // MOZILLA_INTERNAL_API
130 class InfallibleAllocPolicy
;
134 class gfxUserFontSet
;
135 class mozIDOMWindowProxy
;
136 class nsCachableElementsByNameNodeList
;
137 class nsCommandManager
;
139 class nsCycleCollectionTraversalCallback
;
140 class nsDOMCaretPosition
;
141 class nsDOMNavigationTiming
;
144 class nsFrameLoaderOwner
;
145 class nsGenericHTMLElement
;
146 class nsGlobalWindowInner
;
147 class nsHTMLDocument
;
148 class nsHtml5TreeOpExecutor
;
150 class nsIAsyncVerifyRedirectCallback
;
151 class nsIBFCacheEntry
;
153 class nsIContentSecurityPolicy
;
154 class nsIContentSink
;
155 class nsICookieJarSettings
;
156 class nsIDOMXULCommandDispatcher
;
158 class nsIDocShellTreeItem
;
159 class nsIDocumentEncoder
;
160 class nsIDocumentObserver
;
161 class nsIEventTarget
;
163 class nsIGlobalObject
;
164 class nsIHTMLCollection
;
165 class nsIInputStream
;
166 class nsILayoutHistoryState
;
167 class nsIObjectLoadingContent
;
168 class nsIPermissionDelegateHandler
;
169 class nsIRadioVisitor
;
172 class nsIScriptGlobalObject
;
173 class nsISecurityConsoleMessage
;
174 class nsISerialEventTarget
;
175 class nsIStructuredCloneContainer
;
177 class nsNodeInfoManager
;
178 class nsPIWindowRoot
;
181 class nsSimpleContentList
;
184 class nsXULPrototypeDocument
;
189 class AbstractThread
;
190 class AttributeStyles
;
197 class EventListenerManager
;
198 class FullscreenExit
;
199 class FullscreenRequest
;
201 struct LangGroupFontPrefs
;
202 class PermissionDelegateHandler
;
204 class ScrollTimelineAnimationTracker
;
206 enum class StyleOrigin
: uint8_t;
207 class SMILAnimationController
;
208 enum class StyleCursorKind
: uint8_t;
209 class SVGContextPaint
;
210 enum class ColorScheme
: uint8_t;
211 enum class StyleRuleChangeKind
: uint32_t;
212 struct StyleUseCounters
;
224 class AnonymousContent
;
226 class XULBroadcastManager
;
228 class BrowserBridgeChild
;
229 class ChromeObserver
;
236 class DocumentFragment
;
237 class DocumentTimeline
;
239 class DOMImplementation
;
240 class DOMIntersectionObserver
;
244 struct FailedCertSecurityInfo
;
247 class FragmentDirective
;
248 class FrameRequestCallback
;
250 class HighlightRegistry
;
251 class HTMLAllCollection
;
252 class HTMLBodyElement
;
253 class HTMLInputElement
;
254 class HTMLMetaElement
;
255 class HTMLDialogElement
;
256 class HTMLSharedElement
;
257 class HTMLImageElement
;
258 struct LifecycleCallbackArgs
;
261 class MediaQueryList
;
266 enum class OrientationType
: uint8_t;
267 class ProcessingInstruction
;
271 class ServiceWorkerDescriptor
;
281 enum class ViewportFitType
: uint8_t;
282 class WakeLockSentinel
;
284 class WindowGlobalChild
;
285 class WindowProxyHolder
;
287 class WorkerDocumentListener
;
288 class XPathEvaluator
;
289 class XPathExpression
;
290 class XPathNSResolver
;
292 class BrowsingContext
;
294 class nsUnblockOnloadEvent
;
296 template <typename
, typename
>
297 class CallbackObjectHolder
;
299 enum class CallerType
: uint32_t;
302 NOT_ALLOWED
= 1 << 0, // Status 0
303 EVENT_HANDLING_SUPPRESSED
= 1 << 1, // Status 1
304 SUSPENDED
= 1 << 2, // Status 2
305 UNLOAD_LISTENER
= 1 << 3, // Status 3
306 REQUEST
= 1 << 4, // Status 4
307 ACTIVE_GET_USER_MEDIA
= 1 << 5, // Status 5
308 ACTIVE_PEER_CONNECTION
= 1 << 6, // Status 6
309 CONTAINS_EME_CONTENT
= 1 << 7, // Status 7
310 CONTAINS_MSE_CONTENT
= 1 << 8, // Status 8
311 HAS_ACTIVE_SPEECH_SYNTHESIS
= 1 << 9, // Status 9
312 HAS_USED_VR
= 1 << 10, // Status 10
313 CONTAINS_REMOTE_SUBFRAMES
= 1 << 11, // Status 11
314 NOT_ONLY_TOPLEVEL_IN_BCG
= 1 << 12, // Status 12
315 ABOUT_PAGE
= 1 << 13, // Status 13
316 RESTORING
= 1 << 14, // Status 14
317 BEFOREUNLOAD_LISTENER
= 1 << 15, // Status 15
318 ACTIVE_LOCK
= 1 << 16, // Status 16
319 ACTIVE_WEBTRANSPORT
= 1 << 17, // Status 17
323 namespace glean::perf
{
324 struct PageLoadExtra
;
326 } // namespace mozilla
328 namespace mozilla::net
{
329 class ChannelEventQueue
;
330 class EarlyHintConnectArgs
;
331 } // namespace mozilla::net
333 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
334 #define NS_IDOCUMENT_IID \
336 0xce1f7627, 0x7109, 0x4977, { \
337 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
341 namespace mozilla::dom
{
344 class DOMStyleSheetSetList
;
345 class ResizeObserver
;
346 class ResizeObserverController
;
347 class PostMessageEvent
;
349 #define DEPRECATED_OPERATION(_op) e##_op,
350 enum class DeprecatedOperations
: uint16_t {
351 #include "nsDeprecatedOperationList.h"
352 eDeprecatedOperationCount
354 #undef DEPRECATED_OPERATION
356 class ExternalResourceMap
{
357 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
361 * A class that represents an external resource load that has begun but
362 * doesn't have a document yet. Observers can be registered on this object,
363 * and will be notified after the document is created. Observers registered
364 * after the document has been created will NOT be notified. When observers
365 * are notified, the subject will be the newly-created document, the topic
366 * will be "external-resource-document-created", and the data will be null.
367 * If document creation fails for some reason, observers will still be
368 * notified, with a null document pointer.
370 class ExternalResourceLoad
: public nsISupports
{
372 virtual ~ExternalResourceLoad() = default;
374 void AddObserver(nsIObserver
* aObserver
) {
375 MOZ_ASSERT(aObserver
, "Must have observer");
376 mObservers
.AppendElement(aObserver
);
379 const nsTArray
<nsCOMPtr
<nsIObserver
>>& Observers() { return mObservers
; }
382 AutoTArray
<nsCOMPtr
<nsIObserver
>, 8> mObservers
;
385 ExternalResourceMap();
388 * Request an external resource document. This does exactly what
389 * Document::RequestExternalResource is documented to do.
391 Document
* RequestResource(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
392 nsINode
* aRequestingNode
,
393 Document
* aDisplayDocument
,
394 ExternalResourceLoad
** aPendingLoad
);
397 * Enumerate the resource documents. See
398 * Document::EnumerateExternalResources.
400 void EnumerateResources(SubDocEnumFunc aCallback
);
403 * Traverse ourselves for cycle-collection
405 void Traverse(nsCycleCollectionTraversalCallback
* aCallback
) const;
408 * Shut ourselves down (used for cycle-collection unlink), as well
409 * as for document destruction.
412 mPendingLoads
.Clear();
414 mHaveShutDown
= true;
417 bool HaveShutDown() const { return mHaveShutDown
; }
419 // Needs to be public so we can traverse them sanely
420 struct ExternalResource
{
422 RefPtr
<Document
> mDocument
;
423 nsCOMPtr
<nsIDocumentViewer
> mViewer
;
424 nsCOMPtr
<nsILoadGroup
> mLoadGroup
;
427 // Hide all our viewers
430 // Show all our viewers
434 class PendingLoad
: public ExternalResourceLoad
, public nsIStreamListener
{
435 ~PendingLoad() = default;
438 explicit PendingLoad(Document
* aDisplayDocument
)
439 : mDisplayDocument(aDisplayDocument
) {}
442 NS_DECL_NSISTREAMLISTENER
443 NS_DECL_NSIREQUESTOBSERVER
446 * Start aURI loading. This will perform the necessary security checks and
449 nsresult
StartLoad(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
450 nsINode
* aRequestingNode
);
452 * Set up an nsIDocumentViewer based on aRequest. This is guaranteed to
453 * put null in *aViewer and *aLoadGroup on all failures.
455 nsresult
SetupViewer(nsIRequest
* aRequest
, nsIDocumentViewer
** aViewer
,
456 nsILoadGroup
** aLoadGroup
);
459 RefPtr
<Document
> mDisplayDocument
;
460 nsCOMPtr
<nsIStreamListener
> mTargetListener
;
461 nsCOMPtr
<nsIURI
> mURI
;
463 friend class PendingLoad
;
465 class LoadgroupCallbacks final
: public nsIInterfaceRequestor
{
466 ~LoadgroupCallbacks() = default;
469 explicit LoadgroupCallbacks(nsIInterfaceRequestor
* aOtherCallbacks
)
470 : mCallbacks(aOtherCallbacks
) {}
472 NS_DECL_NSIINTERFACEREQUESTOR
474 // The only reason it's safe to hold a strong ref here without leaking is
475 // that the notificationCallbacks on a loadgroup aren't the docshell itself
476 // but a shim that holds a weak reference to the docshell.
477 nsCOMPtr
<nsIInterfaceRequestor
> mCallbacks
;
479 // Use shims for interfaces that docshell implements directly so that we
480 // don't hand out references to the docshell. The shims should all allow
481 // getInterface back on us, but other than that each one should only
482 // implement one interface.
484 // XXXbz I wish we could just derive the _allcaps thing from _i
485 #define DECL_SHIM(_i, _allcaps) \
486 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
490 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
491 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
492 NS_ASSERTION(mIfReq, "Expected non-null here"); \
493 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
496 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
497 NS_FORWARD_##_allcaps(mRealPtr->) private \
498 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
499 nsCOMPtr<_i> mRealPtr; \
502 DECL_SHIM(nsILoadContext
, NSILOADCONTEXT
)
503 DECL_SHIM(nsIProgressEventSink
, NSIPROGRESSEVENTSINK
)
504 DECL_SHIM(nsIChannelEventSink
, NSICHANNELEVENTSINK
)
509 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
510 * when this is called if the URI didn't result in an XML document. This
511 * function makes sure to remove the pending load for aURI, if any, from our
512 * hashtable, and to notify its observers, if any.
514 nsresult
AddExternalResource(nsIURI
* aURI
, nsIDocumentViewer
* aViewer
,
515 nsILoadGroup
* aLoadGroup
,
516 Document
* aDisplayDocument
);
518 nsClassHashtable
<nsURIHashKey
, ExternalResource
> mMap
;
519 nsRefPtrHashtable
<nsURIHashKey
, PendingLoad
> mPendingLoads
;
523 // The current status for a preload.
524 enum class SheetPreloadStatus
: uint8_t {
525 // There's no need to preload anything, the sheet is already in-memory.
527 // The load is in-progress. There's no guarantee that a load was started, it
528 // could be coalesced with other redundant loads.
530 // Something went wrong, and we errored out.
534 //----------------------------------------------------------------------
536 // Document interface. This is implemented by all document objects in
538 class Document
: public nsINode
,
539 public DocumentOrShadowRoot
,
540 public nsSupportsWeakReference
,
541 public nsIScriptObjectPrincipal
,
542 public SupportsWeakPtr
{
543 friend class DocumentOrShadowRoot
;
546 explicit Document(const char* aContentType
);
549 Document(const Document
&) = delete;
550 Document
& operator=(const Document
&) = delete;
553 using ExternalResourceLoad
= dom::ExternalResourceMap::ExternalResourceLoad
;
554 using ReferrerPolicyEnum
= dom::ReferrerPolicy
;
555 using AdoptedStyleSheetCloneCache
=
556 nsRefPtrHashtable
<nsPtrHashKey
<const StyleSheet
>, StyleSheet
>;
558 // nsINode overrides the new operator for DOM Arena allocation.
559 // to use the default one, we need to bring it back again
560 void* operator new(size_t aSize
) { return ::operator new(aSize
); }
563 * Called when XPCOM shutdown.
565 static void Shutdown();
567 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID
)
569 NS_DECL_ISUPPORTS_INHERITED
570 NS_IMETHOD_(void) DeleteCycleCollectable() override
;
572 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
574 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document
,
577 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
579 for (RefPtr obs : mObservers.ForwardRange()) { \
580 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
581 obs->func_ params_; \
584 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
586 if (PresShell* presShell = GetObservingPresShell()) { \
587 presShell->func_ params_; \
591 nsIPrincipal
* EffectiveCookiePrincipal() const;
593 nsIPrincipal
* EffectiveStoragePrincipal() const;
595 // nsIScriptObjectPrincipal
596 nsIPrincipal
* GetPrincipal() final
{ return NodePrincipal(); }
598 nsIPrincipal
* GetEffectiveCookiePrincipal() final
{
599 return EffectiveCookiePrincipal();
602 nsIPrincipal
* GetEffectiveStoragePrincipal() final
{
603 return EffectiveStoragePrincipal();
606 // You should probably not be using this function, since it performs no checks
607 // to ensure that the partitioned principal should really be used here. It is
608 // only designed to be used in very specific circumstances, such as when
609 // inheriting the document/storage principal.
610 nsIPrincipal
* PartitionedPrincipal() final
{ return mPartitionedPrincipal
; }
612 // Gets the appropriate principal to check the URI against a blocklist /
614 nsIPrincipal
* GetPrincipalForPrefBasedHacks() const;
616 void ClearActiveCookieAndStoragePrincipals() {
617 mActiveStoragePrincipal
= nullptr;
618 mActiveCookiePrincipal
= nullptr;
622 void GetEventTargetParent(EventChainPreVisitor
& aVisitor
) override
;
623 EventListenerManager
* GetOrCreateListenerManager() override
;
624 EventListenerManager
* GetExistingListenerManager() const override
;
626 // This helper class must be set when we dispatch beforeunload and unload
627 // events in order to avoid unterminate sync XHRs.
628 class MOZ_RAII PageUnloadingEventTimeStamp
{
629 RefPtr
<Document
> mDocument
;
633 explicit PageUnloadingEventTimeStamp(Document
* aDocument
)
634 : mDocument(aDocument
), mSet(false) {
635 MOZ_ASSERT(aDocument
);
636 if (mDocument
->mPageUnloadingEventTimeStamp
.IsNull()) {
637 mDocument
->SetPageUnloadingEventTimeStamp();
642 ~PageUnloadingEventTimeStamp() {
644 mDocument
->CleanUnloadEventsTimeStamp();
650 * Let the document know that we're starting to load data into it.
651 * @param aCommand The parser command. Must not be null.
652 * XXXbz It's odd to have that here.
653 * @param aChannel The channel the data will come from. The channel must be
654 * able to report its Content-Type.
655 * @param aLoadGroup The loadgroup this document should use from now on.
656 * Note that the document might not be the only thing using
658 * @param aContainer The container this document is in. This may be null.
659 * XXXbz maybe we should make it more explicit (eg make the
660 * container an nsIWebNavigation or nsIDocShell or
662 * @param [out] aDocListener the listener to pump data from the channel into.
663 * Generally this will be the parser this document
664 * sets up, or some sort of data-handler for media
666 * @param aReset whether the document should call Reset() on itself. If this
667 * is false, the document will NOT set its principal to the
668 * channel's owner, will not clear any event listeners that are
669 * already set on it, etc.
671 * Once this has been called, the document will return false for
672 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
673 * sure this happens is the responsibility of the caller of
674 * StartDocumentLoad().
676 * This function has an implementation, and does some setup, but does NOT set
677 * *aDocListener; this is the job of subclasses.
679 virtual nsresult
StartDocumentLoad(const char* aCommand
, nsIChannel
* aChannel
,
680 nsILoadGroup
* aLoadGroup
,
681 nsISupports
* aContainer
,
682 nsIStreamListener
** aDocListener
,
684 void StopDocumentLoad();
686 virtual void SetSuppressParserErrorElement(bool aSuppress
) {}
687 virtual bool SuppressParserErrorElement() { return false; }
689 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress
) {}
690 virtual bool SuppressParserErrorConsoleMessages() { return false; }
693 void InsertChildBefore(nsIContent
* aKid
, nsIContent
* aBeforeThis
,
694 bool aNotify
, ErrorResult
& aRv
) override
;
695 void RemoveChildNode(nsIContent
* aKid
, bool aNotify
) final
;
696 nsresult
Clone(dom::NodeInfo
* aNodeInfo
, nsINode
** aResult
) const override
{
697 return NS_ERROR_NOT_IMPLEMENTED
;
699 nsresult
CloneDocHelper(Document
* clone
) const;
701 Document
* GetLatestStaticClone() const { return mLatestStaticClone
; }
704 * Signal that the document title may have changed
705 * (see Document::GetTitle).
706 * @param aBoundTitleElement true if an HTML or SVG <title> element
707 * has just been bound to the document.
709 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement
);
712 * Return the URI for the document. May return null. If it ever stops being
713 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
714 * also never return null.
716 * The value returned corresponds to the "document's address" in
717 * HTML5. As such, it may change over the lifetime of the document, for
718 * instance as a result of the user navigating to a fragment identifier on
719 * the page, or as a result to a call to pushState() or replaceState().
721 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
723 nsIURI
* GetDocumentURI() const { return mDocumentURI
; }
726 * Return the original URI of the document. This is the same as the
727 * document's URI unless that has changed from its original value (for
728 * example, due to history.pushState() or replaceState() being invoked on the
731 * This method corresponds to the "creation URL" in HTML5 and, once set,
732 * doesn't change over the lifetime of the document.
734 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
736 nsIURI
* GetOriginalURI() const { return mOriginalURI
; }
739 * Return the base domain of the document. This has been computed using
740 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
741 * checks. When the URI of the document changes, this value is recomputed.
743 nsCString
GetBaseDomain() const { return mBaseDomain
; }
746 * Set the URI for the document. This also sets the document's original URI,
749 void SetDocumentURI(nsIURI
* aURI
);
752 * Set the URI for the document loaded via XHR, when accessed from
753 * chrome privileged script.
755 void SetChromeXHRDocURI(nsIURI
* aURI
) { mChromeXHRDocURI
= aURI
; }
758 * Set the base URI for the document loaded via XHR, when accessed from
759 * chrome privileged script.
761 void SetChromeXHRDocBaseURI(nsIURI
* aURI
) { mChromeXHRDocBaseURI
= aURI
; }
764 * The CSP in general is stored in the ClientInfo, but we also cache
765 * the CSP on the document so subresources loaded within a document
766 * can query that cached CSP instead of having to deserialize the CSP
769 * Please note that at the time of CSP parsing the Client is not
770 * available yet, hence we sync CSP of document and Client when the
771 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
773 nsIContentSecurityPolicy
* GetCsp() const;
774 void SetCsp(nsIContentSecurityPolicy
* aCSP
);
776 nsIContentSecurityPolicy
* GetPreloadCsp() const;
777 void SetPreloadCsp(nsIContentSecurityPolicy
* aPreloadCSP
);
779 void GetCspJSON(nsString
& aJSON
);
782 * Set referrer policy and upgrade-insecure-requests flags
784 void ApplySettingsFromCSP(bool aSpeculative
);
786 already_AddRefed
<nsIParser
> CreatorParserOrNull() {
787 nsCOMPtr
<nsIParser
> parser
= mParser
;
788 return parser
.forget();
792 * ReferrerInfo getter for Document.webidl.
794 nsIReferrerInfo
* ReferrerInfo() const { return GetReferrerInfo(); }
796 nsIReferrerInfo
* GetReferrerInfo() const { return mReferrerInfo
; }
798 nsIReferrerInfo
* GetPreloadReferrerInfo() const {
799 return mPreloadReferrerInfo
;
802 * Return the referrer policy of the document. Return "default" if there's no
803 * valid meta referrer tag found in the document.
804 * Referrer policy should be inherited from parent if the iframe is srcdoc
806 ReferrerPolicyEnum
GetReferrerPolicy() const;
809 * GetReferrerPolicy() for Document.webidl.
811 ReferrerPolicyEnum
ReferrerPolicy() const { return GetReferrerPolicy(); }
814 * If true, this flag indicates that all mixed content subresource
815 * loads for this document (and also embeded browsing contexts) will
818 bool GetBlockAllMixedContent(bool aPreload
) const {
820 return mBlockAllMixedContentPreloads
;
822 return mBlockAllMixedContent
;
826 * If true, this flag indicates that all subresource loads for this
827 * document need to be upgraded from http to https.
828 * This flag becomes true if the CSP of the document itself, or any
829 * of the document's ancestors up to the toplevel document makes use
830 * of the CSP directive 'upgrade-insecure-requests'.
832 bool GetUpgradeInsecureRequests(bool aPreload
) const {
834 return mUpgradeInsecurePreloads
;
836 return mUpgradeInsecureRequests
;
839 void SetReferrerInfo(nsIReferrerInfo
*);
842 * Referrer policy from <meta name="referrer" content=`policy`>
843 * will have higher priority than referrer policy from Referrer-Policy
844 * header. So override the old ReferrerInfo if we get one from meta
846 void UpdateReferrerInfoFromMeta(const nsAString
& aMetaReferrer
,
850 * Set the principals responsible for this document. Chances are, you do not
851 * want to be using this.
853 void SetPrincipals(nsIPrincipal
* aPrincipal
,
854 nsIPrincipal
* aPartitionedPrincipal
);
857 * Returns true if exempt from HTTPS-Only Mode upgrade.
859 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus
; }
862 * Return the LoadGroup for the document. May return null.
864 already_AddRefed
<nsILoadGroup
> GetDocumentLoadGroup() const {
865 nsCOMPtr
<nsILoadGroup
> group
= do_QueryReferent(mDocumentLoadGroup
);
866 return group
.forget();
870 * Return the fallback base URL for this document, as defined in the HTML
871 * specification. Note that this can return null if there is no document URI.
873 * XXXbz: This doesn't implement the bits for about:blank yet.
875 nsIURI
* GetFallbackBaseURI() const {
876 if (mIsSrcdocDocument
&& mParentDocument
) {
877 return mParentDocument
->GetDocBaseURI();
883 * Return the referrer from document URI as defined in the Referrer Policy
885 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
886 * While document is an iframe srcdoc document, let document be document's
887 * browsing context's browsing context container's node document.
888 * Then referrer should be document's URL
891 nsIURI
* GetDocumentURIAsReferrer() const {
892 if (mIsSrcdocDocument
&& mParentDocument
) {
893 return mParentDocument
->GetDocumentURIAsReferrer();
899 * Return the base URI for relative URIs in the document (the document uri
900 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
901 * returned URI could be null if there is no document URI. If the document is
902 * a srcdoc document and has no explicit base URL, return the parent
903 * document's base URL.
905 nsIURI
* GetDocBaseURI() const {
906 if (mDocumentBaseURI
) {
907 return mDocumentBaseURI
;
909 return GetFallbackBaseURI();
912 nsIURI
* GetBaseURI(bool aTryUseXHRDocBaseURI
= false) const final
;
914 void SetBaseURI(nsIURI
* aURI
);
917 * Resolves a URI based on the document's base URI.
919 Result
<OwningNonNull
<nsIURI
>, nsresult
> ResolveWithBaseURI(
920 const nsAString
& aURI
);
923 * Return the URL data which style system needs for resolving url value.
924 * This method attempts to use the cached object in mCachedURLData, but
925 * if the base URI, document URI, or principal has changed since last
926 * call to this function, or the function is called the first time for
927 * the document, a new one is created.
929 URLExtraData
* DefaultStyleAttrURLData();
930 nsIReferrerInfo
* ReferrerInfoForInternalCSSAndSVGResources();
933 * Get/Set the base target of a link in a document.
935 void GetBaseTarget(nsAString
& aBaseTarget
) const {
936 aBaseTarget
= mBaseTarget
;
939 void SetBaseTarget(const nsString
& aBaseTarget
) { mBaseTarget
= aBaseTarget
; }
942 * Return a standard name for the document's character set.
944 NotNull
<const Encoding
*> GetDocumentCharacterSet() const {
945 return mCharacterSet
;
949 * Set the document's character encoding.
951 void SetDocumentCharacterSet(NotNull
<const Encoding
*> aEncoding
);
953 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource
; }
955 // This method MUST be called before SetDocumentCharacterSet if
956 // you're planning to call both.
957 void SetDocumentCharacterSetSource(int32_t aCharsetSource
) {
958 mCharacterSetSource
= aCharsetSource
;
962 * Get the Content-Type of this document.
964 void GetContentType(nsAString
& aContentType
);
967 * Set the Content-Type of this document.
969 void SetContentType(const nsACString
& aContentType
);
972 * Return the language of this document, or null if not set.
974 nsAtom
* GetContentLanguage() const { return mContentLanguage
.get(); }
976 void GetContentLanguageForBindings(DOMString
&) const;
978 // The states BidiEnabled and MathMLEnabled should persist across multiple
979 // views (screen, print) of the same document.
982 * Check if the document contains bidi data.
983 * If so, we have to apply the Unicode Bidi Algorithm.
985 bool GetBidiEnabled() const { return mBidiEnabled
; }
988 * Indicate the document contains bidi data.
989 * Currently, we cannot disable bidi, because once bidi is enabled,
990 * it affects a frame model irreversibly, and plays even though
991 * the document no longer contains bidi data.
993 void SetBidiEnabled() { mBidiEnabled
= true; }
995 void SetMathMLEnabled() { mMathMLEnabled
= true; }
998 * Ask this document whether it's the initial document in its window.
1000 bool IsInitialDocument() const { return mIsInitialDocumentInWindow
; }
1003 * Ask this document whether it has ever been a initial document in its
1006 bool IsEverInitialDocument() const { return mIsEverInitialDocumentInWindow
; }
1009 * Tell this document that it's the initial document in its window. See
1010 * comments on mIsInitialDocumentInWindow for when this should be called.
1012 void SetIsInitialDocument(bool aIsInitialDocument
);
1014 void SetLoadedAsData(bool aLoadedAsData
, bool aConsiderForMemoryReporting
);
1016 TimeStamp
GetLoadingOrRestoredFromBFCacheTimeStamp() const {
1017 return mLoadingOrRestoredFromBFCacheTimeStamp
;
1019 void SetLoadingOrRestoredFromBFCacheTimeStampToNow() {
1020 mLoadingOrRestoredFromBFCacheTimeStamp
= TimeStamp::Now();
1024 * Normally we assert if a runnable labeled with one DocGroup touches data
1025 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1026 * means that we can touch that document from any DocGroup without asserting.
1028 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches
= true; }
1031 * Get the bidi options for this document.
1032 * @see nsBidiUtils.h
1034 uint32_t GetBidiOptions() const { return mBidiOptions
; }
1037 * Set the bidi options for this document. This just sets the bits;
1038 * callers are expected to take action as needed if they want this
1039 * change to actually change anything immediately.
1040 * @see nsBidiUtils.h
1042 void SetBidiOptions(uint32_t aBidiOptions
) { mBidiOptions
= aBidiOptions
; }
1045 * Returns true if the document holds a CSP
1046 * delivered through an HTTP Header.
1048 bool GetHasCSPDeliveredThroughHeader() {
1049 return mHasCSPDeliveredThroughHeader
;
1053 * Return a promise which resolves to the content blocking events.
1055 using GetContentBlockingEventsPromise
= MozPromise
<uint32_t, bool, true>;
1056 [[nodiscard
]] RefPtr
<GetContentBlockingEventsPromise
>
1057 GetContentBlockingEvents();
1060 * Get the sandbox flags for this document.
1061 * @see nsSandboxFlags.h for the possible flags
1063 uint32_t GetSandboxFlags() const { return mSandboxFlags
; }
1065 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> GetEmbedderPolicy() const {
1066 return mEmbedderPolicy
;
1069 void SetEmbedderPolicy(
1070 const Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
>& aCOEP
) {
1071 mEmbedderPolicy
= aCOEP
;
1075 * Get string representation of sandbox flags (null if no flags are set)
1077 void GetSandboxFlagsAsString(nsAString
& aFlags
);
1080 * Set the sandbox flags for this document.
1081 * @see nsSandboxFlags.h for the possible flags
1083 void SetSandboxFlags(uint32_t sandboxFlags
) { mSandboxFlags
= sandboxFlags
; }
1086 * Called when the document was decoded as UTF-8 and decoder encountered no
1089 void EnableEncodingMenu() { mEncodingMenuDisabled
= false; }
1092 * Called to disable client access to cookies through the document.cookie API
1093 * from user JavaScript code.
1095 void DisableCookieAccess() { mDisableCookieAccess
= true; }
1097 void SetLinkHandlingEnabled(bool aValue
) { mLinksEnabled
= aValue
; }
1098 bool LinkHandlingEnabled() { return mLinksEnabled
; }
1101 * Set compatibility mode for this document
1103 void SetCompatibilityMode(nsCompatibility aMode
);
1106 * Called to disable client access to document.write() API from user
1109 void SetDocWriteDisabled(bool aDisabled
) { mDisableDocWrite
= aDisabled
; }
1112 * Whether a document.write() call is in progress.
1114 bool IsWriting() const { return mWriteLevel
!= uint32_t(0); }
1117 * Access HTTP header data (this may also get set from other
1118 * sources, like HTML META tags).
1120 void GetHeaderData(nsAtom
* aHeaderField
, nsAString
& aData
) const;
1121 void SetHeaderData(nsAtom
* aheaderField
, const nsAString
& aData
);
1124 * Set Early Hint data, moves the arrays into the function, leaving the
1125 * passed variables empty
1127 void SetEarlyHints(nsTArray
<net::EarlyHintConnectArgs
>&& aEarlyHints
);
1128 const nsTArray
<net::EarlyHintConnectArgs
>& GetEarlyHints() const {
1133 * Create a new presentation shell that will use aContext for its
1134 * presentation context (presentation contexts <b>must not</b> be
1135 * shared among multiple presentation shells). The caller of this
1136 * method is responsible for calling BeginObservingDocument() on the
1137 * presshell if the presshell should observe document mutations.
1139 MOZ_CAN_RUN_SCRIPT already_AddRefed
<PresShell
> CreatePresShell(
1140 nsPresContext
* aContext
, nsViewManager
* aViewManager
);
1141 void DeletePresShell();
1143 PresShell
* GetPresShell() const {
1144 return GetBFCacheEntry() ? nullptr : mPresShell
;
1147 inline PresShell
* GetObservingPresShell() const;
1149 // Return whether the presshell for this document is safe to flush.
1150 bool IsSafeToFlush() const;
1152 inline nsPresContext
* GetPresContext() const;
1154 bool HasShellOrBFCacheEntry() const { return mPresShell
|| mBFCacheEntry
; }
1156 // Instead using this method, what you probably want is
1157 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1158 void DisallowBFCaching(uint32_t aStatus
= BFCacheStatus::NOT_ALLOWED
);
1160 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed
; }
1162 // Accepts null to clear the BFCache entry too.
1163 void SetBFCacheEntry(nsIBFCacheEntry
* aEntry
);
1165 nsIBFCacheEntry
* GetBFCacheEntry() const { return mBFCacheEntry
; }
1167 // Removes this document from the BFCache, if it is cached, and returns
1169 bool RemoveFromBFCacheSync();
1172 * Return the parent document of this document. Will return null
1173 * unless this document is within a compound document and has a
1174 * parent. Note that this parent chain may cross chrome boundaries.
1176 Document
* GetInProcessParentDocument() const { return mParentDocument
; }
1179 * Set the parent document of this document.
1181 void SetParentDocument(Document
* aParent
) {
1182 mParentDocument
= aParent
;
1184 RecomputeResistFingerprinting();
1185 mIgnoreDocGroupMismatches
= aParent
->mIgnoreDocGroupMismatches
;
1189 void SetCurrentContextPaint(const SVGContextPaint
* aContextPaint
) {
1190 mCurrentContextPaint
= aContextPaint
;
1193 const SVGContextPaint
* GetCurrentContextPaint() const {
1194 return mCurrentContextPaint
;
1198 * Set the sub document for aContent to aSubDoc.
1200 nsresult
SetSubDocumentFor(Element
* aContent
, Document
* aSubDoc
);
1203 * Get the sub document for aContent
1205 Document
* GetSubDocumentFor(nsIContent
* aContent
) const;
1208 * Get the content node for which this document is a sub document.
1210 Element
* GetEmbedderElement() const;
1213 * Return the doctype for this document.
1215 DocumentType
* GetDoctype() const;
1218 * Return the root element for this document.
1220 Element
* GetRootElement() const;
1222 Selection
* GetSelection(ErrorResult
& aRv
);
1224 void MakeBrowsingContextNonSynthetic();
1225 nsresult
HasStorageAccessSync(bool& aHasStorageAccess
);
1226 already_AddRefed
<Promise
> HasStorageAccess(ErrorResult
& aRv
);
1228 StorageAccessAPIHelper::PerformPermissionGrant
CreatePermissionGrantPromise(
1229 nsPIDOMWindowInner
* aInnerWindow
, nsIPrincipal
* aPrincipal
,
1230 bool aHasUserInteraction
, bool aRequireUserInteraction
,
1231 const Maybe
<nsCString
>& aTopLevelBaseDomain
, bool aFrameOnly
);
1233 already_AddRefed
<Promise
> RequestStorageAccess(ErrorResult
& aRv
);
1235 already_AddRefed
<Promise
> RequestStorageAccessForOrigin(
1236 const nsAString
& aThirdPartyOrigin
, const bool aRequireUserInteraction
,
1239 already_AddRefed
<Promise
> RequestStorageAccessUnderSite(
1240 const nsAString
& aSerializedSite
, ErrorResult
& aRv
);
1241 already_AddRefed
<Promise
> CompleteStorageAccessRequestFromSite(
1242 const nsAString
& aSerializedOrigin
, ErrorResult
& aRv
);
1244 bool UseRegularPrincipal() const;
1247 * Gets the event target to dispatch key events to if there is no focused
1248 * content in the document.
1250 virtual Element
* GetUnfocusedKeyEventTarget();
1253 * Retrieve information about the viewport as a data structure.
1254 * This will return information in the viewport META data section
1255 * of the document. This can be used in lieu of ProcessViewportInfo(),
1256 * which places the viewport information in the document header instead
1257 * of returning it directly.
1259 * @param aDisplaySize size of the on-screen display area for this
1260 * document, in device pixels.
1262 * NOTE: If the site is optimized for mobile (via the doctype), this
1263 * will return viewport information that specifies default information.
1265 nsViewportInfo
GetViewportInfo(const ScreenIntSize
& aDisplaySize
);
1267 void SetMetaViewportData(UniquePtr
<ViewportMetaData
> aData
);
1269 // Returns a ViewportMetaData for this document.
1270 ViewportMetaData
GetViewportMetaData() const;
1273 * True iff this doc will ignore manual character encoding overrides.
1275 virtual bool WillIgnoreCharsetOverride() { return true; }
1278 * Return whether the document was created by a srcdoc iframe.
1280 bool IsSrcdocDocument() const { return mIsSrcdocDocument
; }
1283 * Sets whether the document was created by a srcdoc iframe.
1285 void SetIsSrcdocDocument(bool aIsSrcdocDocument
) {
1286 mIsSrcdocDocument
= aIsSrcdocDocument
;
1290 * Gets the srcdoc string from within the channel (assuming both exist).
1291 * Returns a void string if this isn't a srcdoc document or if
1292 * the channel has not been set.
1294 nsresult
GetSrcdocData(nsAString
& aSrcdocData
);
1296 already_AddRefed
<AnonymousContent
> InsertAnonymousContent(bool aForce
,
1298 void RemoveAnonymousContent(AnonymousContent
&);
1300 * If aNode is a descendant of anonymous content inserted by
1301 * InsertAnonymousContent, this method returns the root element of the
1302 * inserted anonymous content (in other words, the clone of the aElement
1303 * that was passed to InsertAnonymousContent).
1305 Element
* GetAnonRootIfInAnonymousContentContainer(nsINode
* aNode
) const;
1306 nsTArray
<RefPtr
<AnonymousContent
>>& GetAnonymousContents() {
1307 return mAnonymousContents
;
1310 TimeStamp
GetPageUnloadingEventTimeStamp() const {
1311 if (!mParentDocument
) {
1312 return mPageUnloadingEventTimeStamp
;
1315 TimeStamp
parentTimeStamp(
1316 mParentDocument
->GetPageUnloadingEventTimeStamp());
1317 if (parentTimeStamp
.IsNull()) {
1318 return mPageUnloadingEventTimeStamp
;
1321 if (!mPageUnloadingEventTimeStamp
||
1322 parentTimeStamp
< mPageUnloadingEventTimeStamp
) {
1323 return parentTimeStamp
;
1326 return mPageUnloadingEventTimeStamp
;
1329 void NotifyLayerManagerRecreated();
1331 // Add an element to the list of elements that need their mapped attributes
1332 // resolved to a declaration block.
1334 // These are weak pointers, manually unschedule them when an element is
1335 // removed from the tree.
1336 void ScheduleForPresAttrEvaluation(Element
* aElement
);
1338 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1339 // generally when it's unbound from the tree.
1340 void UnscheduleForPresAttrEvaluation(Element
* aElement
);
1342 // Resolve all presentational attributes scheduled in
1343 // ScheduleForPresAttrEvaluation
1344 void ResolveScheduledPresAttrs() {
1345 if (mLazyPresElements
.IsEmpty()) {
1348 DoResolveScheduledPresAttrs();
1351 Maybe
<ClientInfo
> GetClientInfo() const;
1352 Maybe
<ClientState
> GetClientState() const;
1353 Maybe
<ServiceWorkerDescriptor
> GetController() const;
1355 // Given a node, get a weak reference to it and append that reference to
1356 // mBlockedNodesByClassifier. Can be used later on to look up a node in it.
1357 // (e.g., by the UI)
1359 void AddBlockedNodeByClassifier(nsINode
* aNode
) {
1361 mBlockedNodesByClassifier
.AppendElement(do_GetWeakReference(aNode
));
1365 // Returns the size of the mBlockedNodesByClassifier array.
1367 // This array contains nodes that have been blocked to prevent user tracking,
1368 // fingerprinting, cryptomining, etc. They most likely have had their
1369 // nsIChannel canceled by the URL classifier (Safebrowsing).
1371 // A script can subsequently use GetBlockedNodesByClassifier()
1372 // to get a list of references to these nodes.
1375 // This expresses how many tracking nodes have been blocked for this document
1376 // since its beginning, not how many of them are still around in the DOM tree.
1377 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1378 // array but they are not removed when those nodes are removed from the tree
1379 // or even garbage collected.
1380 size_t BlockedNodeByClassifierCount() const {
1381 return mBlockedNodesByClassifier
.Length();
1384 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1385 // This array contains nodes that have been blocked to prevent
1386 // user tracking. They most likely have had their nsIChannel
1387 // canceled by the URL classifier (Safebrowsing).
1388 already_AddRefed
<nsSimpleContentList
> BlockedNodesByClassifier() const;
1390 // Helper method that returns true if the document has storage-access sandbox
1392 bool StorageAccessSandboxed() const;
1394 // Helper method that returns true if storage access API is enabled and
1395 // the passed flag has storage-access sandbox flag.
1396 static bool StorageAccessSandboxed(uint32_t aSandboxFlags
);
1398 // Returns the cookie jar settings for this and sub contexts.
1399 nsICookieJarSettings
* CookieJarSettings();
1401 // Returns whether this document is using unpartitioned cookies
1402 bool UsingStorageAccess();
1404 // Returns whether the storage access permission of the document is granted by
1406 bool HasStorageAccessPermissionGrantedByAllowList();
1408 // Increments the document generation.
1409 inline void Changed() { ++mGeneration
; }
1411 // Returns the current generation.
1412 inline int32_t GetGeneration() const { return mGeneration
; }
1414 // Adds cached sizes values to aSizes if there's any
1415 // cached value and if the document generation hasn't
1416 // changed since the cache was created.
1417 // Returns true if sizes were added.
1418 bool GetCachedSizes(nsTabSizes
* aSizes
);
1420 // Sets the cache sizes for the current generation.
1421 void SetCachedSizes(nsTabSizes
* aSizes
);
1424 * Should be called when an element's editable changes as a result of
1425 * changing its contentEditable attribute/property.
1427 * The change should be +1 if the contentEditable attribute/property was
1428 * changed to true, -1 if it was changed to false.
1430 void ChangeContentEditableCount(Element
*, int32_t aChange
);
1431 MOZ_CAN_RUN_SCRIPT
void DeferredContentEditableCountChange(Element
*);
1433 enum class EditingState
: int8_t {
1442 * Returns the editing state of the document (not editable, contentEditable or
1445 EditingState
GetEditingState() const { return mEditingState
; }
1448 * Returns whether the document is editable.
1450 bool IsEditingOn() const {
1451 return GetEditingState() == EditingState::eDesignMode
||
1452 GetEditingState() == EditingState::eContentEditable
;
1455 class MOZ_STACK_CLASS nsAutoEditingState
{
1457 nsAutoEditingState(Document
* aDoc
, EditingState aState
)
1458 : mDoc(aDoc
), mSavedState(aDoc
->mEditingState
) {
1459 aDoc
->mEditingState
= aState
;
1461 ~nsAutoEditingState() { mDoc
->mEditingState
= mSavedState
; }
1464 RefPtr
<Document
> mDoc
;
1465 EditingState mSavedState
;
1467 friend class nsAutoEditingState
;
1470 * Set the editing state of the document. Don't use this if you want
1471 * to enable/disable editing, call EditingStateChanged() or
1474 void SetEditingState(EditingState aState
) { mEditingState
= aState
; }
1477 * Called when this Document's editor is destroyed.
1479 void TearingDownEditor();
1481 void SetKeyPressEventModel(uint16_t aKeyPressEventModel
);
1483 // Gets the next form number.
1485 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1486 // parser inserted form element.
1487 int32_t GetNextFormNumber() { return mNextFormNumber
++; }
1489 // Gets the next form control number.
1491 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1492 // parser inserted form control element.
1493 int32_t GetNextControlNumber() { return mNextControlNumber
++; }
1495 PreloadService
& Preloads() { return mPreloadService
; }
1497 bool HasThirdPartyChannel();
1499 bool ShouldIncludeInTelemetry() const;
1501 void AddMediaElementWithMSE();
1502 void RemoveMediaElementWithMSE();
1504 void DoNotifyPossibleTitleChange();
1506 void InitFeaturePolicy();
1507 nsresult
InitFeaturePolicy(nsIChannel
* aChannel
);
1509 void EnsureNotEnteringAndExitFullscreen();
1512 friend class nsUnblockOnloadEvent
;
1514 nsresult
InitCSP(nsIChannel
* aChannel
);
1515 nsresult
InitCOEP(nsIChannel
* aChannel
);
1517 nsresult
InitReferrerInfo(nsIChannel
* aChannel
);
1519 void PostUnblockOnloadEvent();
1521 void DoUnblockOnload();
1523 void DoResolveScheduledPresAttrs();
1525 void RetrieveRelevantHeaders(nsIChannel
* aChannel
);
1527 void TryChannelCharset(nsIChannel
* aChannel
, int32_t& aCharsetSource
,
1528 NotNull
<const Encoding
*>& aEncoding
,
1529 nsHtml5TreeOpExecutor
* aExecutor
);
1531 MOZ_CAN_RUN_SCRIPT
void DispatchContentLoadedEvents();
1533 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1534 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void DispatchPageTransition(
1535 EventTarget
* aDispatchTarget
, const nsAString
& aType
, bool aInFrameSwap
,
1536 bool aPersisted
, bool aOnlySystemGroup
);
1538 // Call this before the document does something that will unbind all content.
1539 // That will stop us from doing a lot of work as each element is removed.
1540 void DestroyElementMaps();
1542 Element
* GetRootElementInternal() const;
1544 void SetPageUnloadingEventTimeStamp() {
1545 MOZ_ASSERT(!mPageUnloadingEventTimeStamp
);
1546 mPageUnloadingEventTimeStamp
= TimeStamp::NowLoRes();
1549 void CleanUnloadEventsTimeStamp() {
1550 MOZ_ASSERT(mPageUnloadingEventTimeStamp
);
1551 mPageUnloadingEventTimeStamp
= TimeStamp();
1555 * Clears any Servo element data stored on Elements in the document.
1557 void ClearStaleServoData();
1560 * Do the tree-disconnection that ResetToURI and document.open need to do.
1562 void DisconnectNodeTree();
1565 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1566 * "CheckKeyPressEventModel" event to check whether we should dispatch
1567 * keypress events in confluent model or split model. This should be
1568 * called only when mEditingState is changed to eDesignMode or
1569 * eConentEditable at first time.
1571 void MaybeDispatchCheckKeyPressEventModelEvent();
1573 /* Midas implementation */
1574 nsCommandManager
* GetMidasCommandManager();
1576 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
TurnEditingOff();
1578 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1579 // of places, and I'm pretty sure the exact ExecCommand call it
1580 // makes cannot actually run script.
1581 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
EditingStateChanged();
1583 void MaybeEditingStateChanged();
1586 // Get the root <html> element, or return null if there isn't one (e.g.
1587 // if the root isn't <html>)
1588 Element
* GetHtmlElement() const;
1589 // Returns the first child of GetHtmlContent which has the given tag,
1590 // or nullptr if that doesn't exist.
1591 Element
* GetHtmlChildElement(nsAtom
* aTag
);
1592 // Get the canonical <body> element, or return null if there isn't one (e.g.
1593 // if the root isn't <html> or if the <body> isn't there)
1594 HTMLBodyElement
* GetBodyElement();
1595 // Get the canonical <head> element, or return null if there isn't one (e.g.
1596 // if the root isn't <html> or if the <head> isn't there)
1597 Element
* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head
); }
1598 // Get the "body" in the sense of document.body: The first <body> or
1599 // <frameset> that's a child of a root <html>
1600 nsGenericHTMLElement
* GetBody();
1601 // Set the "body" in the sense of document.body.
1602 void SetBody(nsGenericHTMLElement
* aBody
, ErrorResult
& rv
);
1603 // Get the "head" element in the sense of document.head.
1604 HTMLSharedElement
* GetHead();
1606 ServoStyleSet
* StyleSetForPresShell() const {
1607 MOZ_ASSERT(!!mStyleSet
.get());
1608 return mStyleSet
.get();
1611 inline ServoStyleSet
& EnsureStyleSet() const;
1613 // ShadowRoot has APIs that can change styles. This notifies the shell that
1614 // stlyes applicable in the shadow tree have potentially changed.
1615 void RecordShadowStyleChange(ShadowRoot
&);
1617 // Needs to be called any time the applicable style can has changed, in order
1618 // to schedule a style flush and setup all the relevant state.
1620 // If we know the stylesheet change applies only to a shadow tree we can avoid
1621 // some work (like updating the font-face-set / counter-styles / etc, as those
1623 void ApplicableStylesChanged(bool aKnownInShadowTree
= false);
1625 // Whether we filled the style set with any style sheet. Only meant to be used
1626 // from DocumentOrShadowRoot::Traverse.
1627 bool StyleSetFilled() const { return mStyleSetFilled
; }
1630 * Accessors to the collection of stylesheets owned by this document.
1631 * Style sheets are ordered, most significant last.
1634 void InsertSheetAt(size_t aIndex
, StyleSheet
&);
1637 * Add a stylesheet to the document
1639 * TODO(emilio): This is only used by parts of editor that are no longer in
1640 * use by m-c or c-c, so remove.
1642 void AddStyleSheet(StyleSheet
* aSheet
) {
1644 InsertSheetAt(SheetCount(), *aSheet
);
1648 * Notify the document that the applicable state of the sheet changed
1649 * and that observers should be notified and style sets updated
1651 void StyleSheetApplicableStateChanged(StyleSheet
&);
1652 void PostStyleSheetApplicableStateChangeEvent(StyleSheet
&);
1653 void PostStyleSheetRemovedEvent(StyleSheet
&);
1654 void PostCustomPropertyRegistered(const dom::PropertyDefinition
&);
1656 enum additionalSheetType
{
1660 AdditionalSheetTypeCount
1663 nsresult
LoadAdditionalStyleSheet(additionalSheetType aType
,
1665 nsresult
AddAdditionalStyleSheet(additionalSheetType aType
,
1666 StyleSheet
* aSheet
);
1667 void RemoveAdditionalStyleSheet(additionalSheetType aType
, nsIURI
* sheetURI
);
1669 StyleSheet
* GetFirstAdditionalAuthorSheet() {
1670 return mAdditionalSheets
[eAuthorSheet
].SafeElementAt(0);
1674 * Returns the index that aSheet should be inserted at to maintain document
1677 size_t FindDocStyleSheetInsertionPoint(const StyleSheet
& aSheet
);
1680 * Get this document's CSSLoader. This is guaranteed to not return null.
1682 css::Loader
* CSSLoader() const { return mCSSLoader
; }
1685 * Get this document's StyleImageLoader. This is guaranteed to not return
1688 css::ImageLoader
* StyleImageLoader() const { return mStyleImageLoader
; }
1691 * Get the channel that was passed to StartDocumentLoad or Reset for this
1692 * document. Note that this may be null in some cases (eg if
1693 * StartDocumentLoad or Reset were never called)
1695 nsIChannel
* GetChannel() const { return mChannel
; }
1698 * Get this document's attribute stylesheet. May return null if
1701 AttributeStyles
* GetAttributeStyles() const { return mAttributeStyles
.get(); }
1703 virtual void SetScriptGlobalObject(nsIScriptGlobalObject
* aGlobalObject
);
1706 * Get/set the object from which the context for the event/script handling can
1707 * be got. Normally GetScriptHandlingObject() returns the same object as
1708 * GetScriptGlobalObject(), but if the document is loaded as data,
1709 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1710 * aHasHadScriptHandlingObject is set true if document has had the object
1711 * for event/script handling. Do not process any events/script if the method
1712 * returns null, but aHasHadScriptHandlingObject is true.
1714 nsIScriptGlobalObject
* GetScriptHandlingObject(
1715 bool& aHasHadScriptHandlingObject
) const {
1716 aHasHadScriptHandlingObject
= mHasHadScriptHandlingObject
;
1717 return mScriptGlobalObject
? mScriptGlobalObject
.get()
1718 : GetScriptHandlingObjectInternal();
1720 void SetScriptHandlingObject(nsIScriptGlobalObject
* aScriptObject
);
1723 * Get the object that is used as the scope for all of the content
1724 * wrappers whose owner document is this document. Unlike the script global
1725 * object, this will only return null when the global object for this
1726 * document is truly gone. Use this object when you're trying to find a
1727 * content wrapper in XPConnect.
1729 nsIGlobalObject
* GetScopeObject() const;
1730 void SetScopeObject(nsIGlobalObject
* aGlobal
);
1733 * Return the window containing the document (the outer window).
1735 nsPIDOMWindowOuter
* GetWindow() const {
1736 return mWindow
? mWindow
->GetOuterWindow() : GetWindowInternal();
1739 bool IsInBackgroundWindow() const {
1740 auto* outer
= mWindow
? mWindow
->GetOuterWindow() : nullptr;
1741 return outer
&& outer
->IsBackground();
1745 * Return the inner window used as the script compilation scope for
1746 * this document. If you're not absolutely sure you need this, use
1749 nsPIDOMWindowInner
* GetInnerWindow() const {
1750 return mRemovedFromDocShell
? nullptr : mWindow
;
1754 * Return the outer window ID.
1756 uint64_t OuterWindowID() const {
1757 nsPIDOMWindowOuter
* window
= GetWindow();
1758 return window
? window
->WindowID() : 0;
1762 * Return the inner window ID.
1764 uint64_t InnerWindowID() const {
1765 nsPIDOMWindowInner
* window
= GetInnerWindow();
1766 return window
? window
->WindowID() : 0;
1770 * Return WindowGlobalChild that is associated with the inner window.
1772 WindowGlobalChild
* GetWindowGlobalChild() {
1773 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1778 * Return WindowContext associated with the inner window.
1780 WindowContext
* GetWindowContext() const {
1781 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1784 bool IsTopLevelWindowInactive() const {
1785 return mState
.HasState(DocumentState::WINDOW_INACTIVE
);
1789 * Get the script loader for this document
1791 dom::ScriptLoader
* ScriptLoader() { return mScriptLoader
; }
1794 * Add/Remove an element to the document's id and name hashes
1796 void AddToIdTable(Element
* aElement
, nsAtom
* aId
);
1797 void RemoveFromIdTable(Element
* aElement
, nsAtom
* aId
);
1798 void AddToNameTable(Element
* aElement
, nsAtom
* aName
);
1799 void RemoveFromNameTable(Element
* aElement
, nsAtom
* aName
);
1802 * Returns all elements in the top layer in the insertion order.
1804 nsTArray
<Element
*> GetTopLayer() const;
1806 bool TopLayerContains(Element
&) const;
1808 // Do the "fullscreen element ready check" from the fullscreen spec.
1809 // It returns true if the given element is allowed to go into fullscreen.
1810 // It is responsive to dispatch "fullscreenerror" event when necessary.
1811 bool FullscreenElementReadyCheck(FullscreenRequest
&);
1814 * When this is called on content process, this asynchronously requests that
1815 * the document make aElement the fullscreen element, and move into fullscreen
1816 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1817 * and it can be returned to fullscreen status by calling
1818 * RestorePreviousFullscreenState().
1819 * If on chrome process, this is synchronously.
1821 * Note that requesting fullscreen in a document also makes the element which
1822 * contains this document in this document's parent document fullscreen. i.e.
1823 * the <iframe> or <browser> that contains this document is also mode
1824 * fullscreen. This happens recursively in all ancestor documents.
1826 void RequestFullscreen(UniquePtr
<FullscreenRequest
> aRequest
,
1827 bool aApplyFullscreenDirectly
= false);
1830 void RequestFullscreenInContentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1831 bool aApplyFullscreenDirectly
);
1832 void RequestFullscreenInParentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1833 bool aApplyFullscreenDirectly
);
1835 // Pushes aElement onto the top layer
1836 void TopLayerPush(Element
&);
1838 // Removes the topmost element for which aPredicate returns true from the top
1839 // layer. The removed element, if any, is returned.
1840 Element
* TopLayerPop(FunctionRef
<bool(Element
*)> aPredicate
);
1842 // Removes the given element from the top layer. The removed element, if any,
1844 Element
* TopLayerPop(Element
&);
1846 MOZ_CAN_RUN_SCRIPT
bool TryAutoFocusCandidate(Element
& aElement
);
1849 // Removes all the elements with fullscreen flag set from the top layer, and
1850 // clears their fullscreen flag.
1851 void CleanupFullscreenState();
1853 // Pops the fullscreen element from the top layer and clears its
1854 // fullscreen flag. Returns whether there was any fullscreen element.
1855 enum class UpdateViewport
: bool { No
, Yes
};
1856 bool PopFullscreenElement(UpdateViewport
= UpdateViewport::Yes
);
1858 // Pushes the given element into the top of top layer and set fullscreen
1860 void SetFullscreenElement(Element
&);
1862 // Whether we has pending fullscreen request.
1863 bool HasPendingFullscreenRequests();
1866 * When Esc key is pressed, cancel the dialog element if the document is
1867 * blocked by the dialog or hide popover if popover is shown.
1869 MOZ_CAN_RUN_SCRIPT
void HandleEscKey();
1871 void AddModalDialog(HTMLDialogElement
&);
1872 void RemoveModalDialog(HTMLDialogElement
&);
1875 * Called when a frame in a child process has entered fullscreen or when a
1876 * fullscreen frame in a child process changes to another origin.
1877 * aFrameElement is the frame element which contains the child-process
1878 * fullscreen document.
1880 void RemoteFrameFullscreenChanged(Element
* aFrameElement
);
1883 * Called when a frame in a remote child document has rolled back fullscreen
1884 * so that all its top layer are empty; we must continue the
1885 * rollback in this parent process' doc tree branch which is fullscreen.
1886 * Note that only one branch of the document tree can have its documents in
1887 * fullscreen state at one time. We're in inconsistent state if a
1888 * fullscreen document has a parent and that parent isn't fullscreen. We
1889 * preserve this property across process boundaries.
1891 void RemoteFrameFullscreenReverted();
1894 * Restores the previous fullscreen element to fullscreen status. If there
1895 * is no former fullscreen element, this exits fullscreen, moving the
1896 * top-level browser window out of fullscreen mode.
1898 void RestorePreviousFullscreenState(UniquePtr
<FullscreenExit
>);
1901 * Returns true if this document is a fullscreen leaf document, i.e. it
1902 * is in fullscreen mode and has no fullscreen children.
1904 bool IsFullscreenLeaf();
1907 * Returns the document which is at the root of this document's branch
1908 * in the in-process document tree. Returns nullptr if the document isn't
1911 Document
* GetFullscreenRoot() const { return mFullscreenRoot
; }
1913 size_t CountFullscreenElements() const;
1916 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1919 void SetFullscreenRoot(Document
* aRoot
) { mFullscreenRoot
= aRoot
; }
1922 * Synchronously cleans up the fullscreen state on the given document.
1924 * Calling this without performing fullscreen transition could lead
1925 * to undesired effect (the transition happens after document state
1926 * flips), hence it should only be called either by nsGlobalWindow
1927 * when we have performed the transition, or when it is necessary to
1928 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1929 * should be called instead.
1931 * aDocument must not be null.
1933 static void ExitFullscreenInDocTree(Document
* aDocument
);
1936 * Ask the document to exit fullscreen state asynchronously.
1938 * Different from ExitFullscreenInDocTree(), this allows the window
1939 * to perform fullscreen transition first if any.
1941 * If aDocument is null, it will exit fullscreen from all documents
1944 static void AsyncExitFullscreen(Document
* aDocument
);
1947 * Handles any pending fullscreen in aDocument or its subdocuments.
1949 * Returns whether there is any fullscreen request handled.
1951 static bool HandlePendingFullscreenRequests(Document
* aDocument
);
1954 * Clear pending fullscreen in aDocument.
1956 static void ClearPendingFullscreenRequests(Document
* aDocument
);
1958 // ScreenOrientation related APIs
1960 void ClearOrientationPendingPromise();
1961 bool SetOrientationPendingPromise(Promise
* aPromise
);
1962 Promise
* GetOrientationPendingPromise() const {
1963 return mOrientationPendingPromise
;
1966 //----------------------------------------------------------------------
1968 // Document notification API's
1971 * Add a new observer of document change notifications. Whenever
1972 * content is changed, appended, inserted or removed the observers are
1973 * informed. An observer that is already observing the document must
1974 * not be added without being removed first.
1976 void AddObserver(nsIDocumentObserver
* aObserver
);
1979 * Remove an observer of document change notifications. This will
1980 * return false if the observer cannot be found.
1982 bool RemoveObserver(nsIDocumentObserver
* aObserver
);
1984 // Observation hooks used to propagate notifications to document observers.
1985 // BeginUpdate must be called before any batch of modifications of the
1986 // content model or of style data, EndUpdate must be called afterward.
1987 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1990 uint32_t UpdateNestingLevel() { return mUpdateNestLevel
; }
1993 virtual void EndLoad();
1996 READYSTATE_UNINITIALIZED
= 0,
1997 READYSTATE_LOADING
= 1,
1998 READYSTATE_INTERACTIVE
= 3,
1999 READYSTATE_COMPLETE
= 4
2001 // Set the readystate of the document. If aUpdateTimingInformation is true,
2002 // this will record relevant timestamps in the document's performance timing.
2003 // Some consumers (document.open is the only one right now, actually) don't
2004 // want to do that, though.
2005 void SetReadyStateInternal(ReadyState
, bool aUpdateTimingInformation
= true);
2006 ReadyState
GetReadyStateEnum() { return mReadyState
; }
2008 void NotifyLoading(bool aNewParentIsLoading
, const ReadyState
& aCurrentState
,
2009 ReadyState aNewState
);
2011 void NotifyAbortedLoad();
2013 // Notify that an element changed state. This must happen under a
2014 // scriptblocker but NOT within a begin/end update.
2015 void ElementStateChanged(Element
*, ElementState
);
2017 // Update a set of document states that may have changed.
2018 // This should only be called by callers whose state is also reflected in the
2019 // implementation of Document::State.
2021 // aNotify controls whether we notify our DocumentStatesChanged observers.
2022 void UpdateDocumentStates(DocumentState aMaybeChangedStates
, bool aNotify
);
2024 void ResetDocumentDirection();
2026 // Observation hooks for style data to propagate notifications
2027 // to document observers
2028 void RuleChanged(StyleSheet
&, css::Rule
*, StyleRuleChangeKind
);
2029 void RuleAdded(StyleSheet
&, css::Rule
&);
2030 void RuleRemoved(StyleSheet
&, css::Rule
&);
2031 void SheetCloned(StyleSheet
&) {}
2032 void ImportRuleLoaded(CSSImportRule
&, StyleSheet
&);
2035 * Flush notifications for this document and its parent documents
2036 * (since those may affect the layout of this one).
2038 void FlushPendingNotifications(FlushType aType
);
2041 * Another variant of the above FlushPendingNotifications. This function
2042 * takes a ChangesToFlush to specify whether throttled animations are flushed
2044 * If in doubt, use the above FlushPendingNotifications.
2046 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2047 void FlushPendingNotifications(ChangesToFlush aFlush
);
2050 * Calls FlushPendingNotifications on any external resources this document
2051 * has. If this document has no external resources or is an external resource
2052 * itself this does nothing. This should only be called with
2053 * aType >= FlushType::Style.
2055 void FlushExternalResources(FlushType aType
);
2057 void AddWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2058 void RemoveWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2060 // Triggers an update of <svg:use> element shadow trees.
2061 void UpdateSVGUseElementShadowTrees() {
2062 if (mSVGUseElementsNeedingShadowTreeUpdate
.IsEmpty()) {
2065 DoUpdateSVGUseElementShadowTrees();
2069 * Only to be used inside Gecko, you can't really do anything with the
2070 * pointer outside Gecko anyway.
2072 nsNodeInfoManager
* NodeInfoManager() const { return mNodeInfoManager
; }
2075 * Reset the document using the given channel and loadgroup. This works
2076 * like ResetToURI, but also sets the document's channel to aChannel.
2077 * The principal of the document will be set from the channel.
2079 virtual void Reset(nsIChannel
* aChannel
, nsILoadGroup
* aLoadGroup
);
2082 * Reset this document to aURI, aLoadGroup, aPrincipal and
2083 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2084 * content principal based on aURI will be used.
2086 virtual void ResetToURI(nsIURI
* aURI
, nsILoadGroup
* aLoadGroup
,
2087 nsIPrincipal
* aPrincipal
,
2088 nsIPrincipal
* aPartitionedPrincipal
);
2091 * Set the container (docshell) for this document. Virtual so that
2092 * docshell can call it.
2094 virtual void SetContainer(nsDocShell
* aContainer
);
2097 * Get the container (docshell) for this document.
2099 nsISupports
* GetContainer() const;
2102 * Get the container's load context for this document.
2104 nsILoadContext
* GetLoadContext() const;
2107 * Get docshell the for this document.
2109 nsIDocShell
* GetDocShell() const;
2112 * Set and get XML declaration. If aVersion is null there is no declaration.
2113 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2114 * was no standalone parameter in the declaration, that it was given as no,
2115 * or that it was given as yes.
2117 void SetXMLDeclaration(const char16_t
* aVersion
, const char16_t
* aEncoding
,
2118 const int32_t aStandalone
);
2119 void GetXMLDeclaration(nsAString
& aVersion
, nsAString
& aEncoding
,
2120 nsAString
& Standalone
);
2123 * Returns the bits for the color-scheme specified by the
2124 * <meta name="color-scheme">.
2126 uint8_t GetColorSchemeBits() const { return mColorSchemeBits
; }
2129 * Traverses the DOM and computes the supported color schemes as per
2130 * https://html.spec.whatwg.org/#meta-color-scheme
2132 void RecomputeColorScheme();
2133 void AddColorSchemeMeta(HTMLMetaElement
&);
2134 void RemoveColorSchemeMeta(HTMLMetaElement
&);
2137 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2138 * regular HTML document with Content-Type "text/html", image documents and
2139 * media documents). Returns false for XHTML and any other documents parsed
2140 * by the XML parser.
2142 bool IsHTMLDocument() const { return mType
== eHTML
; }
2143 bool IsHTMLOrXHTML() const { return mType
== eHTML
|| mType
== eXHTML
; }
2144 bool IsImageDocument() const {
2145 return MediaDocumentKind() == MediaDocumentKind::Image
;
2147 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2148 bool IsSVGDocument() const { return mType
== eSVG
; }
2149 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2150 bool LoadsFullXULStyleSheetUpFront() {
2151 if (IsSVGDocument()) {
2154 return AllowXULXBL();
2157 bool IsScriptEnabled() const;
2160 * Returns true if this document was created from a nsXULPrototypeDocument.
2162 bool LoadedFromPrototype() const { return mPrototypeDocument
; }
2164 * Returns the prototype the document was created from, or null if it was not
2165 * created from a prototype.
2167 nsXULPrototypeDocument
* GetPrototype() const { return mPrototypeDocument
; }
2169 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument
; }
2170 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument
) {
2171 mIsTopLevelContentDocument
= aIsTopLevelContentDocument
;
2174 bool IsContentDocument() const { return mIsContentDocument
; }
2175 void SetIsContentDocument(bool aIsContentDocument
) {
2176 mIsContentDocument
= aIsContentDocument
;
2179 void ProcessMETATag(HTMLMetaElement
* aMetaElement
);
2181 * Create an element with the specified name, prefix and namespace ID.
2182 * Returns null if element name parsing failed.
2184 already_AddRefed
<Element
> CreateElem(const nsAString
& aName
, nsAtom
* aPrefix
,
2185 int32_t aNamespaceID
,
2186 const nsAString
* aIs
= nullptr);
2189 * Get the security info (i.e. SSL state etc) that the document got
2190 * from the channel/document that created the content of the
2195 nsITransportSecurityInfo
* GetSecurityInfo() { return mSecurityInfo
; }
2198 * Get the channel that failed to load and resulted in an error page, if it
2199 * exists. This is only relevant to error pages.
2201 nsIChannel
* GetFailedChannel() const { return mFailedChannel
; }
2204 * This function checks if the document that is trying to access
2205 * GetNetErrorInfo is a trusted about net error page or not.
2207 static bool CallerIsTrustedAboutNetError(JSContext
* aCx
, JSObject
* aObject
);
2210 * This function checks if the document that is trying to access
2211 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2213 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext
* aCx
,
2217 * Get security info like error code for a failed channel. This
2218 * property is only exposed to about:neterror documents.
2220 void GetNetErrorInfo(mozilla::dom::NetErrorInfo
& aInfo
, ErrorResult
& aRv
);
2223 * This function checks if the document that is trying to access
2224 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2226 static bool CallerIsTrustedAboutCertError(JSContext
* aCx
, JSObject
* aObject
);
2229 * This function checks if the privilege storage access api is available for
2230 * the caller. We only allow privilege SSA to be called by system principal
2231 * and webcompat extension.
2233 static bool CallerCanAccessPrivilegeSSA(JSContext
* aCx
, JSObject
* aObject
);
2236 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2237 * failed Channel. This property is only exposed for about:certerror
2240 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo
& aInfo
,
2244 * Set the channel that failed to load and resulted in an error page.
2245 * This is only relevant to error pages.
2247 void SetFailedChannel(nsIChannel
* aChannel
) { mFailedChannel
= aChannel
; }
2250 * Returns the default namespace ID used for elements created in this
2253 int32_t GetDefaultNamespaceID() const { return mDefaultElementType
; }
2255 void RemoveAllProperties();
2256 void RemoveAllPropertiesFor(nsINode
* aNode
);
2258 nsPropertyTable
& PropertyTable() { return mPropertyTable
; }
2261 * Sets the ID used to identify this part of the multipart document
2263 void SetPartID(uint32_t aID
) { mPartID
= aID
; }
2266 * Return the ID used to identify this part of the multipart document
2268 uint32_t GetPartID() const { return mPartID
; }
2271 * Sanitize the document by resetting all input elements and forms that have
2272 * autocomplete=off to their default values.
2273 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2275 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Sanitize();
2278 * Enumerate all subdocuments.
2279 * The enumerator callback should return CallState::Continue to continue
2280 * enumerating, or CallState::Stop to stop. This will never get passed a null
2283 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
2284 void EnumerateSubDocuments(SubDocEnumFunc aCallback
);
2287 * Collect all the descendant documents for which |aCalback| returns true.
2288 * The callback function must not mutate any state for the given document.
2290 using nsDocTestFunc
= bool (*)(const Document
* aDocument
);
2291 void CollectDescendantDocuments(nsTArray
<RefPtr
<Document
>>& aDescendants
,
2292 nsDocTestFunc aCallback
) const;
2295 * Check whether it is safe to cache the presentation of this document
2296 * and all of its subdocuments (depending on the 3rd param). This method
2297 * checks the following conditions recursively:
2298 * - Some document types, such as plugin documents, cannot be safely cached.
2299 * - If there are any pending requests, we don't allow the presentation
2300 * to be cached. Ideally these requests would be suspended and resumed,
2301 * but that is difficult in some cases, such as XMLHttpRequest.
2302 * - If there are any beforeunload or unload listeners, we must fire them
2303 * for correctness, but this likely puts the document into a state where
2304 * it would not function correctly if restored.
2306 * |aNewRequest| should be the request for a new document which will
2307 * replace this document in the docshell. The new document's request
2308 * will be ignored when checking for active requests. If there is no
2309 * request associated with the new document, this parameter may be null.
2311 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2312 * combination is when we try to BFCache aNewRequest
2314 virtual bool CanSavePresentation(nsIRequest
* aNewRequest
,
2315 uint32_t& aBFCacheCombo
,
2316 bool aIncludeSubdocuments
,
2317 bool aAllowUnloadListeners
= true);
2320 * Pass principals if the correct ones are known when calling Init. That way
2321 * NodeInfoManager doesn't need to create a temporary null principal.
2323 virtual nsresult
Init(nsIPrincipal
* aPrincipal
,
2324 nsIPrincipal
* aPartitionedPrincipal
);
2327 * Notify the document that its associated ContentViewer is being destroyed.
2328 * This releases circular references so that the document can go away.
2329 * Destroy() is only called on documents that have a content viewer.
2331 virtual void Destroy();
2334 * Notify the document that its associated ContentViewer is no longer
2335 * the current viewer for the docshell. The document might still
2336 * be rendered in "zombie state" until the next document is ready.
2337 * The document should save form control state.
2339 void RemovedFromDocShell();
2342 * Get the layout history state that should be used to save and restore state
2343 * for nodes in this document. This may return null; if that happens state
2344 * saving and restoration is not possible.
2346 already_AddRefed
<nsILayoutHistoryState
> GetLayoutHistoryState() const;
2349 * Methods that can be used to prevent onload firing while an event that
2350 * should block onload is posted. onload is guaranteed to not fire until
2351 * either all calls to BlockOnload() have been matched by calls to
2352 * UnblockOnload() or the load has been stopped altogether (by the user
2353 * pressing the Stop button, say).
2357 * @param aFireSync whether to fire onload synchronously. If false,
2358 * onload will fire asynchronously after all onload blocks have been
2359 * removed. It will NOT fire from inside UnblockOnload. If true,
2360 * onload may fire from inside UnblockOnload.
2362 void UnblockOnload(bool aFireSync
);
2364 // Only BlockOnload should call this!
2365 void AsyncBlockOnload();
2367 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded
; }
2369 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnblockDOMContentLoaded();
2372 * Notification that the page has been shown, for documents which are loaded
2373 * into a DOM window. This corresponds to the completion of document load,
2374 * or to the page's presentation being restored into an existing DOM window.
2375 * This notification fires applicable DOM events to the content window. See
2376 * PageTransitionEvent.webidl for a description of the |aPersisted|
2377 * parameter. If aDispatchStartTarget is null, the pageshow event is
2378 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2379 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2380 * event is only dispatched to listeners in the system group.
2381 * Note: if aDispatchStartTarget isn't null, the showing state of the
2382 * document won't be altered.
2384 virtual void OnPageShow(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2385 bool aOnlySystemGroup
= false);
2388 * Notification that the page has been hidden, for documents which are loaded
2389 * into a DOM window. This corresponds to the unloading of the document, or
2390 * to the document's presentation being saved but removed from an existing
2391 * DOM window. This notification fires applicable DOM events to the content
2392 * window. See PageTransitionEvent.webidl for a description of the
2393 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2394 * event is dispatched on the ScriptGlobalObject for this document,
2395 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2396 * true, the event is only dispatched to listeners in the system group.
2397 * Note: if aDispatchStartTarget isn't null, the showing state of the
2398 * document won't be altered.
2400 void OnPageHide(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2401 bool aOnlySystemGroup
= false);
2404 * We record the set of links in the document that are relevant to
2408 * Notification that an element is a link that is relevant to style.
2410 void AddStyleRelevantLink(Link
* aLink
) {
2411 NS_ASSERTION(aLink
, "Passing in a null link. Expect crashes RSN!");
2413 NS_ASSERTION(!mStyledLinks
.Contains(aLink
),
2414 "Document already knows about this Link!");
2415 mStyledLinksCleared
= false;
2417 mStyledLinks
.Insert(aLink
);
2421 * Notification that an element is a link and its URI might have been
2422 * changed or the element removed. If the element is still a link relevant
2423 * to style, then someone must ensure that AddStyleRelevantLink is
2424 * (eventually) called on it again.
2426 void ForgetLink(Link
* aLink
) {
2427 MOZ_ASSERT(aLink
, "Passing in a null link. Expect crashes RSN!");
2428 MOZ_ASSERT(mStyledLinks
.Contains(aLink
) || mStyledLinksCleared
,
2429 "Document knows nothing about this Link!");
2430 mStyledLinks
.Remove(aLink
);
2433 // Refreshes the hrefs of all the links in the document.
2434 void RefreshLinkHrefs();
2437 * Support for window.matchMedia()
2440 already_AddRefed
<MediaQueryList
> MatchMedia(const nsACString
& aMediaQueryList
,
2441 CallerType aCallerType
);
2443 LinkedList
<MediaQueryList
>& MediaQueryLists() { return mDOMMediaQueryLists
; }
2445 nsTHashtable
<LCPEntryHashEntry
>& ContentIdentifiersForLCP() {
2446 return mContentIdentifiersForLCP
;
2450 * Get the compatibility mode for this document
2452 nsCompatibility
GetCompatibilityMode() const { return mCompatMode
; }
2455 * Check whether we've ever fired a DOMTitleChanged event for this
2458 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange
; }
2461 * To batch DOMSubtreeModified, document needs to be informed when
2462 * a mutation event might be dispatched, even if the event isn't actually
2463 * created because there are no listeners for it.
2465 * @param aTarget is the target for the mutation event.
2467 void MayDispatchMutationEvent(nsINode
* aTarget
) {
2468 if (mSubtreeModifiedDepth
> 0) {
2469 mSubtreeModifiedTargets
.AppendObject(aTarget
);
2474 * Marks as not-going-to-be-collected for the given generation of
2477 void MarkUncollectableForCCGeneration(uint32_t aGeneration
) {
2478 mMarkedCCGeneration
= aGeneration
;
2482 * Gets the cycle collector generation this document is marked for.
2484 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration
; }
2487 * Returns whether this document is cookie averse. See
2488 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2490 bool IsCookieAverse() const {
2491 // If we are a document that "has no browsing context."
2492 if (!GetInnerWindow()) {
2496 // If we are a document "whose URL's scheme is not a network scheme."
2497 // NB: Explicitly allow file: URIs to store cookies.
2499 return !NodePrincipal()->SchemeIs("http") &&
2500 !NodePrincipal()->SchemeIs("https") &&
2501 !NodePrincipal()->SchemeIs("file");
2504 bool IsLoadedAsData() { return mLoadedAsData
; }
2506 void SetAddedToMemoryReportAsDataDocument() {
2507 mAddedToMemoryReportingAsDataDocument
= true;
2510 void UnregisterFromMemoryReportingForDataDocument();
2512 bool MayStartLayout() { return mMayStartLayout
; }
2514 void SetMayStartLayout(bool aMayStartLayout
);
2516 already_AddRefed
<nsIDocumentEncoder
> GetCachedEncoder();
2518 void SetCachedEncoder(already_AddRefed
<nsIDocumentEncoder
> aEncoder
);
2520 // In case of failure, the document really can't initialize the frame loader.
2521 nsresult
InitializeFrameLoader(nsFrameLoader
* aLoader
);
2522 // In case of failure, the caller must handle the error, for example by
2523 // finalizing frame loader asynchronously.
2524 nsresult
FinalizeFrameLoader(nsFrameLoader
* aLoader
, nsIRunnable
* aFinalizer
);
2525 // Removes the frame loader of aShell from the initialization list.
2526 void TryCancelFrameLoaderInitialization(nsIDocShell
* aShell
);
2529 * Check whether this document is a root document that is not an
2530 * external resource.
2532 bool IsRootDisplayDocument() const {
2533 return !mParentDocument
&& !mDisplayDocument
;
2536 bool ChromeRulesEnabled() const { return mChromeRulesEnabled
; }
2538 bool IsInChromeDocShell() const {
2539 const Document
* root
= this;
2540 while (const Document
* displayDoc
= root
->GetDisplayDocument()) {
2543 return root
->mInChromeDocShell
;
2546 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage
; }
2548 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage
= true; }
2550 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument
; }
2552 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument
= true; }
2554 bool IsResourceDoc() const {
2555 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2556 mHasDisplayDocument
; // Are we an external resource doc?
2560 * Get the document for which this document is an external resource. This
2561 * will be null if this document is not an external resource. Otherwise,
2562 * GetDisplayDocument() will return a non-null document, and
2563 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2565 Document
* GetDisplayDocument() const { return mDisplayDocument
; }
2568 * Set the display document for this document. aDisplayDocument must not be
2571 void SetDisplayDocument(Document
* aDisplayDocument
) {
2572 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2573 "Shouldn't set mDisplayDocument on documents that already "
2574 "have a presentation or a docshell or a window");
2575 MOZ_ASSERT(aDisplayDocument
, "Must not be null");
2576 MOZ_ASSERT(aDisplayDocument
!= this, "Should be different document");
2577 MOZ_ASSERT(!aDisplayDocument
->GetDisplayDocument(),
2578 "Display documents should not nest");
2579 mDisplayDocument
= aDisplayDocument
;
2580 mHasDisplayDocument
= !!aDisplayDocument
;
2584 * Request an external resource document for aURI. This will return the
2585 * resource document if available. If one is not available yet, it will
2586 * start loading as needed, and the pending load object will be returned in
2587 * aPendingLoad so that the caller can register an observer to wait for the
2588 * load. If this function returns null and doesn't return a pending load,
2589 * that means that there is no resource document for this URI and won't be
2590 * one in the future.
2592 * @param aURI the URI to get
2593 * @param aReferrerInfo the referrerInfo of the request
2594 * @param aRequestingNode the node making the request
2595 * @param aPendingLoad the pending load for this request, if any
2597 Document
* RequestExternalResource(nsIURI
* aURI
,
2598 nsIReferrerInfo
* aReferrerInfo
,
2599 nsINode
* aRequestingNode
,
2600 ExternalResourceLoad
** aPendingLoad
);
2603 * Enumerate the external resource documents associated with this document.
2604 * The enumerator callback should return CallState::Continue to continue
2605 * enumerating, or CallState::Stop to stop. This callback will never get
2606 * passed a null aDocument.
2608 void EnumerateExternalResources(SubDocEnumFunc aCallback
);
2610 dom::ExternalResourceMap
& ExternalResourceMap() {
2611 return mExternalResourceMap
;
2615 * Return whether the document is currently showing (in the sense of
2616 * OnPageShow() having been called already and OnPageHide() not having been
2619 bool IsShowing() const { return mIsShowing
; }
2621 * Return whether the document is currently visible (in the sense of
2622 * OnPageHide having been called and OnPageShow not yet having been called)
2624 bool IsVisible() const { return mVisible
; }
2626 void SetSuppressedEventListener(EventListener
* aListener
);
2628 EventListener
* GetSuppressedEventListener() {
2629 return mSuppressedEventListener
;
2633 * Return true when this document is active, i.e., an active document
2634 * in a content viewer and not in the bfcache.
2635 * This does NOT match the "active document" concept in the WHATWG spec -
2636 * see IsCurrentActiveDocument.
2638 bool IsActive() const;
2641 * Return true if this is the current active document for its
2642 * docshell. Note that a docshell may have multiple active documents
2643 * due to the bfcache -- this should be used when you need to
2644 * differentiate the *current* active document from any active
2647 bool IsCurrentActiveDocument() const {
2648 nsPIDOMWindowInner
* inner
= GetInnerWindow();
2649 return inner
&& inner
->IsCurrentInnerWindow() && inner
->GetDoc() == this;
2653 * Returns whether this document should perform image loads.
2655 bool ShouldLoadImages() const {
2656 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2657 // images can themselves have data: URL image references.
2658 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2662 void SetHasPrintCallbacks() {
2663 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2664 mHasPrintCallbacks
= true;
2667 bool HasPrintCallbacks() const { return mHasPrintCallbacks
; }
2670 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2671 * the document's activity changes such as OnPageHide, visibility, activity.
2672 * The ActivityObserver objects can be nsIObjectLoadingContent or
2673 * nsIDocumentActivity or HTMLMEdiaElement.
2675 void RegisterActivityObserver(nsISupports
* aSupports
);
2676 bool UnregisterActivityObserver(nsISupports
* aSupports
);
2677 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2678 using ActivityObserverEnumerator
= FunctionRef
<void(nsISupports
*)>;
2679 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator
);
2681 void NotifyActivityChanged();
2683 // Indicates whether mAnimationController has been (lazily) initialized.
2684 // If this returns true, we're promising that GetAnimationController()
2685 // will have a non-null return value.
2686 bool HasAnimationController() { return !!mAnimationController
; }
2688 // Getter for this document's SMIL Animation Controller. Performs lazy
2689 // initialization, if this document supports animation and if
2690 // mAnimationController isn't yet initialized.
2692 // If HasAnimationController is true, this is guaranteed to return non-null.
2693 SMILAnimationController
* GetAnimationController();
2695 // Gets the tracker for scroll-driven animations that are waiting to start.
2696 // Returns nullptr if there is no scroll-driven animation tracker for this
2697 // document which will be the case if there have never been any scroll-driven
2698 // animations in the document.
2699 ScrollTimelineAnimationTracker
* GetScrollTimelineAnimationTracker() {
2700 return mScrollTimelineAnimationTracker
;
2703 // Gets the tracker for scroll-driven animations that are waiting to start and
2704 // creates it if it doesn't already exist. As a result, the return value
2705 // will never be nullptr.
2706 ScrollTimelineAnimationTracker
* GetOrCreateScrollTimelineAnimationTracker();
2709 * Prevents user initiated events from being dispatched to the document and
2712 void SuppressEventHandling(uint32_t aIncrease
= 1);
2715 * Unsuppress event handling.
2716 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2719 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnsuppressEventHandlingAndFireEvents(
2722 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed
; }
2724 bool IsEventHandlingEnabled() const {
2725 return !EventHandlingSuppressed() && mScriptGlobalObject
;
2728 bool WouldScheduleFrameRequestCallbacks() const {
2729 // If this function changes to depend on some other variable, make sure to
2730 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2731 // where that variable can change.
2732 return mPresShell
&& IsEventHandlingEnabled();
2735 void DecreaseEventSuppression() {
2736 MOZ_ASSERT(mEventsSuppressed
);
2737 --mEventsSuppressed
;
2738 UpdateFrameRequestCallbackSchedulingState();
2742 * Some clipboard commands are unconditionally enabled on some documents, so
2743 * as to always dispatch copy / paste events even though you'd normally not be
2746 bool AreClipboardCommandsUnconditionallyEnabled() const;
2749 * Note a ChannelEventQueue which has been suspended on the document's behalf
2750 * to prevent XHRs from running content scripts while event handling is
2751 * suppressed. The document is responsible for resuming the queue after
2752 * event handling is unsuppressed.
2754 void AddSuspendedChannelEventQueue(net::ChannelEventQueue
* aQueue
);
2757 * Returns true if a postMessage event should be suspended instead of running.
2758 * The document is responsible for running the event later, in the order they
2761 bool SuspendPostMessageEvent(PostMessageEvent
* aEvent
);
2764 * Run any suspended postMessage events, or clear them.
2766 void FireOrClearPostMessageEvents(bool aFireEvents
);
2768 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent
= true; }
2771 * Flag whether we're about to fire the window's load event for this document.
2773 void SetLoadEventFiring(bool aFiring
) { mLoadEventFiring
= aFiring
; }
2776 * Test whether we should be firing a load event for this document after a
2777 * document.close(). This is public and on Document, instead of being private
2778 * to Document, because we need to go through the normal docloader logic
2779 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2780 * semantics of firing the load event; we just don't want to fire the load
2781 * event if this tests true. So we need the docloader to be able to access
2784 * This method should only be called at the point when the load event is about
2785 * to be fired. It resets the "skip" flag, so it is not idempotent.
2787 bool SkipLoadEventAfterClose() {
2788 bool skip
= mSkipLoadEventAfterClose
;
2789 mSkipLoadEventAfterClose
= false;
2794 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2796 void IncrementIgnoreDestructiveWritesCounter() {
2797 ++mIgnoreDestructiveWritesCounter
;
2801 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2803 void DecrementIgnoreDestructiveWritesCounter() {
2804 --mIgnoreDestructiveWritesCounter
;
2807 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch
; }
2810 * Returns true if this document is allowed to contain XUL element and
2811 * use non-builtin XBL bindings.
2813 bool AllowXULXBL() {
2814 return mAllowXULXBL
== eTriTrue
? true
2815 : mAllowXULXBL
== eTriFalse
? false
2816 : InternalAllowXULXBL();
2820 * Returns true if this document is allowed to load DTDs from UI resources
2823 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks
; }
2825 void ForceEnableXULXBL() { mAllowXULXBL
= eTriTrue
; }
2827 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks
= true; }
2830 * Returns the template content owner document that owns the content of
2831 * HTMLTemplateElement.
2833 Document
* GetTemplateContentsOwner();
2835 Document
* GetTemplateContentsOwnerIfExists() const {
2836 return mTemplateContentsOwner
.get();
2839 bool IsTemplateContentsOwner() const {
2840 // Template contents owner documents are the template contents owner of
2842 return mTemplateContentsOwner
== this;
2846 * Returns true if this document is a static clone of a normal document.
2848 * We create static clones for print preview and printing (possibly other
2849 * things in future).
2851 * Note that static documents are also "loaded as data" (if this method
2852 * returns true, IsLoadedAsData() will also return true).
2854 bool IsStaticDocument() const { return mIsStaticDocument
; }
2857 * Clones the document along with any subdocuments, stylesheet, etc.
2859 * The resulting document and everything it contains (including any
2860 * sub-documents) are created purely via cloning. The returned documents and
2861 * any sub-documents are "loaded as data" documents to preserve the state as
2862 * it was during the clone process (we don't want external resources to load
2863 * and replace the cloned resources).
2865 * @param aCloneContainer The container for the clone document.
2866 * @param aDocumentViewer The viewer for the clone document. Must be the
2867 * viewer of aCloneContainer, but callers must have a
2868 * reference to it already and ensure it's not null.
2869 * @param aPrintSettings The print settings for this clone.
2870 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2872 already_AddRefed
<Document
> CreateStaticClone(
2873 nsIDocShell
* aCloneContainer
, nsIDocumentViewer
* aDocumentViewer
,
2874 nsIPrintSettings
* aPrintSettings
, bool* aOutHasInProcessPrintCallbacks
);
2877 * If this document is a static clone, this returns the original
2880 Document
* GetOriginalDocument() const {
2881 MOZ_ASSERT(!mOriginalDocument
|| !mOriginalDocument
->GetOriginalDocument());
2882 return mOriginalDocument
;
2886 * If this document is a static clone, let the original document know that
2887 * we're going away and then release our reference to it.
2889 void UnlinkOriginalDocumentIfStatic();
2892 * These are called by the parser as it encounters <picture> tags, the end of
2893 * said tags, and possible picture <source srcset> sources respectively. These
2894 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2895 * expected to be marked void.
2897 * NOTE that the parser does not attempt to track the current picture nesting
2898 * level or whether the given <source> tag is within a picture -- it is only
2899 * guaranteed to order these calls properly with respect to
2900 * ResolvePreLoadImage.
2903 void PreloadPictureOpened() { mPreloadPictureDepth
++; }
2905 void PreloadPictureClosed();
2907 void PreloadPictureImageSource(const nsAString
& aSrcsetAttr
,
2908 const nsAString
& aSizesAttr
,
2909 const nsAString
& aTypeAttr
,
2910 const nsAString
& aMediaAttr
);
2913 * Called by the parser to resolve an image for preloading. The parser will
2914 * call the PreloadPicture* functions to inform us of possible <picture>
2915 * nesting and possible sources, which are used to inform URL selection
2916 * responsive <picture> or <img srcset> images. Unset attributes are expected
2917 * to be marked void.
2918 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2919 * true, false otherwise.
2921 already_AddRefed
<nsIURI
> ResolvePreloadImage(nsIURI
* aBaseURI
,
2922 const nsAString
& aSrcAttr
,
2923 const nsAString
& aSrcsetAttr
,
2924 const nsAString
& aSizesAttr
,
2927 * Called by nsParser to preload images. Can be removed and code moved
2928 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2929 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2930 * be a void string if the attr is not present.
2931 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2932 * when this image is for loading <picture> or <img srcset> images.
2934 void MaybePreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2935 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2936 bool aLinkPreload
, const nsAString
& aFetchPriority
);
2937 void PreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2938 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2939 bool aLinkPreload
, uint64_t aEarlyHintPreloaderId
,
2940 const nsAString
& aFetchPriority
);
2943 * Called by images to forget an image preload when they start doing
2946 void ForgetImagePreload(nsIURI
* aURI
);
2949 * Called by the parser or the preload service to preload style sheets.
2950 * aCrossOriginAttr should be a void string if the attr is not present.
2952 SheetPreloadStatus
PreloadStyle(nsIURI
* aURI
, const Encoding
* aEncoding
,
2953 const nsAString
& aCrossOriginAttr
,
2954 ReferrerPolicyEnum aReferrerPolicy
,
2955 const nsAString
& aNonce
,
2956 const nsAString
& aIntegrity
,
2957 css::StylePreloadKind
,
2958 uint64_t aEarlyHintPreloaderId
,
2959 const nsAString
& aFetchPriority
);
2962 * Called by the chrome registry to load style sheets.
2964 * This always does a synchronous load, and parses as a normal document sheet.
2966 RefPtr
<StyleSheet
> LoadChromeSheetSync(nsIURI
* aURI
);
2969 * Returns true if the locale used for the document specifies a direction of
2970 * right to left. For chrome documents, this comes from the chrome registry.
2971 * This is used to determine the current state for the :-moz-locale-dir
2972 * pseudoclass so once can know whether a document is expected to be rendered
2973 * left-to-right or right-to-left.
2975 bool IsDocumentRightToLeft();
2978 * Called by Parser for link rel=preconnect
2980 void MaybePreconnect(nsIURI
* uri
, CORSMode aCORSMode
);
2983 * Set the document's pending state object (as serialized using structured
2986 void SetStateObject(nsIStructuredCloneContainer
* scContainer
);
2989 * Set the document's pending state object to the same state object as
2992 void SetStateObjectFrom(Document
* aDocument
) {
2993 SetStateObject(aDocument
->mStateObjectContainer
);
2996 // Whether we're a media document or not.
2997 enum class MediaDocumentKind
{
3004 virtual enum MediaDocumentKind
MediaDocumentKind() const {
3005 return MediaDocumentKind::NotMedia
;
3008 DocumentState
State() const { return mState
; }
3010 nsISupports
* GetCurrentContentSink();
3012 void ElementWithAutoFocusInserted(Element
* aAutoFocusCandidate
);
3013 MOZ_CAN_RUN_SCRIPT
void FlushAutoFocusCandidates();
3014 void ScheduleFlushAutoFocusCandidates();
3015 bool HasAutoFocusCandidates() const {
3016 return !mAutoFocusCandidates
.IsEmpty();
3019 void SetAutoFocusFired();
3021 void SetScrollToRef(nsIURI
* aDocumentURI
);
3022 MOZ_CAN_RUN_SCRIPT
void ScrollToRef();
3023 void ResetScrolledToRefAlready() { mScrolledToRefAlready
= false; }
3025 void SetChangeScrollPosWhenScrollingToRef(bool aValue
) {
3026 mChangeScrollPosWhenScrollingToRef
= aValue
;
3029 using DocumentOrShadowRoot::GetElementById
;
3030 using DocumentOrShadowRoot::GetElementsByClassName
;
3031 using DocumentOrShadowRoot::GetElementsByTagName
;
3032 using DocumentOrShadowRoot::GetElementsByTagNameNS
;
3034 DocumentTimeline
* Timeline();
3035 LinkedList
<DocumentTimeline
>& Timelines() { return mTimelines
; }
3036 void UpdateHiddenByContentVisibilityForAnimations();
3038 SVGSVGElement
* GetSVGRootElement() const;
3040 nsresult
ScheduleFrameRequestCallback(FrameRequestCallback
& aCallback
,
3042 void CancelFrameRequestCallback(int32_t aHandle
);
3045 * Returns true if the handle refers to a callback that was canceled that
3046 * we did not find in our list of callbacks (e.g. because it is one of those
3047 * in the set of callbacks currently queued to be run).
3049 bool IsCanceledFrameRequestCallback(int32_t aHandle
) const;
3052 * Put this document's frame request callbacks into the provided
3053 * list, and forget about them.
3055 void TakeFrameRequestCallbacks(nsTArray
<FrameRequest
>& aCallbacks
);
3058 * @return true if this document's frame request callbacks should be
3059 * throttled. We throttle requestAnimationFrame for documents which aren't
3060 * visible (e.g. scrolled out of the viewport).
3062 bool ShouldThrottleFrameRequests() const;
3064 // This returns true when the document tree is being teared down.
3065 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion
; }
3067 dom::ImageTracker
* ImageTracker();
3069 // Adds an element to mResponsiveContent when the element is
3070 // added to the tree.
3071 void AddResponsiveContent(HTMLImageElement
* aContent
) {
3072 MOZ_ASSERT(aContent
);
3073 mResponsiveContent
.Insert(aContent
);
3076 // Removes an element from mResponsiveContent when the element is
3077 // removed from the tree.
3078 void RemoveResponsiveContent(HTMLImageElement
* aContent
) {
3079 MOZ_ASSERT(aContent
);
3080 mResponsiveContent
.Remove(aContent
);
3083 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement
&);
3084 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement
& aElement
) {
3085 mSVGUseElementsNeedingShadowTreeUpdate
.Remove(&aElement
);
3088 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement
& aElement
) const {
3089 return mSVGUseElementsNeedingShadowTreeUpdate
.Contains(&aElement
);
3092 using ShadowRootSet
= nsTHashSet
<ShadowRoot
*>;
3094 void AddComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3095 mComposedShadowRoots
.Insert(&aShadowRoot
);
3098 void RemoveComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3099 mComposedShadowRoots
.Remove(&aShadowRoot
);
3102 // If you're considering using this, you probably want to use
3103 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3105 bool IsComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3106 return mComposedShadowRoots
.Contains(&aShadowRoot
);
3109 const ShadowRootSet
& ComposedShadowRoots() const {
3110 return mComposedShadowRoots
;
3113 // WebIDL method for chrome code.
3114 void GetConnectedShadowRoots(nsTArray
<RefPtr
<ShadowRoot
>>&) const;
3116 // Notifies any responsive content added by AddResponsiveContent upon media
3117 // features values changing.
3118 void NotifyMediaFeatureValuesChanged();
3120 nsresult
GetStateObject(JS::MutableHandle
<JS::Value
> aState
);
3122 nsDOMNavigationTiming
* GetNavigationTiming() const { return mTiming
; }
3124 void SetNavigationTiming(nsDOMNavigationTiming
* aTiming
);
3126 nsContentList
* ImageMapList();
3128 // Add aLink to the set of links that need their status resolved.
3129 void RegisterPendingLinkUpdate(Link
* aLink
);
3131 // Update state on links in mLinksToUpdate.
3132 void FlushPendingLinkUpdates();
3134 bool HasWarnedAbout(DeprecatedOperations aOperation
) const;
3136 DeprecatedOperations aOperation
, bool asError
= false,
3137 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3139 #define DOCUMENT_WARNING(_op) e##_op,
3140 enum DocumentWarnings
{
3141 #include "nsDocumentWarningList.h"
3142 eDocumentWarningCount
3144 #undef DOCUMENT_WARNING
3145 bool HasWarnedAbout(DocumentWarnings aWarning
) const;
3147 DocumentWarnings aWarning
, bool asError
= false,
3148 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3150 // This method may fire a DOM event; if it does so it will happen
3153 // Whether the event fires is controlled by the argument.
3154 enum class DispatchVisibilityChange
{ No
, Yes
};
3155 void UpdateVisibilityState(
3156 DispatchVisibilityChange
= DispatchVisibilityChange::Yes
);
3158 // Posts an event to call UpdateVisibilityState.
3159 void PostVisibilityUpdateEvent();
3161 bool IsSyntheticDocument() const { return mIsSyntheticDocument
; }
3163 // Adds the size of a given node, which must not be a document node, to the
3164 // window sizes passed-in.
3165 static void AddSizeOfNodeTree(nsINode
&, nsWindowSizes
&);
3167 // Note: Document is a sub-class of nsINode, which has a
3168 // SizeOfExcludingThis function. However, because Document objects can
3169 // only appear at the top of the DOM tree, we have a specialized measurement
3170 // function which returns multiple sizes.
3171 virtual void DocAddSizeOfExcludingThis(nsWindowSizes
& aWindowSizes
) const;
3172 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3173 // because Document inherits from nsINode; see the comment above the
3174 // declaration of nsINode::SizeOfIncludingThis.
3175 virtual void DocAddSizeOfIncludingThis(nsWindowSizes
& aWindowSizes
) const;
3177 void ConstructUbiNode(void* storage
) override
;
3179 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers
; }
3181 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers
= true; }
3183 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers
; }
3185 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers
= true; }
3187 bool IsInSyncOperation() { return mInSyncOperationCount
!= 0; }
3189 void SetIsInSyncOperation(bool aSync
);
3191 bool CreatingStaticClone() const { return mCreatingStaticClone
; }
3194 * Creates a new element in the HTML namespace with a local name given by
3197 already_AddRefed
<Element
> CreateHTMLElement(nsAtom
* aTag
);
3200 nsIGlobalObject
* GetParentObject() const { return GetScopeObject(); }
3201 static already_AddRefed
<Document
> Constructor(const GlobalObject
& aGlobal
,
3203 DOMImplementation
* GetImplementation(ErrorResult
& rv
);
3204 [[nodiscard
]] nsresult
GetURL(nsString
& retval
) const;
3205 [[nodiscard
]] nsresult
GetDocumentURI(nsString
& retval
) const;
3206 // Return the URI for the document.
3207 // The returned value may differ if the document is loaded via XHR, and
3208 // when accessed from chrome privileged script and
3209 // from content privileged script for compatibility.
3210 void GetDocumentURIFromJS(nsString
& aDocumentURI
, CallerType aCallerType
,
3211 ErrorResult
& aRv
) const;
3212 void GetCompatMode(nsString
& retval
) const;
3213 void GetCharacterSet(nsAString
& retval
) const;
3214 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3215 // GetDoctype defined above
3216 Element
* GetDocumentElement() const { return GetRootElement(); }
3218 WindowContext
* GetTopLevelWindowContext() const;
3220 // If the top-level ancestor content document for this document is in the same
3221 // process, returns it. Otherwise, returns null. This function is not
3222 // Fission-compatible, and should not be used in new code.
3223 Document
* GetTopLevelContentDocumentIfSameProcess();
3224 const Document
* GetTopLevelContentDocumentIfSameProcess() const;
3226 // Returns the associated app window if this is a top-level chrome document,
3228 already_AddRefed
<nsIAppWindow
> GetAppWindowIfToplevelChrome() const;
3230 already_AddRefed
<Element
> CreateElement(
3231 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3233 already_AddRefed
<Element
> CreateElementNS(
3234 const nsAString
& aNamespaceURI
, const nsAString
& aQualifiedName
,
3235 const ElementCreationOptionsOrString
& aOptions
, ErrorResult
& rv
);
3236 already_AddRefed
<Element
> CreateXULElement(
3237 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3239 already_AddRefed
<DocumentFragment
> CreateDocumentFragment() const;
3240 already_AddRefed
<nsTextNode
> CreateTextNode(const nsAString
& aData
) const;
3241 already_AddRefed
<nsTextNode
> CreateEmptyTextNode() const;
3242 already_AddRefed
<Comment
> CreateComment(const nsAString
& aData
) const;
3243 already_AddRefed
<ProcessingInstruction
> CreateProcessingInstruction(
3244 const nsAString
& target
, const nsAString
& data
, ErrorResult
& rv
) const;
3245 already_AddRefed
<nsINode
> ImportNode(nsINode
& aNode
, bool aDeep
,
3246 ErrorResult
& rv
) const;
3247 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3248 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode
* AdoptNode(
3249 nsINode
& aAdoptedNode
, ErrorResult
& rv
, bool aAcceptShadowRoot
= false);
3250 already_AddRefed
<Event
> CreateEvent(const nsAString
& aEventType
,
3251 CallerType aCallerType
,
3252 ErrorResult
& rv
) const;
3253 already_AddRefed
<nsRange
> CreateRange(ErrorResult
& rv
);
3254 already_AddRefed
<NodeIterator
> CreateNodeIterator(nsINode
& aRoot
,
3255 uint32_t aWhatToShow
,
3256 NodeFilter
* aFilter
,
3257 ErrorResult
& rv
) const;
3258 already_AddRefed
<TreeWalker
> CreateTreeWalker(nsINode
& aRoot
,
3259 uint32_t aWhatToShow
,
3260 NodeFilter
* aFilter
,
3261 ErrorResult
& rv
) const;
3262 // Deprecated WebIDL bits
3263 already_AddRefed
<CDATASection
> CreateCDATASection(const nsAString
& aData
,
3265 already_AddRefed
<Attr
> CreateAttribute(const nsAString
& aName
,
3267 already_AddRefed
<Attr
> CreateAttributeNS(const nsAString
& aNamespaceURI
,
3268 const nsAString
& aQualifiedName
,
3270 void GetInputEncoding(nsAString
& aInputEncoding
) const;
3271 already_AddRefed
<Location
> GetLocation() const;
3272 void GetDomain(nsAString
& aDomain
);
3273 void SetDomain(const nsAString
& aDomain
, mozilla::ErrorResult
& rv
);
3274 void GetCookie(nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3275 void SetCookie(const nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3276 void GetReferrer(nsACString
& aReferrer
) const;
3277 void GetLastModified(nsAString
& aLastModified
) const;
3278 void GetReadyState(nsAString
& aReadyState
) const;
3280 void GetTitle(nsAString
& aTitle
);
3281 void SetTitle(const nsAString
& aTitle
, ErrorResult
& rv
);
3282 void GetDir(nsAString
& aDirection
) const;
3283 void SetDir(const nsAString
& aDirection
);
3284 nsIHTMLCollection
* Images();
3285 nsIHTMLCollection
* Embeds();
3286 nsIHTMLCollection
* Plugins() { return Embeds(); }
3287 nsIHTMLCollection
* Links();
3288 nsIHTMLCollection
* Forms();
3289 nsIHTMLCollection
* Scripts();
3290 already_AddRefed
<nsContentList
> GetElementsByName(const nsAString
& aName
) {
3291 return GetFuncStringContentList
<nsCachableElementsByNameNodeList
>(
3292 this, MatchNameAttribute
, nullptr, UseExistingNameString
, aName
);
3294 Document
* Open(const mozilla::dom::Optional
<nsAString
>& /* unused */,
3295 const mozilla::dom::Optional
<nsAString
>& /* unused */,
3296 mozilla::ErrorResult
& aError
);
3297 mozilla::dom::Nullable
<mozilla::dom::WindowProxyHolder
> Open(
3298 const nsAString
& aURL
, const nsAString
& aName
, const nsAString
& aFeatures
,
3299 mozilla::ErrorResult
& rv
);
3300 void Close(mozilla::ErrorResult
& rv
);
3301 void Write(const mozilla::dom::Sequence
<nsString
>& aText
,
3302 mozilla::ErrorResult
& rv
);
3303 void Writeln(const mozilla::dom::Sequence
<nsString
>& aText
,
3304 mozilla::ErrorResult
& rv
);
3305 Nullable
<WindowProxyHolder
> GetDefaultView() const;
3306 Element
* GetActiveElement();
3307 enum class IncludeChromeOnly
: bool { No
, Yes
};
3308 // TODO(emilio): Audit callers and remove the default argument, some seem like
3309 // they could want the IncludeChromeOnly::Yes version.
3310 nsIContent
* GetUnretargetedFocusedContent(
3311 IncludeChromeOnly
= IncludeChromeOnly::No
) const;
3313 * Return true if this document or a subdocument has focus.
3315 bool HasFocus(ErrorResult
& rv
) const;
3318 * Return true if this document itself has focus.
3320 bool ThisDocumentHasFocus() const;
3322 void GetDesignMode(nsAString
& aDesignMode
);
3323 void SetDesignMode(const nsAString
& aDesignMode
,
3324 nsIPrincipal
& aSubjectPrincipal
, mozilla::ErrorResult
& rv
);
3325 void SetDesignMode(const nsAString
& aDesignMode
,
3326 const mozilla::Maybe
<nsIPrincipal
*>& aSubjectPrincipal
,
3327 mozilla::ErrorResult
& rv
);
3329 bool ExecCommand(const nsAString
& aHTMLCommandName
, bool aShowUI
,
3330 const nsAString
& aValue
, nsIPrincipal
& aSubjectPrincipal
,
3331 mozilla::ErrorResult
& aRv
);
3332 MOZ_CAN_RUN_SCRIPT
bool QueryCommandEnabled(const nsAString
& aHTMLCommandName
,
3333 nsIPrincipal
& aSubjectPrincipal
,
3334 mozilla::ErrorResult
& aRv
);
3335 MOZ_CAN_RUN_SCRIPT
bool QueryCommandIndeterm(
3336 const nsAString
& aHTMLCommandName
, mozilla::ErrorResult
& aRv
);
3337 MOZ_CAN_RUN_SCRIPT
bool QueryCommandState(const nsAString
& aHTMLCommandName
,
3338 mozilla::ErrorResult
& aRv
);
3339 MOZ_CAN_RUN_SCRIPT
bool QueryCommandSupported(
3340 const nsAString
& aHTMLCommandName
, mozilla::dom::CallerType aCallerType
,
3341 mozilla::ErrorResult
& aRv
);
3342 MOZ_CAN_RUN_SCRIPT
void QueryCommandValue(const nsAString
& aHTMLCommandName
,
3344 mozilla::ErrorResult
& aRv
);
3345 nsIHTMLCollection
* Applets();
3346 nsIHTMLCollection
* Anchors();
3347 TimeStamp
LastFocusTime() const;
3348 void SetLastFocusTime(const TimeStamp
& aFocusTime
);
3349 // Event handlers are all on nsINode already
3350 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3351 Element
* GetCurrentScript();
3352 void ReleaseCapture() const;
3353 void MozSetImageElement(const nsAString
& aImageElementId
, Element
* aElement
);
3354 nsIURI
* GetDocumentURIObject() const;
3355 // Not const because all the fullscreen goop is not const
3356 const char* GetFullscreenError(CallerType
);
3357 bool FullscreenEnabled(CallerType aCallerType
) {
3358 return !GetFullscreenError(aCallerType
);
3361 void GetWireframeWithoutFlushing(bool aIncludeNodes
, Nullable
<Wireframe
>&);
3363 MOZ_CAN_RUN_SCRIPT
void GetWireframe(bool aIncludeNodes
,
3364 Nullable
<Wireframe
>&);
3366 // Hides all popovers until the given end point, see
3367 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3368 MOZ_CAN_RUN_SCRIPT
void HideAllPopoversUntil(nsINode
& aEndpoint
,
3369 bool aFocusPreviousElement
,
3372 // Hides the given popover element, see
3373 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3374 MOZ_CAN_RUN_SCRIPT
void HidePopover(Element
& popover
,
3375 bool aFocusPreviousElement
,
3376 bool aFireEvents
, ErrorResult
& aRv
);
3378 // Returns a list of all the elements in the Document's top layer whose
3379 // popover attribute is in the auto state.
3380 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3381 nsTArray
<Element
*> AutoPopoverList() const;
3383 // Return document's auto popover list's last element.
3385 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3386 Element
* GetTopmostAutoPopover() const;
3388 // Adds/removes an element to/from the auto popover list.
3389 void AddToAutoPopoverList(Element
&);
3390 void RemoveFromAutoPopoverList(Element
&);
3392 void AddPopoverToTopLayer(Element
&);
3393 void RemovePopoverFromTopLayer(Element
&);
3395 Element
* GetTopLayerTop();
3396 // Return the fullscreen element in the top layer
3397 Element
* GetUnretargetedFullscreenElement() const;
3398 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3399 already_AddRefed
<Promise
> ExitFullscreen(ErrorResult
&);
3400 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3401 void GetFgColor(nsAString
& aFgColor
);
3402 void SetFgColor(const nsAString
& aFgColor
);
3403 void GetLinkColor(nsAString
& aLinkColor
);
3404 void SetLinkColor(const nsAString
& aLinkColor
);
3405 void GetVlinkColor(nsAString
& aAvlinkColor
);
3406 void SetVlinkColor(const nsAString
& aVlinkColor
);
3407 void GetAlinkColor(nsAString
& aAlinkColor
);
3408 void SetAlinkColor(const nsAString
& aAlinkColor
);
3409 void GetBgColor(nsAString
& aBgColor
);
3410 void SetBgColor(const nsAString
& aBgColor
);
3411 void Clear() const {
3414 void CaptureEvents();
3415 void ReleaseEvents();
3417 mozilla::dom::HTMLAllCollection
* All();
3419 static bool DocumentSupportsL10n(JSContext
* aCx
, JSObject
* aObject
);
3420 static bool AreWebAnimationsTimelinesEnabled(JSContext
* aCx
,
3422 // Checks that the caller is either chrome or some addon.
3423 static bool IsCallerChromeOrAddon(JSContext
* aCx
, JSObject
* aObject
);
3425 bool Hidden() const { return mVisibilityState
!= VisibilityState::Visible
; }
3426 dom::VisibilityState
VisibilityState() const { return mVisibilityState
; }
3429 void GetSelectedStyleSheetSet(nsAString
& aSheetSet
);
3430 void SetSelectedStyleSheetSet(const nsAString
& aSheetSet
);
3431 void GetLastStyleSheetSet(nsAString
& aSheetSet
) {
3432 aSheetSet
= mLastStyleSheetSet
;
3434 const nsString
& GetCurrentStyleSheetSet() const {
3435 return mLastStyleSheetSet
.IsEmpty() ? mPreferredStyleSheetSet
3436 : mLastStyleSheetSet
;
3438 void SetPreferredStyleSheetSet(const nsAString
&);
3439 void GetPreferredStyleSheetSet(nsAString
& aSheetSet
) {
3440 aSheetSet
= mPreferredStyleSheetSet
;
3442 DOMStringList
* StyleSheetSets();
3443 void EnableStyleSheetsForSet(const nsAString
& aSheetSet
);
3446 * Retrieve the location of the caret position (DOM node and character
3447 * offset within that node), given a point.
3449 * @param aX Horizontal point at which to determine the caret position, in
3451 * @param aY Vertical point at which to determine the caret position, in
3454 already_AddRefed
<nsDOMCaretPosition
> CaretPositionFromPoint(float aX
,
3457 Element
* GetScrollingElement();
3458 // A way to check whether a given element is what would get returned from
3459 // GetScrollingElement. It can be faster than comparing to the return value
3460 // of GetScrollingElement() due to being able to avoid flushes in various
3461 // cases. This method assumes that null is NOT passed.
3462 bool IsScrollingElement(Element
* aElement
);
3464 // QuerySelector and QuerySelectorAll already defined on nsINode
3466 UniquePtr
<XPathExpression
> CreateExpression(const nsAString
& aExpression
,
3467 XPathNSResolver
* aResolver
,
3469 nsINode
* CreateNSResolver(nsINode
& aNodeResolver
);
3470 already_AddRefed
<XPathResult
> Evaluate(
3471 JSContext
* aCx
, const nsAString
& aExpression
, nsINode
& aContextNode
,
3472 XPathNSResolver
* aResolver
, uint16_t aType
, JS::Handle
<JSObject
*> aResult
,
3474 // Touch event handlers already on nsINode
3475 already_AddRefed
<Touch
> CreateTouch(nsGlobalWindowInner
* aView
,
3476 EventTarget
* aTarget
, int32_t aIdentifier
,
3477 int32_t aPageX
, int32_t aPageY
,
3478 int32_t aScreenX
, int32_t aScreenY
,
3479 int32_t aClientX
, int32_t aClientY
,
3480 int32_t aRadiusX
, int32_t aRadiusY
,
3481 float aRotationAngle
, float aForce
);
3482 already_AddRefed
<TouchList
> CreateTouchList();
3483 already_AddRefed
<TouchList
> CreateTouchList(
3484 Touch
& aTouch
, const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3485 already_AddRefed
<TouchList
> CreateTouchList(
3486 const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3488 void SetStyleSheetChangeEventsEnabled(bool aValue
) {
3489 mStyleSheetChangeEventsEnabled
= aValue
;
3492 bool StyleSheetChangeEventsEnabled() const {
3493 return mStyleSheetChangeEventsEnabled
;
3496 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue
) {
3497 mDevToolsAnonymousAndShadowEventsEnabled
= aValue
;
3499 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3500 return mDevToolsAnonymousAndShadowEventsEnabled
;
3503 already_AddRefed
<Promise
> BlockParsing(Promise
& aPromise
,
3504 const BlockParsingOptions
& aOptions
,
3507 already_AddRefed
<nsIURI
> GetMozDocumentURIIfNotForErrorPages();
3509 Promise
* GetDocumentReadyForIdle(ErrorResult
& aRv
);
3511 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock
) {
3515 UnblockOnload(/* aFireSync = */ false);
3519 nsIDOMXULCommandDispatcher
* GetCommandDispatcher();
3520 bool HasXULBroadcastManager() const { return mXULBroadcastManager
; };
3521 void InitializeXULBroadcastManager();
3522 XULBroadcastManager
* GetXULBroadcastManager() const {
3523 return mXULBroadcastManager
;
3525 nsINode
* GetPopupRangeParent(ErrorResult
& aRv
);
3526 int32_t GetPopupRangeOffset(ErrorResult
& aRv
);
3528 bool DevToolsWatchingDOMMutations() const {
3529 return mDevToolsWatchingDOMMutations
;
3531 void SetDevToolsWatchingDOMMutations(bool aValue
);
3533 void MaybeWarnAboutZoom();
3535 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3536 void EvaluateMediaQueriesAndReportChanges(bool aRecurse
);
3538 nsTHashSet
<RefPtr
<WakeLockSentinel
>>& ActiveWakeLocks(WakeLockType aType
);
3540 void UnlockAllWakeLocks(WakeLockType aType
);
3543 nsIHTMLCollection
* Children();
3544 uint32_t ChildElementCount();
3547 * Asserts IsHTMLOrXHTML, and can't return null.
3548 * Defined inline in nsHTMLDocument.h
3550 inline nsHTMLDocument
* AsHTMLDocument();
3551 inline const nsHTMLDocument
* AsHTMLDocument() const;
3554 * Asserts IsSVGDocument, and can't return null.
3555 * Defined inline in SVGDocument.h
3557 inline SVGDocument
* AsSVGDocument();
3558 inline const SVGDocument
* AsSVGDocument() const;
3561 * Asserts IsImageDocument, and can't return null.
3562 * Defined inline in ImageDocument.h
3564 inline ImageDocument
* AsImageDocument();
3565 inline const ImageDocument
* AsImageDocument() const;
3567 gfxUserFontSet
* GetUserFontSet();
3568 void FlushUserFontSet();
3569 void MarkUserFontSetDirty();
3570 FontFaceSet
* GetFonts() { return mFontFaceSet
; }
3573 FontFaceSet
* GetFonts(ErrorResult
&) { return Fonts(); }
3574 FontFaceSet
* Fonts();
3576 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded
; }
3578 bool IsSynthesized();
3580 // Records whether we will track use counters for this document, and if so,
3581 // which top-level document that page counters will be accumulated to.
3583 // Informs the parent process that page use counters will be sent once the
3584 // document goes away.
3585 void InitUseCounters();
3587 // Reports document use counters via telemetry. This method only has an
3588 // effect once per document, and so is called during document destruction.
3589 void ReportDocumentUseCounters();
3591 // Reports largest contentful paint via telemetry. We want the most up to
3592 // date value for LCP and so this is called during document destruction.
3595 // Report how lazyload performs for this document.
3596 void ReportDocumentLazyLoadCounters();
3598 // Sends page use counters to the parent process to accumulate against the
3599 // top-level document. Must be called while we still have access to our
3600 // WindowContext. This method has an effect each time it is called, and we
3601 // call it just before the document loses its window.
3602 void SendPageUseCounters();
3604 void SetUseCounter(UseCounter aUseCounter
) {
3605 mUseCounters
[aUseCounter
] = true;
3608 const StyleUseCounters
* GetStyleUseCounters() {
3609 return mStyleUseCounters
.get();
3612 // Propagate our use counters explicitly into the specified referencing
3615 // This is used for SVG image documents, which cannot be enumerated in the
3616 // referencing document's ReportUseCounters() like external resource documents
3618 void PropagateImageUseCounters(Document
* aReferencingDocument
);
3620 // Called to track whether this document has had any interaction.
3621 // This is used to track whether we should permit "beforeunload".
3622 void SetUserHasInteracted();
3623 bool UserHasInteracted() { return mUserHasInteracted
; }
3624 void ResetUserInteractionTimer();
3626 // Whether we're cloning the contents of an SVG use element.
3627 bool CloningForSVGUse() const { return mCloningForSVGUse
; }
3629 // This should be called when this document receives events which are likely
3630 // to be user interaction with the document, rather than the byproduct of
3631 // interaction with the browser (i.e. a keypress to scroll the view port,
3632 // keyboard shortcuts, etc). This is used to decide whether we should
3633 // permit autoplay audible media. This also gesture activates all other
3634 // content documents in this tab.
3635 void NotifyUserGestureActivation(
3636 UserActivation::Modifiers aModifiers
= UserActivation::Modifiers::None());
3638 // This function is used for mochitest only.
3639 void ClearUserGestureActivation();
3641 // Return true if NotifyUserGestureActivation() has been called on any
3642 // document in the document tree.
3643 bool HasBeenUserGestureActivated();
3645 // Reture timestamp of last user gesture in milliseconds relative to
3646 // navigation start timestamp.
3647 DOMHighResTimeStamp
LastUserGestureTimeStamp();
3649 // Return true if there is transient user gesture activation and it hasn't yet
3650 // timed out or hasn't been consumed.
3651 bool HasValidTransientUserGestureActivation() const;
3653 // Return true if HasValidTransientUserGestureActivation() would return true,
3654 // and consume the activation.
3655 bool ConsumeTransientUserGestureActivation();
3657 bool GetTransientUserGestureActivationModifiers(
3658 UserActivation::Modifiers
* aModifiers
);
3660 BrowsingContext
* GetBrowsingContext() const;
3662 // This document is a WebExtension page, it might be a background page, a
3663 // popup, a visible tab, a visible iframe ...e.t.c.
3664 bool IsExtensionPage() const;
3666 bool HasScriptsBlockedBySandbox() const;
3668 void ReportHasScrollLinkedEffect(const TimeStamp
& aTimeStamp
);
3669 bool HasScrollLinkedEffect() const;
3672 void AssertDocGroupMatchesKey() const;
3675 DocGroup
* GetDocGroup() const {
3677 AssertDocGroupMatchesKey();
3682 DocGroup
* GetDocGroupOrCreate();
3685 * If we're a sub-document, the parent document's layout can affect our style
3686 * and layout (due to the viewport size, viewport units, media queries...).
3688 * This function returns true if our parent document and our child document
3689 * can observe each other. If they cannot, then we don't need to synchronously
3690 * update the parent document layout every time the child document may need
3691 * up-to-date layout information.
3693 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3694 return GetInProcessParentDocument() &&
3695 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3698 void AddIntersectionObserver(DOMIntersectionObserver
* aObserver
) {
3699 MOZ_ASSERT(!mIntersectionObservers
.Contains(aObserver
),
3700 "Intersection observer already in the list");
3701 mIntersectionObservers
.Insert(aObserver
);
3704 void RemoveIntersectionObserver(DOMIntersectionObserver
* aObserver
) {
3705 mIntersectionObservers
.Remove(aObserver
);
3708 bool HasIntersectionObservers() const {
3709 return !mIntersectionObservers
.IsEmpty();
3712 void UpdateIntersectionObservations(TimeStamp aNowTime
);
3713 void ScheduleIntersectionObserverNotification();
3714 MOZ_CAN_RUN_SCRIPT
void NotifyIntersectionObservers();
3716 DOMIntersectionObserver
* GetLazyLoadObserver() { return mLazyLoadObserver
; }
3717 DOMIntersectionObserver
& EnsureLazyLoadObserver();
3719 bool HasElementsWithLastRememberedSize() const {
3720 return !mElementsObservedForLastRememberedSize
.IsEmpty();
3722 void ObserveForLastRememberedSize(Element
&);
3723 void UnobserveForLastRememberedSize(Element
&);
3724 void UpdateLastRememberedSizes();
3726 // Dispatch a runnable related to the document.
3727 nsresult
Dispatch(already_AddRefed
<nsIRunnable
>&& aRunnable
) const;
3729 // The URLs passed to this function should match what
3730 // JS::DescribeScriptedCaller() returns, since this API is used to
3731 // determine whether some code is being called from a tracking script.
3732 void NoteScriptTrackingStatus(const nsACString
& aURL
, bool isTracking
);
3733 // The JSContext passed to this method represents the context that we want to
3734 // determine if it belongs to a tracker.
3735 bool IsScriptTracking(JSContext
* aCx
) const;
3737 // ResizeObserver usage.
3738 void AddResizeObserver(ResizeObserver
&);
3739 void RemoveResizeObserver(ResizeObserver
&);
3740 void ScheduleResizeObserversNotification() const;
3741 bool HasResizeObservers() const { return !mResizeObservers
.IsEmpty(); }
3743 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3744 * All observations in each ResizeObserver with element's depth more than
3745 * aDepth will be gathered.
3747 void GatherAllActiveResizeObservations(uint32_t aDepth
);
3749 * Calls BroadcastActiveObservations() for all ResizeObservers.
3750 * It also returns the shallowest depth of observed target elements with
3751 * active observations from all ResizeObservers or
3752 * numeric_limits<uint32_t>::max() if there aren't any active observations
3755 MOZ_CAN_RUN_SCRIPT
uint32_t BroadcastAllActiveResizeObservations();
3757 * Returns whether there is any ResizeObserver that has active
3760 bool HasAnyActiveResizeObservations() const;
3762 * Returns whether there is any ResizeObserver that has skipped observations.
3764 bool HasAnySkippedResizeObservations() const;
3766 * Determine proximity to viewport for content-visibility: auto elements and
3767 * notify resize observers.
3769 MOZ_CAN_RUN_SCRIPT
void
3770 DetermineProximityToViewportAndNotifyResizeObservers();
3772 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3773 PermissionDelegateHandler
* GetPermissionDelegateHandler();
3775 // Notify the document that a fetch or a XHR request has completed
3776 // succesfully in this document. This is used by the password manager to infer
3777 // whether a form is submitted.
3778 void NotifyFetchOrXHRSuccess();
3780 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3781 void SetNotifyFetchSuccess(bool aShouldNotify
);
3783 // When this is set, removing a form or a password field from DOM
3784 // sends a Chrome-only event. This is now only used by the password manager
3785 // and formautofill.
3786 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify
);
3788 // This function is used by HTMLFormElement and HTMLInputElement to determin
3789 // whether to send an event when it is removed from DOM.
3790 bool ShouldNotifyFormOrPasswordRemoved() const {
3791 return mShouldNotifyFormOrPasswordRemoved
;
3794 HTMLEditor
* GetHTMLEditor() const;
3799 * For more information on DocumentL10n see
3800 * intl/l10n/docs/fluent/tutorial.rst
3805 * This is a public method exposed on Document WebIDL
3806 * to chrome only documents.
3808 DocumentL10n
* GetL10n() const { return mDocumentL10n
.get(); }
3811 * Whether there's any async l10n mutation work pending.
3813 * When this turns false, we fire the L10nMutationsFinished event.
3815 bool HasPendingL10nMutations() const;
3818 * This method should be called when the container
3819 * of l10n resources parsing is completed.
3821 * It triggers initial async fetch of the resources
3822 * as early as possible.
3824 * In HTML case this is </head>.
3825 * In XUL case this is </linkset>.
3827 void OnL10nResourceContainerParsed();
3830 * This method should be called when a link element
3831 * with rel="localization" is being added to the
3832 * l10n resource container element.
3834 void LocalizationLinkAdded(Element
* aLinkElement
);
3837 * This method should be called when a link element
3838 * with rel="localization" is being removed.
3840 void LocalizationLinkRemoved(Element
* aLinkElement
);
3843 * This method should be called as soon as the
3844 * parsing of the document is completed.
3846 * In HTML/XHTML this happens when we finish parsing
3847 * the document element.
3848 * In XUL it happens at `DoneWalking`, during
3849 * `MozBeforeInitialXULLayout`.
3851 void OnParsingCompleted();
3854 * This method is called when the initial translation
3855 * of the document is completed.
3857 * It unblocks the load event if translation was blocking it.
3859 * If the `aL10nCached` is set to `true`, and the document has
3860 * a prototype, it will set the `isL10nCached` flag on it.
3862 void InitialTranslationCompleted(bool aL10nCached
);
3865 * Returns whether the document allows localization.
3867 bool AllowsL10n() const;
3869 void SetAllowDeclarativeShadowRoots(bool aAllowDeclarativeShadowRoots
);
3870 bool AllowsDeclarativeShadowRoots() const;
3872 void SuspendDOMNotifications() {
3873 MOZ_ASSERT(IsHTMLDocument(),
3874 "Currently suspending DOM notifications is supported only on "
3876 mSuspendDOMNotifications
= true;
3879 void ResumeDOMNotifications() { mSuspendDOMNotifications
= false; }
3881 bool DOMNotificationsSuspended() const { return mSuspendDOMNotifications
; }
3884 RefPtr
<DocumentL10n
> mDocumentL10n
;
3887 * Return true when you want a document without explicitly specified viewport
3888 * dimensions/scale to be treated as if "width=device-width" had in fact been
3891 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3894 bool IsErrorPage() const;
3896 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3898 void SetCssUseCounterBits();
3900 void ParseWidthAndHeightInMetaViewport(const nsAString
& aWidthString
,
3901 const nsAString
& aHeightString
,
3904 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3905 // represents the scale property and returns the scale value if it's valid.
3906 Maybe
<LayoutDeviceToScreenScale
> ParseScaleInHeader(nsAtom
* aHeaderField
);
3908 // Parse scale values in |aViewportMetaData| and set the values in
3909 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3910 void ParseScalesInViewportMetaData(const ViewportMetaData
& aViewportMetaData
);
3912 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3913 // stored in parent iframe or container's browsingContext (cross process)
3914 already_AddRefed
<mozilla::dom::FeaturePolicy
> GetParentFeaturePolicy();
3917 const OriginTrials
& Trials() const { return mTrials
; }
3920 void DoCacheAllKnownLangPrefs();
3921 void RecomputeLanguageFromCharset();
3922 bool GetSHEntryHasUserInteraction();
3924 void AppendAutoFocusCandidateToTopDocument(Element
* aAutoFocusCandidate
);
3927 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate
= true; }
3929 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate
; }
3931 void SetSHEntryHasUserInteraction(bool aHasInteraction
);
3933 nsAtom
* GetContentLanguageAsAtomForStyle() const;
3934 nsAtom
* GetLanguageForStyle() const;
3937 * Fetch the user's font preferences for the given aLanguage's
3940 const LangGroupFontPrefs
* GetFontPrefsForLang(
3941 nsAtom
* aLanguage
, bool* aNeedsToCache
= nullptr) const;
3943 void ForceCacheLang(nsAtom
* aLanguage
) {
3944 if (!mLanguagesUsed
.EnsureInserted(aLanguage
)) {
3947 GetFontPrefsForLang(aLanguage
);
3950 void CacheAllKnownLangPrefs() {
3951 if (!mMayNeedFontPrefsUpdate
) {
3954 DoCacheAllKnownLangPrefs();
3957 nsINode
* GetServoRestyleRoot() const { return mServoRestyleRoot
; }
3959 uint32_t GetServoRestyleRootDirtyBits() const {
3960 MOZ_ASSERT(mServoRestyleRoot
);
3961 MOZ_ASSERT(mServoRestyleRootDirtyBits
);
3962 return mServoRestyleRootDirtyBits
;
3965 void ClearServoRestyleRoot() {
3966 mServoRestyleRoot
= nullptr;
3967 mServoRestyleRootDirtyBits
= 0;
3970 inline void SetServoRestyleRoot(nsINode
* aRoot
, uint32_t aDirtyBits
);
3971 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits
);
3973 bool ShouldThrowOnDynamicMarkupInsertion() {
3974 return mThrowOnDynamicMarkupInsertionCounter
;
3977 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3978 ++mThrowOnDynamicMarkupInsertionCounter
;
3981 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3982 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter
);
3983 --mThrowOnDynamicMarkupInsertionCounter
;
3986 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter
; }
3988 void IncrementIgnoreOpensDuringUnloadCounter() {
3989 ++mIgnoreOpensDuringUnloadCounter
;
3992 void DecrementIgnoreOpensDuringUnloadCounter() {
3993 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter
);
3994 --mIgnoreOpensDuringUnloadCounter
;
3997 mozilla::dom::FeaturePolicy
* FeaturePolicy() 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 (and
4027 // thus likely not accessible by content). Likely because it shouldn't be used
4028 // for security checks for example, see bug 1860098.
4029 bool IsLikelyContentInaccessibleTopLevelAboutBlank() const;
4031 // CSS prefers-color-scheme media feature for this document.
4032 enum class IgnoreRFP
{ No
, Yes
};
4033 ColorScheme
PreferredColorScheme(IgnoreRFP
= IgnoreRFP::No
) const;
4034 // Returns the initial color-scheme used for this document based on the
4035 // color-scheme meta tag.
4036 ColorScheme
DefaultColorScheme() const;
4038 static bool HasRecentlyStartedForegroundLoads();
4040 static bool AutomaticStorageAccessPermissionCanBeGranted(
4041 nsIPrincipal
* aPrincipal
);
4043 already_AddRefed
<Promise
> AddCertException(bool aIsTemporary
,
4044 ErrorResult
& aError
);
4046 void ReloadWithHttpsOnlyException();
4048 // Subframes need to be static cloned after the main document has been
4049 // embedded within a script global. A `PendingFrameStaticClone` is a static
4050 // clone which has not yet been performed.
4052 // The getter returns a direct reference to an internal array which is
4053 // manipulated from within printing code.
4054 struct PendingFrameStaticClone
{
4055 PendingFrameStaticClone() = default;
4056 PendingFrameStaticClone(PendingFrameStaticClone
&&) = default;
4057 PendingFrameStaticClone
& operator=(PendingFrameStaticClone
&&) = default;
4058 ~PendingFrameStaticClone();
4060 RefPtr
<nsFrameLoaderOwner
> mElement
;
4061 RefPtr
<nsFrameLoader
> mStaticCloneOf
;
4063 void AddPendingFrameStaticClone(nsFrameLoaderOwner
* aElement
,
4064 nsFrameLoader
* aStaticCloneOf
);
4066 bool ShouldAvoidNativeTheme() const;
4068 static bool IsValidDomain(nsIURI
* aOrigHost
, nsIURI
* aNewURI
);
4070 // Inform a parent document that a BrowserBridgeChild has been created for
4071 // an OOP sub-document.
4072 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4073 void OOPChildLoadStarted(BrowserBridgeChild
* aChild
);
4075 // Inform a parent document that the BrowserBridgeChild for one of its
4076 // OOP sub-documents is done calling its onload handler.
4077 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4078 void OOPChildLoadDone(BrowserBridgeChild
* aChild
);
4080 void ClearOOPChildrenLoading();
4082 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading
.IsEmpty(); }
4084 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache
= true; }
4086 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache
; }
4089 * Get the `HighlightRegistry` which contains all highlights associated
4090 * with this document.
4092 class HighlightRegistry
& HighlightRegistry();
4095 * @brief Returns the `FragmentDirective` object which contains information
4096 * and functionality to extract or create text directives.
4097 * Guaranteed to be non-null.
4099 class FragmentDirective
* FragmentDirective();
4101 bool ShouldResistFingerprinting(RFPTarget aTarget
) const;
4102 bool IsInPrivateBrowsing() const;
4104 const Maybe
<RFPTarget
>& GetOverriddenFingerprintingSettings() const {
4105 return mOverriddenFingerprintingSettings
;
4108 // Recompute the current resist fingerprinting state. Returns true when
4109 // the state was changed.
4110 bool RecomputeResistFingerprinting();
4112 void RecordCanvasUsage(CanvasUsage
& aUsage
);
4113 void RecordFontFingerprinting();
4115 bool MayHaveDOMActivateListeners() const;
4117 void DropStyleSet();
4120 // Returns the WindowContext for the document that we will contribute
4121 // page use counters to.
4122 WindowContext
* GetWindowContextForPageUseCounters() const;
4124 void DoUpdateSVGUseElementShadowTrees();
4126 already_AddRefed
<nsIPrincipal
> MaybeDowngradePrincipal(
4127 nsIPrincipal
* aPrincipal
);
4129 void EnsureOnloadBlocker();
4131 void SendToConsole(nsCOMArray
<nsISecurityConsoleMessage
>& aMessages
);
4133 // Returns true if the scheme for the url for this document is "about".
4134 bool IsAboutPage() const;
4136 bool ContainsEMEContent();
4137 bool ContainsMSEContent();
4140 * Returns the title element of the document as defined by the HTML
4141 * specification, or null if there isn't one. For documents whose root
4142 * element is an <svg:svg>, this is the first <svg:title> element that's a
4143 * child of the root. For other documents, it's the first HTML title element
4146 Element
* GetTitleElement();
4148 void RecordNavigationTiming(ReadyState aReadyState
);
4150 // Recomputes the visibility state but doesn't set the new value.
4151 dom::VisibilityState
ComputeVisibilityState() const;
4153 // Since we wouldn't automatically play media from non-visited page, we need
4154 // to notify window when the page was first visited.
4155 void MaybeActiveMediaComponents();
4157 // Apply the fullscreen state to the document, and trigger related
4158 // events. It returns false if the fullscreen element ready check
4159 // fails and nothing gets changed.
4160 MOZ_CAN_RUN_SCRIPT_BOUNDARY
bool ApplyFullscreen(
4161 UniquePtr
<FullscreenRequest
>);
4163 void RemoveDocStyleSheetsFromStyleSets();
4164 void ResetStylesheetsToURI(nsIURI
* aURI
);
4165 void FillStyleSet();
4166 void FillStyleSetUserAndUASheets();
4167 void FillStyleSetDocumentSheets();
4168 void CompatibilityModeChanged();
4169 bool NeedsQuirksSheet() const {
4170 // SVG documents never load quirk.css.
4171 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4172 return mCompatMode
== eCompatibility_NavQuirks
&& !IsSVGDocument();
4174 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode
);
4175 void RemoveContentEditableStyleSheets();
4176 void AddStyleSheetToStyleSets(StyleSheet
&);
4177 void RemoveStyleSheetFromStyleSets(StyleSheet
&);
4178 void NotifyStyleSheetApplicableStateChanged();
4179 // Just like EnableStyleSheetsForSet, but doesn't check whether
4180 // aSheetSet is null and allows the caller to control whether to set
4181 // aSheetSet as the preferred set in the CSSLoader.
4182 void EnableStyleSheetsForSetInternal(const nsAString
& aSheetSet
,
4183 bool aUpdateCSSLoader
);
4185 already_AddRefed
<nsIURI
> GetDomainURI();
4186 already_AddRefed
<nsIURI
> CreateInheritingURIForHost(
4187 const nsACString
& aHostString
);
4188 already_AddRefed
<nsIURI
> RegistrableDomainSuffixOfInternal(
4189 const nsAString
& aHostSuffixString
, nsIURI
* aOrigHost
);
4191 void WriteCommon(const nsAString
& aText
, bool aNewlineTerminate
,
4192 mozilla::ErrorResult
& aRv
);
4193 // A version of WriteCommon used by WebIDL bindings
4194 void WriteCommon(const mozilla::dom::Sequence
<nsString
>& aText
,
4195 bool aNewlineTerminate
, mozilla::ErrorResult
& rv
);
4197 void* GenerateParserKey(void);
4200 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4202 enum class ExecCommandParam
: uint8_t {
4203 // Always ignore it.
4205 // Treat the given parameter as-is. If the command requires it, use it.
4206 // Otherwise, ignore it.
4208 // Always treat it as boolean parameter.
4210 // Always treat it as boolean, but inverted.
4214 using GetEditorCommandFunc
= mozilla::EditorCommand
*();
4216 struct InternalCommandData
{
4217 const char* mXULCommandName
;
4218 mozilla::Command mCommand
; // uint8_t
4219 // How ConvertToInternalCommand() to treats aValue.
4220 // Its callers don't need to check this.
4221 ExecCommandParam mExecCommandParam
; // uint8_t
4222 GetEditorCommandFunc
* mGetEditorCommandFunc
;
4223 enum class CommandOnTextEditor
: uint8_t {
4226 FallThrough
, // Not disabled, but handled by HTMLEditor if there is one
4228 CommandOnTextEditor mCommandOnTextEditor
;
4230 InternalCommandData()
4231 : mXULCommandName(nullptr),
4232 mCommand(mozilla::Command::DoNothing
),
4233 mExecCommandParam(ExecCommandParam::Ignore
),
4234 mGetEditorCommandFunc(nullptr),
4235 mCommandOnTextEditor(CommandOnTextEditor::Disabled
) {}
4236 InternalCommandData(const char* aXULCommandName
, mozilla::Command aCommand
,
4237 ExecCommandParam aExecCommandParam
,
4238 GetEditorCommandFunc aGetEditorCommandFunc
,
4239 CommandOnTextEditor aCommandOnTextEditor
)
4240 : mXULCommandName(aXULCommandName
),
4242 mExecCommandParam(aExecCommandParam
),
4243 mGetEditorCommandFunc(aGetEditorCommandFunc
),
4244 mCommandOnTextEditor(aCommandOnTextEditor
) {}
4246 bool IsAvailableOnlyWhenEditable() const {
4247 return mCommand
!= mozilla::Command::Cut
&&
4248 mCommand
!= mozilla::Command::Copy
&&
4249 mCommand
!= mozilla::Command::Paste
&&
4250 mCommand
!= mozilla::Command::SetDocumentReadOnly
&&
4251 mCommand
!= mozilla::Command::SelectAll
;
4253 bool IsCutOrCopyCommand() const {
4254 return mCommand
== mozilla::Command::Cut
||
4255 mCommand
== mozilla::Command::Copy
;
4257 bool IsPasteCommand() const { return mCommand
== mozilla::Command::Paste
; }
4261 * AutoEditorCommandTarget considers which editor or global command manager
4262 * handles given command.
4264 class MOZ_RAII AutoEditorCommandTarget
{
4266 MOZ_CAN_RUN_SCRIPT
AutoEditorCommandTarget(
4267 Document
& aDocument
, const InternalCommandData
& aCommandData
);
4268 AutoEditorCommandTarget() = delete;
4269 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget
& aOther
) =
4272 bool DoNothing() const { return mDoNothing
; }
4273 MOZ_CAN_RUN_SCRIPT
bool IsEditable(Document
* aDocument
) const;
4274 bool IsEditor() const {
4275 MOZ_ASSERT_IF(mEditorCommand
, mActiveEditor
|| mHTMLEditor
);
4276 return !!mEditorCommand
;
4279 MOZ_CAN_RUN_SCRIPT
bool IsCommandEnabled() const;
4280 MOZ_CAN_RUN_SCRIPT nsresult
DoCommand(nsIPrincipal
* aPrincipal
) const;
4281 template <typename ParamType
>
4282 MOZ_CAN_RUN_SCRIPT nsresult
DoCommandParam(const ParamType
& aParam
,
4283 nsIPrincipal
* aPrincipal
) const;
4284 MOZ_CAN_RUN_SCRIPT nsresult
4285 GetCommandStateParams(nsCommandParams
& aParams
) const;
4288 // The returned editor's life is guaranteed while this instance is alive.
4289 EditorBase
* GetTargetEditor() const;
4291 RefPtr
<EditorBase
> mActiveEditor
;
4292 RefPtr
<HTMLEditor
> mHTMLEditor
;
4293 RefPtr
<EditorCommand
> mEditorCommand
;
4294 const InternalCommandData
& mCommandData
;
4295 bool mDoNothing
= false;
4299 * Helper method to initialize sInternalCommandDataHashtable.
4301 static void EnsureInitializeInternalCommandDataHashtable();
4304 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4305 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4306 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4307 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4308 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4309 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4310 * returns a copy of instance created with default constructor. I.e., its
4311 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4312 * is unsupported in such case.
4314 * @param aHTMLCommandName Command name in HTML, e.g., used by
4316 * @param aValue The value which is set to the 3rd parameter
4318 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4319 * Will be set to adjusted value for executing
4320 * the internal command.
4321 * @return Returns a copy of instance created with the
4322 * default constructor if there is no
4323 * corresponding internal command for
4324 * aHTMLCommandName or aValue is invalid for
4325 * found internal command when aAdjustedValue
4326 * is not nullptr. Otherwise, returns a copy of
4327 * instance registered in
4328 * sInternalCommandDataHashtable.
4330 static InternalCommandData
ConvertToInternalCommand(
4331 const nsAString
& aHTMLCommandName
, const nsAString
& aValue
= u
""_ns
,
4332 nsAString
* aAdjustedValue
= nullptr);
4335 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4336 * Since it's a bit field, not a bool member, therefore, we cannot use
4337 * AutoRestorer for it.
4339 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final
{
4341 AutoRunningExecCommandMarker() = delete;
4342 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker
&) =
4344 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4345 MOZ_CAN_RUN_SCRIPT
AutoRunningExecCommandMarker(Document
& aDocument
,
4346 nsIPrincipal
* aPrincipal
);
4347 ~AutoRunningExecCommandMarker() {
4348 if (mTreatAsUserInput
) {
4349 mDocument
.mIsRunningExecCommandByChromeOrAddon
=
4350 mHasBeenRunningByChromeOrAddon
;
4352 mDocument
.mIsRunningExecCommandByContent
= mHasBeenRunningByContent
;
4356 [[nodiscard
]] bool IsSafeToRun() const {
4357 // We don't allow nested calls of execCommand even if the caller is chrome
4359 if (mTreatAsUserInput
) {
4360 return !mHasBeenRunningByChromeOrAddon
&& !mHasBeenRunningByContent
;
4362 // If current call is by content, we should ignore whether nested with a
4363 // call by addon (or chrome script) because the caller wants to emulate
4364 // user input for making it undoable. So, we should treat the first
4365 // call as user input.
4366 return !mHasBeenRunningByContent
;
4370 Document
& mDocument
;
4371 bool mTreatAsUserInput
;
4372 bool mHasBeenRunningByContent
;
4373 bool mHasBeenRunningByChromeOrAddon
;
4376 // Mapping table from HTML command name to internal command.
4377 using InternalCommandDataHashtable
=
4378 nsTHashMap
<nsStringCaseInsensitiveHashKey
, InternalCommandData
>;
4379 static InternalCommandDataHashtable
* sInternalCommandDataHashtable
;
4381 mutable std::bitset
<static_cast<size_t>(
4382 DeprecatedOperations::eDeprecatedOperationCount
)>
4383 mDeprecationWarnedAbout
;
4384 mutable std::bitset
<eDocumentWarningCount
> mDocWarningWarnedAbout
;
4386 // Lazy-initialization to have mDocGroup initialized in prior to the
4387 UniquePtr
<ServoStyleSet
> mStyleSet
;
4390 // Never ever call this. Only call GetWindow!
4391 nsPIDOMWindowOuter
* GetWindowInternal() const;
4393 // Never ever call this. Only call GetScriptHandlingObject!
4394 nsIScriptGlobalObject
* GetScriptHandlingObjectInternal() const;
4396 // Never ever call this. Only call AllowXULXBL!
4397 bool InternalAllowXULXBL();
4400 * These methods should be called before and after dispatching
4402 * To make this easy and painless, use the mozAutoSubtreeModified helper
4405 void WillDispatchMutationEvent(nsINode
* aTarget
);
4406 void MutationEventDispatched(nsINode
* aTarget
);
4407 friend class mozAutoSubtreeModified
;
4409 virtual Element
* GetNameSpaceElement() override
{ return GetRootElement(); }
4411 nsCString
GetContentTypeInternal() const { return mContentType
; }
4413 // Update our frame request callback scheduling state, if needed. This will
4414 // schedule or unschedule them, if necessary, and update
4415 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4416 // mPresShell is becoming null; in that case it will be used to get hold of
4417 // the relevant refresh driver.
4418 void UpdateFrameRequestCallbackSchedulingState(
4419 PresShell
* aOldPresShell
= nullptr);
4421 // Helper for GetScrollingElement/IsScrollingElement.
4422 bool IsPotentiallyScrollable(HTMLBodyElement
* aBody
);
4424 void MaybeAllowStorageForOpenerAfterUserInteraction();
4426 void MaybeStoreUserInteractionAsPermission();
4428 // Helpers for GetElementsByName.
4429 static bool MatchNameAttribute(Element
* aElement
, int32_t aNamespaceID
,
4430 nsAtom
* aAtom
, void* aData
);
4431 static void* UseExistingNameString(nsINode
* aRootNode
, const nsString
* aName
);
4433 void MaybeResolveReadyForIdle();
4435 using AutomaticStorageAccessPermissionGrantPromise
=
4436 MozPromise
<bool, bool, true>;
4437 [[nodiscard
]] RefPtr
<AutomaticStorageAccessPermissionGrantPromise
>
4438 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation
);
4440 static void AddToplevelLoadingDocument(Document
* aDoc
);
4441 static void RemoveToplevelLoadingDocument(Document
* aDoc
);
4442 static AutoTArray
<Document
*, 8>* sLoadingForegroundTopLevelContentDocument
;
4443 friend class cycleCollection
;
4445 nsCOMPtr
<nsIReferrerInfo
> mPreloadReferrerInfo
;
4446 nsCOMPtr
<nsIReferrerInfo
> mReferrerInfo
;
4448 nsString mLastModified
;
4450 nsCOMPtr
<nsIURI
> mDocumentURI
;
4451 nsCOMPtr
<nsIURI
> mOriginalURI
;
4452 nsCOMPtr
<nsIURI
> mChromeXHRDocURI
;
4453 nsCOMPtr
<nsIURI
> mDocumentBaseURI
;
4454 nsCOMPtr
<nsIURI
> mChromeXHRDocBaseURI
;
4456 // The base domain of the document for third-party checks.
4457 nsCString mBaseDomain
;
4459 // A lazily-constructed URL data for style system to resolve URL values.
4460 RefPtr
<URLExtraData
> mCachedURLData
;
4461 nsCOMPtr
<nsIReferrerInfo
> mCachedReferrerInfoForInternalCSSAndSVGResources
;
4463 nsWeakPtr mDocumentLoadGroup
;
4465 WeakPtr
<nsDocShell
> mDocumentContainer
;
4467 NotNull
<const Encoding
*> mCharacterSet
;
4468 int32_t mCharacterSetSource
;
4470 OriginTrials mTrials
;
4472 // This is just a weak pointer; the parent document owns its children.
4473 Document
* mParentDocument
;
4475 // A reference to the element last returned from GetRootElement().
4476 Element
* mCachedRootElement
;
4478 // This is maintained by AutoSetRestoreSVGContextPaint.
4479 const SVGContextPaint
* mCurrentContextPaint
= nullptr;
4481 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4482 // which in turn holds a strong reference to this mNodeInfoManager.
4483 nsNodeInfoManager
* mNodeInfoManager
;
4484 RefPtr
<css::Loader
> mCSSLoader
;
4485 RefPtr
<css::ImageLoader
> mStyleImageLoader
;
4487 // The object that contains link color declarations (from the <body> mapped
4488 // attributes), mapped attribute caches, and inline style attribute caches.
4489 RefPtr
<AttributeStyles
> mAttributeStyles
;
4491 // Tracking for images in the document.
4492 RefPtr
<dom::ImageTracker
> mImageTracker
;
4494 // A hashtable of ShadowRoots belonging to the composed doc.
4496 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4497 ShadowRootSet mComposedShadowRoots
;
4499 using SVGUseElementSet
= nsTHashSet
<SVGUseElement
*>;
4501 // The set of <svg:use> elements that need a shadow tree reclone because the
4502 // tree they map to has changed.
4503 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate
;
4505 // The set of all object, embed, video/audio elements or
4506 // nsIObjectLoadingContent or DocumentActivity for which this is
4507 // the owner document. (They might not be in the document.)
4509 // These are non-owning pointers, the elements are responsible for removing
4510 // themselves when they go away.
4511 UniquePtr
<nsTHashSet
<nsISupports
*>> mActivityObservers
;
4513 // A hashtable of styled links keyed by address pointer.
4514 nsTHashSet
<Link
*> mStyledLinks
;
4516 // Indicates whether mStyledLinks was cleared or not. This is used to track
4517 // state so we can provide useful assertions to consumers of ForgetLink and
4518 // AddStyleRelevantLink.
4519 bool mStyledLinksCleared
;
4522 // The array of all links that need their status resolved. Links must add
4523 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4525 static const size_t kSegmentSize
= 128;
4527 using LinksToUpdateList
=
4528 SegmentedVector
<nsCOMPtr
<Link
>, kSegmentSize
, InfallibleAllocPolicy
>;
4530 LinksToUpdateList mLinksToUpdate
;
4532 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4533 RefPtr
<SMILAnimationController
> mAnimationController
;
4535 // Table of element properties for this document.
4536 nsPropertyTable mPropertyTable
;
4538 // Our cached .children collection
4539 nsCOMPtr
<nsIHTMLCollection
> mChildrenCollection
;
4541 // Various DOM lists
4542 RefPtr
<nsContentList
> mImages
;
4543 RefPtr
<nsContentList
> mEmbeds
;
4544 RefPtr
<nsContentList
> mLinks
;
4545 RefPtr
<nsContentList
> mForms
;
4546 RefPtr
<nsContentList
> mScripts
;
4547 nsCOMPtr
<nsIHTMLCollection
> mApplets
;
4548 RefPtr
<nsContentList
> mAnchors
;
4550 // container for per-context fonts (downloadable, SVG, etc.)
4551 RefPtr
<FontFaceSet
> mFontFaceSet
;
4553 // Last time this document or a one of its sub-documents was focused. If
4554 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4555 TimeStamp mLastFocusTime
;
4557 // Last time we found any scroll linked effect in this document.
4558 TimeStamp mLastScrollLinkedEffectDetectionTime
;
4560 DocumentState mState
{DocumentState::LTR_LOCALE
};
4562 RefPtr
<Promise
> mReadyForIdle
;
4564 RefPtr
<mozilla::dom::FeaturePolicy
> mFeaturePolicy
;
4566 // Permission Delegate Handler, lazily-initialized in
4567 // GetPermissionDelegateHandler
4568 RefPtr
<PermissionDelegateHandler
> mPermissionDelegateHandler
;
4570 bool mCachedStateObjectValid
: 1;
4571 bool mBlockAllMixedContent
: 1;
4572 bool mBlockAllMixedContentPreloads
: 1;
4573 bool mUpgradeInsecureRequests
: 1;
4574 bool mUpgradeInsecurePreloads
: 1;
4575 bool mDevToolsWatchingDOMMutations
: 1;
4577 // True if BIDI is enabled.
4578 bool mBidiEnabled
: 1;
4579 // True if we may need to recompute the language prefs for this document.
4580 bool mMayNeedFontPrefsUpdate
: 1;
4581 // True if a MathML element has ever been owned by this document.
4582 bool mMathMLEnabled
: 1;
4584 // True if this document is the initial document for a window. This should
4585 // basically be true only for documents that exist in newly-opened windows or
4586 // documents created to satisfy a GetDocument() on a window when there's no
4588 bool mIsInitialDocumentInWindow
: 1;
4590 // True if this document has ever been the initial document for a window. This
4591 // is useful to determine if a document that was the initial document at one
4592 // point, and became non-initial later.
4593 bool mIsEverInitialDocumentInWindow
: 1;
4595 bool mIgnoreDocGroupMismatches
: 1;
4597 // True if we're loaded as data and therefor has any dangerous stuff, such
4598 // as scripts and plugins, disabled.
4599 bool mLoadedAsData
: 1;
4601 // True if the document is considered for memory reporting as a
4603 bool mAddedToMemoryReportingAsDataDocument
: 1;
4605 // If true, whoever is creating the document has gotten it to the
4606 // point where it's safe to start layout on it.
4607 bool mMayStartLayout
: 1;
4609 // True iff we've ever fired a DOMTitleChanged event for this document
4610 bool mHaveFiredTitleChange
: 1;
4612 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4613 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4614 // before the initial load completes and when we're in bfcache or unloaded,
4616 bool mIsShowing
: 1;
4618 // State for IsVisible(). mVisible starts off true. It becomes false when
4619 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4620 // it's false only when we're in bfcache or unloaded.
4623 // True if our content viewer has been removed from the docshell
4624 // (it may still be displayed, but in zombie state). Form control data
4626 bool mRemovedFromDocShell
: 1;
4628 // True iff DNS prefetch is allowed for this document. Note that if the
4629 // document has no window, DNS prefetch won't be performed no matter what.
4630 bool mAllowDNSPrefetch
: 1;
4632 // True when this document is a static clone of a normal document
4633 bool mIsStaticDocument
: 1;
4635 // True while this document is being cloned to a static document.
4636 bool mCreatingStaticClone
: 1;
4638 // True if this static document has any <canvas> element with a
4639 // mozPrintCallback property at the time of the clone.
4640 bool mHasPrintCallbacks
: 1;
4642 // True iff the document is being unlinked or deleted.
4643 bool mInUnlinkOrDeletion
: 1;
4645 // True if document has ever had script handling object.
4646 bool mHasHadScriptHandlingObject
: 1;
4648 // True if we're an SVG document being used as an image.
4649 bool mIsBeingUsedAsImage
: 1;
4651 // True if our current document URI's scheme enables privileged CSS rules.
4652 bool mChromeRulesEnabled
: 1;
4654 // True if we're loaded in a chrome docshell.
4655 bool mInChromeDocShell
: 1;
4657 // True is this document is synthetic : stand alone image, video, audio
4659 bool mIsSyntheticDocument
: 1;
4661 // True is there is a pending runnable which will call
4662 // FlushPendingLinkUpdates().
4663 bool mHasLinksToUpdateRunnable
: 1;
4665 // True if we're flushing pending link updates.
4666 bool mFlushingPendingLinkUpdates
: 1;
4668 // True if a DOMMutationObserver is perhaps attached to a node in the
4670 bool mMayHaveDOMMutationObservers
: 1;
4672 // True if an nsIAnimationObserver is perhaps attached to a node in the
4674 bool mMayHaveAnimationObservers
: 1;
4676 // True if the document has a CSP delivered throuh a header
4677 bool mHasCSPDeliveredThroughHeader
: 1;
4679 // True if DisallowBFCaching has been called on this document.
4680 bool mBFCacheDisallowed
: 1;
4682 bool mHasHadDefaultView
: 1;
4684 // Whether style sheet change events will be dispatched for this document
4685 bool mStyleSheetChangeEventsEnabled
: 1;
4687 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4688 // will be dispatched for this document.
4689 bool mDevToolsAnonymousAndShadowEventsEnabled
: 1;
4691 // Whether the document was created by a srcdoc iframe.
4692 bool mIsSrcdocDocument
: 1;
4694 // Whether this document has a display document and thus is considered to
4695 // be a resource document. Normally this is the same as !!mDisplayDocument,
4696 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4697 // valid in the document's destructor.
4698 bool mHasDisplayDocument
: 1;
4700 // Is the current mFontFaceSet valid?
4701 bool mFontFaceSetDirty
: 1;
4703 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4704 // (e.g. we're not being parsed at all).
4705 bool mDidFireDOMContentLoaded
: 1;
4707 // True if we have frame request callbacks scheduled with the refresh driver.
4708 // This should generally be updated only via
4709 // UpdateFrameRequestCallbackSchedulingState.
4710 bool mFrameRequestCallbacksScheduled
: 1;
4712 bool mIsTopLevelContentDocument
: 1;
4714 bool mIsContentDocument
: 1;
4716 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4717 bool mDidCallBeginLoad
: 1;
4719 // True if the encoding menu should be disabled.
4720 bool mEncodingMenuDisabled
: 1;
4722 // False if we've disabled link handling for elements inside this document,
4724 bool mLinksEnabled
: 1;
4726 // True if this document is for an SVG-in-OpenType font.
4727 bool mIsSVGGlyphsDocument
: 1;
4729 // True if the document is being destroyed.
4730 bool mInDestructor
: 1;
4732 // True if the document has been detached from its content viewer.
4733 bool mIsGoingAway
: 1;
4735 // Whether we have filled our style set with all the stylesheets.
4736 bool mStyleSetFilled
: 1;
4738 // Whether we have a quirks mode stylesheet in the style set.
4739 bool mQuirkSheetAdded
: 1;
4741 // Whether we have a contenteditable.css stylesheet in the style set.
4742 bool mContentEditableSheetAdded
: 1;
4744 // Whether we have a designmode.css stylesheet in the style set.
4745 bool mDesignModeSheetAdded
: 1;
4747 // True if this document has ever had an HTML or SVG <title> element
4749 bool mMayHaveTitleElement
: 1;
4751 bool mDOMLoadingSet
: 1;
4752 bool mDOMInteractiveSet
: 1;
4753 bool mDOMCompleteSet
: 1;
4754 bool mAutoFocusFired
: 1;
4756 bool mScrolledToRefAlready
: 1;
4757 bool mChangeScrollPosWhenScrollingToRef
: 1;
4759 bool mDelayFrameLoaderInitialization
: 1;
4761 bool mSynchronousDOMContentLoaded
: 1;
4763 // Set to true when the document is possibly controlled by the ServiceWorker.
4764 // Used to prevent multiple requests to ServiceWorkerManager.
4765 bool mMaybeServiceWorkerControlled
: 1;
4767 // These member variables cache information about the viewport so we don't
4768 // have to recalculate it each time.
4769 bool mAllowZoom
: 1;
4770 bool mValidScaleFloat
: 1;
4771 bool mValidMinScale
: 1;
4772 bool mValidMaxScale
: 1;
4773 bool mWidthStrEmpty
: 1;
4775 // Parser aborted. True if the parser of this document was forcibly
4776 // terminated instead of letting it finish at its own pace.
4777 bool mParserAborted
: 1;
4779 // Whether we have reported document use counters for this document with
4780 // Telemetry yet. Normally this is only done at document destruction time,
4781 // but for image documents (SVG documents) that are not guaranteed to be
4782 // destroyed, we report use counters when the image cache no longer has any
4783 // imgRequestProxys pointing to them. We track whether we ever reported use
4784 // counters so that we only report them once for the document.
4785 bool mReportedDocumentUseCounters
: 1;
4787 bool mHasReportedShadowDOMUsage
: 1;
4789 // Whether an event triggered by the refresh driver was delayed because this
4790 // document has suppressed events.
4791 bool mHasDelayedRefreshEvent
: 1;
4793 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4794 // to have the right semantics. See
4795 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4796 // flag that is set while the window's 'load' event is firing if this document
4797 // is the window's document.
4798 bool mLoadEventFiring
: 1;
4800 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4801 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4802 // What we have instead is a flag that is set if completion of our document
4803 // via document.close() should skip firing the load event. Note that this
4804 // flag is only relevant for HTML documents, but lives here for reasons that
4805 // are documented above on SkipLoadEventAfterClose().
4806 bool mSkipLoadEventAfterClose
: 1;
4808 // When false, the .cookies property is completely disabled
4809 bool mDisableCookieAccess
: 1;
4811 // When false, the document.write() API is disabled.
4812 bool mDisableDocWrite
: 1;
4814 // Has document.write() been called with a recursion depth higher than
4816 bool mTooDeepWriteRecursion
: 1;
4819 * Temporary flag that is set in EndUpdate() to ignore
4820 * MaybeEditingStateChanged() script runners from a nested scope.
4822 bool mPendingMaybeEditingStateChanged
: 1;
4824 // mHasBeenEditable is set to true when mEditingState is firstly set to
4825 // eDesignMode or eContentEditable.
4826 bool mHasBeenEditable
: 1;
4828 // Whether we've warned about the CSS zoom property.
4830 // We don't use the general deprecated operation mechanism for this because we
4831 // also record this as a `CountedUnknownProperty`.
4832 bool mHasWarnedAboutZoom
: 1;
4834 // While we're handling an execCommand call by web app, set
4836 bool mIsRunningExecCommandByContent
: 1;
4837 // While we're handling an execCommand call by an addon (or chrome script),
4839 bool mIsRunningExecCommandByChromeOrAddon
: 1;
4841 // True if we should change the readystate to complete after we fire
4842 // DOMContentLoaded. This happens when we abort a load and
4843 // nsDocumentViewer::EndLoad runs while we still have things blocking
4844 // DOMContentLoaded. We wait for those to complete, and then update the
4845 // readystate when they finish.
4846 bool mSetCompleteAfterDOMContentLoaded
: 1;
4848 // Set the true if a completed cached stylesheet was created for the document.
4849 bool mDidHitCompleteSheetCache
: 1;
4851 // Whether we have initialized mShouldReportUseCounters and
4852 // mShouldSendPageUseCounters, and sent any needed message to the parent
4853 // process to indicate that use counter data will be sent at some later point.
4854 bool mUseCountersInitialized
: 1;
4856 // Whether this document should report use counters.
4857 bool mShouldReportUseCounters
: 1;
4859 // Whether this document should send page use counters. Set to true after
4860 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4861 bool mShouldSendPageUseCounters
: 1;
4863 // Whether the user has interacted with the document or not:
4864 bool mUserHasInteracted
: 1;
4866 // We constantly update the user-interaction anti-tracking permission at any
4867 // user-interaction using a timer. This boolean value is set to true when this
4868 // timer is scheduled.
4869 bool mHasUserInteractionTimerScheduled
: 1;
4871 // Whether we should resist fingerprinting.
4872 bool mShouldResistFingerprinting
: 1;
4874 // Whether we are in private browsing mode.
4875 bool mIsInPrivateBrowsing
: 1;
4877 // Whether we're cloning the contents of an SVG use element.
4878 bool mCloningForSVGUse
: 1;
4880 bool mAllowDeclarativeShadowRoots
: 1;
4882 bool mSuspendDOMNotifications
: 1;
4884 // The fingerprinting protections overrides for this document. The value will
4885 // override the default enabled fingerprinting protections for this document.
4886 // This will only get populated if these is one that comes from the local
4887 // fingerprinting protection override pref or WebCompat. Otherwise, a value of
4888 // Nothing() indicates no overrides are present for this document.
4889 Maybe
<RFPTarget
> mOverriddenFingerprintingSettings
;
4891 uint8_t mXMLDeclarationBits
;
4893 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4894 // use uint8_t to avoid having to include a bunch of style system headers
4896 uint8_t mColorSchemeBits
= 0;
4898 // Currently active onload blockers.
4899 uint32_t mOnloadBlockCount
;
4901 // Tracks if we are currently processing any document.write calls (either
4902 // implicit or explicit). Note that if a write call writes out something which
4903 // would block the parser, then mWriteLevel will be incorrect until the parser
4904 // finishes processing that script.
4905 uint32_t mWriteLevel
;
4907 uint32_t mContentEditableCount
;
4908 EditingState mEditingState
;
4910 // Compatibility mode
4911 nsCompatibility mCompatMode
;
4914 ReadyState mReadyState
;
4916 // Ancestor's loading state
4917 bool mAncestorIsLoading
;
4919 // Our visibility state
4920 dom::VisibilityState mVisibilityState
;
4923 eUnknown
, // should never be used
4932 uint8_t mDefaultElementType
;
4934 enum Tri
{ eTriUnset
= 0, eTriFalse
, eTriTrue
};
4938 bool mSkipDTDSecurityChecks
;
4940 // The document's script global object, the object from which the
4941 // document can get its script context and scope. This is the
4942 // *inner* window object.
4943 nsCOMPtr
<nsIScriptGlobalObject
> mScriptGlobalObject
;
4945 // If mIsStaticDocument is true, mOriginalDocument points to the original
4947 RefPtr
<Document
> mOriginalDocument
;
4949 // The bidi options for this document. What this bitfield means is
4950 // defined in nsBidiUtils.h
4951 uint32_t mBidiOptions
;
4953 // The sandbox flags on the document. These reflect the value of the sandbox
4954 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4955 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4957 uint32_t mSandboxFlags
;
4959 // The embedder policy obtained from parsing the HTTP response header or from
4960 // our opener if this is the initial about:blank document.
4961 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> mEmbedderPolicy
;
4963 RefPtr
<nsAtom
> mContentLanguage
;
4965 // The channel that got passed to Document::StartDocumentLoad(), if any.
4966 nsCOMPtr
<nsIChannel
> mChannel
;
4968 // The CSP for every load lives in the Client within the LoadInfo. For all
4969 // document-initiated subresource loads we can use that cached version of the
4970 // CSP so we do not have to deserialize the CSP from the Client all the time.
4971 nsCOMPtr
<nsIContentSecurityPolicy
> mCSP
;
4972 nsCOMPtr
<nsIContentSecurityPolicy
> mPreloadCSP
;
4975 nsCString mContentType
;
4978 // The document's security info
4979 nsCOMPtr
<nsITransportSecurityInfo
> mSecurityInfo
;
4981 // The channel that failed to load and resulted in an error page.
4982 // This only applies to error pages. Might be null.
4983 nsCOMPtr
<nsIChannel
> mFailedChannel
;
4985 // if this document is part of a multipart document,
4986 // the ID can be used to distinguish it from the other parts.
4989 // Cycle collector generation in which we're certain that this document
4990 // won't be collected
4991 uint32_t mMarkedCCGeneration
;
4993 PresShell
* mPresShell
;
4995 nsCOMArray
<nsINode
> mSubtreeModifiedTargets
;
4996 uint32_t mSubtreeModifiedDepth
;
4998 // All images in process of being preloaded. This is a hashtable so
4999 // we can remove them as the real image loads start; that way we
5000 // make sure to not keep the image load going when no one cares
5001 // about it anymore.
5002 nsRefPtrHashtable
<nsURIHashKey
, imgIRequest
> mPreloadingImages
;
5004 // A list of preconnects initiated by the preloader. This prevents
5005 // the same uri from being used more than once, and allows the dom
5006 // builder to not repeat the work of the preloader.
5007 nsTHashMap
<nsURIHashKey
, bool> mPreloadedPreconnects
;
5009 // Current depth of picture elements from parser
5010 uint32_t mPreloadPictureDepth
;
5012 // Set if we've found a URL for the current picture
5013 nsString mPreloadPictureFoundSource
;
5015 // If we're an external resource document, this will be non-null and will
5016 // point to our "display document": the one that all resource lookups should
5018 RefPtr
<Document
> mDisplayDocument
;
5020 uint32_t mEventsSuppressed
;
5022 // Any XHR ChannelEventQueues that were suspended on this document while
5023 // events were suppressed.
5024 nsTArray
<RefPtr
<net::ChannelEventQueue
>> mSuspendedQueues
;
5026 // Any postMessage events that were suspended on this document while events
5028 nsTArray
<RefPtr
<PostMessageEvent
>> mSuspendedPostMessageEvents
;
5030 RefPtr
<EventListener
> mSuppressedEventListener
;
5033 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5035 uint32_t mIgnoreDestructiveWritesCounter
;
5037 // Count of live static clones of this document.
5038 uint32_t mStaticCloneCount
;
5040 // If the document is currently printing (or in print preview) this will point
5041 // to the current static clone of this document. This is weak since the clone
5042 // also has a reference to this document.
5043 WeakPtr
<Document
> mLatestStaticClone
;
5045 // Array of nodes that have been blocked to prevent user tracking.
5046 // They most likely have had their nsIChannel canceled by the URL
5047 // classifier. (Safebrowsing)
5049 // Weak nsINode pointers are used to allow nodes to disappear.
5050 nsTArray
<nsWeakPtr
> mBlockedNodesByClassifier
;
5052 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5053 // updated on every set of mScriptGlobalObject.
5054 nsPIDOMWindowInner
* mWindow
;
5056 nsCOMPtr
<nsIDocumentEncoder
> mCachedEncoder
;
5058 FrameRequestManager mFrameRequestManager
;
5060 // This object allows us to evict ourself from the back/forward cache. The
5061 // pointer is non-null iff we're currently in the bfcache.
5062 nsIBFCacheEntry
* mBFCacheEntry
;
5065 nsString mBaseTarget
;
5067 nsCOMPtr
<nsIStructuredCloneContainer
> mStateObjectContainer
;
5068 JS::Heap
<JS::Value
> mCachedStateObject
;
5070 uint32_t mInSyncOperationCount
;
5072 UniquePtr
<dom::XPathEvaluator
> mXPathEvaluator
;
5074 nsTArray
<RefPtr
<AnonymousContent
>> mAnonymousContents
;
5076 uint32_t mBlockDOMContentLoaded
;
5078 // Our live MediaQueryLists
5079 LinkedList
<MediaQueryList
> mDOMMediaQueryLists
;
5081 // A hashset to keep track of which {element, imgRequestProxy}
5082 // combination has been processed to avoid considering the same
5083 // element twice for LargestContentfulPaint.
5084 nsTHashtable
<LCPEntryHashEntry
> mContentIdentifiersForLCP
;
5086 // Array of observers
5087 nsTObserverArray
<nsIDocumentObserver
*> mObservers
;
5089 // Flags for use counters used directly by this document.
5090 UseCounters mUseCounters
;
5091 // Flags for use counters from resource documents, static clones,
5092 // and SVG images referenced by this document. Those documents propagate
5093 // their use counters up to here, which then count towards the top-level
5094 // document's page use counters.
5095 UseCounters mChildDocumentUseCounters
;
5097 // The CSS property use counters.
5098 UniquePtr
<StyleUseCounters
> mStyleUseCounters
;
5100 TimeStamp mPageUnloadingEventTimeStamp
;
5102 RefPtr
<DocGroup
> mDocGroup
;
5104 RefPtr
<nsCommandManager
> mMidasCommandManager
;
5106 // The set of all the tracking script URLs. URLs are added to this set by
5107 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5108 // existing in the set means the corresponding script isn't a tracking script.
5109 nsTHashSet
<nsCString
> mTrackingScripts
;
5111 // Pointer to our parser if we're currently in the process of being
5113 nsCOMPtr
<nsIParser
> mParser
;
5115 // If the document was created from the the prototype cache there will be a
5116 // reference to the prototype document to allow tracing.
5117 RefPtr
<nsXULPrototypeDocument
> mPrototypeDocument
;
5119 // Weak reference to our sink for in case we no longer have a parser. This
5120 // will allow us to flush out any pending stuff from the sink even if
5121 // EndLoad() has already happened.
5122 nsWeakPtr mWeakSink
;
5124 // Our update nesting level
5125 uint32_t mUpdateNestLevel
;
5127 // HTTPS-Only Mode Status
5128 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5129 uint32_t mHttpsOnlyStatus
;
5131 enum ViewportType
: uint8_t {
5137 ViewportType mViewportType
;
5139 // viewport-fit described by
5140 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5141 ViewportFitType mViewportFit
;
5143 // XXXdholbert This should really be modernized to a nsTHashMap or similar,
5144 // though note that the modernization will need to take care to also convert
5145 // the special hash_table_ops logic (e.g. how SubDocClearEntry clears the
5146 // parent document as part of cleaning up an entry in this table).
5147 UniquePtr
<PLDHashTable
> mSubDocuments
;
5150 UniquePtr
<HeaderData
> mHeaderData
;
5152 nsTArray
<net::EarlyHintConnectArgs
> mEarlyHints
;
5154 class TitleChangeEvent
;
5155 nsRevocableEventPtr
<TitleChangeEvent
> mPendingTitleChangeEvent
;
5157 RefPtr
<nsDOMNavigationTiming
> mTiming
;
5159 // Recorded time of change to 'loading' state
5160 // or time of the page gets restored from BFCache.
5161 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp
;
5163 // Decided to use nsTObserverArray because it allows us to
5164 // remove candidates while iterating them and this is what
5165 // the spec defines. We could implement the spec without
5166 // using nsTObserverArray, however using nsTObserverArray is more clear.
5167 nsTObserverArray
<nsWeakPtr
> mAutoFocusCandidates
;
5169 nsCString mScrollToRef
;
5171 // Weak reference to the scope object (aka the script global object)
5172 // that, unlike mScriptGlobalObject, is never unset once set. This
5173 // is a weak reference to avoid leaks due to circular references.
5174 nsWeakPtr mScopeObject
;
5176 // Array of intersection observers
5177 nsTHashSet
<DOMIntersectionObserver
*> mIntersectionObservers
;
5179 // Array of resize observers
5180 nsTArray
<ResizeObserver
*> mResizeObservers
;
5182 RefPtr
<DOMIntersectionObserver
> mLazyLoadObserver
;
5184 // Elements observed for a last remembered size.
5185 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5186 nsTHashSet
<RefPtr
<Element
>> mElementsObservedForLastRememberedSize
;
5188 // Stack of top layer elements.
5189 nsTArray
<nsWeakPtr
> mTopLayer
;
5191 // The root of the doc tree in which this document is in. This is only
5192 // non-null when this document is in fullscreen mode.
5193 WeakPtr
<Document
> mFullscreenRoot
;
5195 RefPtr
<DOMImplementation
> mDOMImplementation
;
5197 RefPtr
<nsContentList
> mImageMaps
;
5199 // A set of responsive images keyed by address pointer.
5200 nsTHashSet
<HTMLImageElement
*> mResponsiveContent
;
5202 RefPtr
<DocumentTimeline
> mDocumentTimeline
;
5203 LinkedList
<DocumentTimeline
> mTimelines
;
5205 RefPtr
<dom::ScriptLoader
> mScriptLoader
;
5207 // Tracker for scroll-driven animations that are waiting to start.
5208 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5209 RefPtr
<ScrollTimelineAnimationTracker
> mScrollTimelineAnimationTracker
;
5211 // A document "without a browsing context" that owns the content of
5212 // HTMLTemplateElement.
5213 RefPtr
<Document
> mTemplateContentsOwner
;
5215 dom::ExternalResourceMap mExternalResourceMap
;
5217 // ScreenOrientation "pending promise" as described by
5218 // http://www.w3.org/TR/screen-orientation/
5219 RefPtr
<Promise
> mOrientationPendingPromise
;
5221 nsTArray
<RefPtr
<nsFrameLoader
>> mInitializableFrameLoaders
;
5222 nsTArray
<nsCOMPtr
<nsIRunnable
>> mFrameLoaderFinalizers
;
5223 RefPtr
<nsRunnableMethod
<Document
>> mFrameLoaderRunner
;
5225 nsTArray
<PendingFrameStaticClone
> mPendingFrameStaticClones
;
5227 // The layout history state that should be used by nodes in this
5228 // document. We only actually store a pointer to it when:
5229 // 1) We have no script global object.
5230 // 2) We haven't had Destroy() called on us yet.
5231 nsCOMPtr
<nsILayoutHistoryState
> mLayoutHistoryState
;
5233 // Mapping of wake lock types to sets of wake locks sentinels
5234 // https://w3c.github.io/screen-wake-lock/#internal-slots
5235 nsTHashMap
<WakeLockType
, nsTHashSet
<RefPtr
<WakeLockSentinel
>>> mActiveLocks
;
5237 // The parsed viewport metadata of the last modified <meta name=viewport>
5239 UniquePtr
<ViewportMetaData
> mLastModifiedViewportMetaData
;
5241 // A tree ordered list of all color-scheme meta tags in this document.
5243 // TODO(emilio): There are other meta tags in the spec that have a similar
5244 // processing model to color-scheme. We could store all in-document meta tags
5245 // here to get sane and fast <meta> element processing.
5246 TreeOrderedArray
<HTMLMetaElement
*> mColorSchemeMetaTags
;
5248 // These member variables cache information about the viewport so we don't
5249 // have to recalculate it each time.
5250 LayoutDeviceToScreenScale mScaleMinFloat
;
5251 LayoutDeviceToScreenScale mScaleMaxFloat
;
5252 LayoutDeviceToScreenScale mScaleFloat
;
5253 CSSToLayoutDeviceScale mPixelRatio
;
5257 CSSCoord mMinHeight
;
5258 CSSCoord mMaxHeight
;
5260 RefPtr
<EventListenerManager
> mListenerManager
;
5262 nsCOMPtr
<nsIRequest
> mOnloadBlocker
;
5264 // Gecko-internal sheets used for extensions and such.
5265 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5266 nsTArray
<RefPtr
<StyleSheet
>> mAdditionalSheets
[AdditionalSheetTypeCount
];
5268 // Member to store out last-selected stylesheet set.
5269 nsString mLastStyleSheetSet
;
5270 nsString mPreferredStyleSheetSet
;
5272 RefPtr
<DOMStyleSheetSetList
> mStyleSheetSetList
;
5274 // We lazily calculate declaration blocks for elements with mapped
5275 // attributes. This set contains all elements which need lazy resolution.
5276 nsTHashSet
<Element
*> mLazyPresElements
;
5278 nsTHashSet
<RefPtr
<nsAtom
>> mLanguagesUsed
;
5280 // TODO(emilio): Is this hot enough to warrant to be cached?
5281 RefPtr
<nsAtom
> mLanguageFromCharset
;
5283 // Restyle root for servo's style system.
5285 // We store this as an nsINode, rather than as an Element, so that we can
5286 // store the Document node as the restyle root if the entire document (along
5287 // with all document-level native-anonymous content) needs to be restyled.
5289 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5290 // root corresponds to.
5291 nsCOMPtr
<nsINode
> mServoRestyleRoot
;
5292 uint32_t mServoRestyleRootDirtyBits
;
5294 // Used in conjunction with the create-an-element-for-the-token algorithm to
5295 // prevent custom element constructors from being able to use document.open(),
5296 // document.close(), and document.write() when they are invoked by the parser.
5297 uint32_t mThrowOnDynamicMarkupInsertionCounter
;
5299 // Count of unload/beforeunload/pagehide operations in progress.
5300 uint32_t mIgnoreOpensDuringUnloadCounter
;
5302 nsCOMPtr
<nsIDOMXULCommandDispatcher
>
5303 mCommandDispatcher
; // [OWNER] of the focus tracker
5305 RefPtr
<XULBroadcastManager
> mXULBroadcastManager
;
5306 RefPtr
<XULPersist
> mXULPersist
;
5307 RefPtr
<ChromeObserver
> mChromeObserver
;
5309 RefPtr
<HTMLAllCollection
> mAll
;
5311 nsTHashSet
<RefPtr
<WorkerDocumentListener
>> mWorkerListeners
;
5313 // Pres shell resolution saved before entering fullscreen mode.
5314 float mSavedResolution
;
5316 nsCOMPtr
<nsICookieJarSettings
> mCookieJarSettings
;
5318 bool mHasStoragePermission
;
5320 // Document generation. Gets incremented everytime it changes.
5321 int32_t mGeneration
;
5323 // Cached TabSizes values for the document.
5324 int32_t mCachedTabSizeGeneration
;
5325 nsTabSizes mCachedTabSizes
;
5327 // This is equal to document's principal but with an isolation key. See
5328 // StoragePrincipalHelper.h to know more.
5329 nsCOMPtr
<nsIPrincipal
> mPartitionedPrincipal
;
5331 // The cached storage principal for this document.
5332 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5333 // which is required due to its CloneDocHelper() call site. :-(
5334 mutable nsCOMPtr
<nsIPrincipal
> mActiveStoragePrincipal
;
5336 // The cached cookie principal for this document.
5337 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5338 // which is required due to its CloneDocHelper() call site. :-(
5339 mutable nsCOMPtr
<nsIPrincipal
> mActiveCookiePrincipal
;
5341 // See GetNextFormNumber and GetNextControlNumber.
5342 int32_t mNextFormNumber
;
5343 int32_t mNextControlNumber
;
5345 uint32_t mMediaElementWithMSECount
= 0;
5347 // Scope preloads per document. This is used by speculative loading as well.
5348 PreloadService mPreloadService
;
5350 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5351 bool mShouldNotifyFetchSuccess
;
5353 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5354 bool mShouldNotifyFormOrPasswordRemoved
;
5356 // Record page load telemetry
5357 void RecordPageLoadEventTelemetry(
5358 glean::perf::PageLoadExtra
& aEventTelemetryData
);
5360 // Accumulate JS telemetry collected
5361 void AccumulateJSTelemetry(
5362 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5364 // Accumulate page load metrics
5365 void AccumulatePageLoadTelemetry(
5366 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5368 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5369 // Not holding strong refs here since we don't actually use the BBCs.
5370 nsTArray
<const BrowserBridgeChild
*> mOOPChildrenLoading
;
5372 // Registry of custom highlight definitions associated with this document.
5373 RefPtr
<class HighlightRegistry
> mHighlightRegistry
;
5375 // Used for tracking a number of recent canvas extractions (e.g. toDataURL),
5376 // this is used for a canvas fingerprinter detection heuristic.
5377 nsTArray
<CanvasUsage
> mCanvasUsage
;
5378 uint64_t mLastCanvasUsage
= 0;
5380 RefPtr
<class FragmentDirective
> mFragmentDirective
;
5381 UniquePtr
<RadioGroupContainer
> mRadioGroupContainer
;
5384 // Needs to be public because the bindings code pokes at it.
5385 JS::ExpandoAndGeneration mExpandoAndGeneration
;
5387 bool HasPendingInitialTranslation();
5389 nsRefPtrHashtable
<nsRefPtrHashKey
<Element
>, nsXULPrototypeElement
>
5392 void LoadEventFired();
5394 RadioGroupContainer
& OwnedRadioGroupContainer();
5396 static already_AddRefed
<Document
> ParseHTMLUnsafe(GlobalObject
& aGlobal
,
5397 const nsAString
& aHTML
);
5400 NS_DEFINE_STATIC_IID_ACCESSOR(Document
, NS_IDOCUMENT_IID
)
5403 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5404 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5405 * object is deleted.
5407 class MOZ_STACK_CLASS mozAutoSubtreeModified
{
5410 * @param aSubTreeOwner The document in which a subtree will be modified.
5411 * @param aTarget The target of the possible DOMSubtreeModified event.
5412 * Can be nullptr, in which case mozAutoSubtreeModified
5413 * is just used to batch DOM mutations.
5415 mozAutoSubtreeModified(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5416 UpdateTarget(aSubtreeOwner
, aTarget
);
5419 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5421 void UpdateTarget(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5422 if (mSubtreeOwner
) {
5423 mSubtreeOwner
->MutationEventDispatched(mTarget
);
5427 mSubtreeOwner
= aSubtreeOwner
;
5428 if (mSubtreeOwner
) {
5429 mSubtreeOwner
->WillDispatchMutationEvent(mTarget
);
5434 nsCOMPtr
<nsINode
> mTarget
;
5435 RefPtr
<Document
> mSubtreeOwner
;
5438 enum class SyncOperationBehavior
{ eSuspendInput
, eAllowInput
};
5440 class AutoWalkBrowsingContextGroup
{
5442 virtual ~AutoWalkBrowsingContextGroup() = default;
5445 void SuppressBrowsingContext(BrowsingContext
* aContext
);
5446 void SuppressBrowsingContextGroup(BrowsingContextGroup
* aGroup
);
5447 void UnsuppressDocuments() {
5448 for (const auto& doc
: mDocuments
) {
5449 UnsuppressDocument(doc
);
5452 virtual void SuppressDocument(Document
* aDocument
) = 0;
5453 virtual void UnsuppressDocument(Document
* aDocument
) = 0;
5454 AutoTArray
<RefPtr
<Document
>, 16> mDocuments
;
5457 class MOZ_RAII nsAutoSyncOperation
: private AutoWalkBrowsingContextGroup
{
5459 explicit nsAutoSyncOperation(Document
* aDocument
,
5460 SyncOperationBehavior aSyncBehavior
);
5461 ~nsAutoSyncOperation();
5464 void SuppressDocument(Document
* aDocument
) override
;
5465 void UnsuppressDocument(Document
* aDocument
) override
;
5468 uint32_t mMicroTaskLevel
;
5469 const SyncOperationBehavior mSyncBehavior
;
5470 RefPtr
<BrowsingContext
> mBrowsingContext
;
5473 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final
{
5475 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document
* aDocument
)
5476 : mDocument(aDocument
) {
5477 mDocument
->IncrementThrowOnDynamicMarkupInsertionCounter();
5480 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5481 mDocument
->DecrementThrowOnDynamicMarkupInsertionCounter();
5485 Document
* mDocument
;
5488 class MOZ_RAII IgnoreOpensDuringUnload final
{
5490 explicit IgnoreOpensDuringUnload(Document
* aDoc
) : mDoc(aDoc
) {
5491 mDoc
->IncrementIgnoreOpensDuringUnloadCounter();
5494 ~IgnoreOpensDuringUnload() {
5495 mDoc
->DecrementIgnoreOpensDuringUnloadCounter();
5502 bool IsInFocusedTab(Document
* aDoc
);
5504 // This covers all cases covered by IsInFocusedTab, but also ensures that
5505 // focused tab is "active" meaning not occluded.
5506 bool IsInActiveTab(Document
* aDoc
);
5508 } // namespace mozilla::dom
5510 NON_VIRTUAL_ADDREF_RELEASE(mozilla::dom::Document
)
5512 // XXX These belong somewhere else
5513 nsresult
NS_NewHTMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5514 nsIPrincipal
* aPrincipal
,
5515 nsIPrincipal
* aPartitionedPrincipal
,
5516 bool aLoadedAsData
= false);
5518 nsresult
NS_NewXMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5519 nsIPrincipal
* aPrincipal
,
5520 nsIPrincipal
* aPartitionedPrincipal
,
5521 bool aLoadedAsData
= false,
5522 bool aIsPlainDocument
= false);
5524 nsresult
NS_NewSVGDocument(mozilla::dom::Document
** aInstancePtrResult
,
5525 nsIPrincipal
* aPrincipal
,
5526 nsIPrincipal
* aPartitionedPrincipal
);
5528 nsresult
NS_NewImageDocument(mozilla::dom::Document
** aInstancePtrResult
,
5529 nsIPrincipal
* aPrincipal
,
5530 nsIPrincipal
* aPartitionedPrincipal
);
5532 nsresult
NS_NewVideoDocument(mozilla::dom::Document
** aInstancePtrResult
,
5533 nsIPrincipal
* aPrincipal
,
5534 nsIPrincipal
* aPartitionedPrincipal
);
5536 // Enum for requesting a particular type of document when creating a doc
5537 enum DocumentFlavor
{
5538 DocumentFlavorLegacyGuess
, // compat with old code until made HTML5-compliant
5539 DocumentFlavorHTML
, // HTMLDocument with HTMLness bit set to true
5540 DocumentFlavorSVG
, // SVGDocument
5541 DocumentFlavorXML
, // XMLDocument
5542 DocumentFlavorPlain
, // Just a Document
5545 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5546 // -- this method will not attempt to get a principal based on aDocumentURI.
5547 // Also, both aDocumentURI and aBaseURI must not be null.
5548 nsresult
NS_NewDOMDocument(
5549 mozilla::dom::Document
** aInstancePtrResult
, const nsAString
& aNamespaceURI
,
5550 const nsAString
& aQualifiedName
, mozilla::dom::DocumentType
* aDoctype
,
5551 nsIURI
* aDocumentURI
, nsIURI
* aBaseURI
, nsIPrincipal
* aPrincipal
,
5552 bool aLoadedAsData
, nsIGlobalObject
* aEventObject
, DocumentFlavor aFlavor
);
5554 inline mozilla::dom::Document
* nsINode::GetOwnerDocument() const {
5555 mozilla::dom::Document
* ownerDoc
= OwnerDoc();
5557 return ownerDoc
!= this ? ownerDoc
: nullptr;
5560 inline nsINode
* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5562 inline mozilla::dom::Document
* nsINode::AsDocument() {
5563 MOZ_ASSERT(IsDocument());
5564 return static_cast<mozilla::dom::Document
*>(this);
5567 inline const mozilla::dom::Document
* nsINode::AsDocument() const {
5568 MOZ_ASSERT(IsDocument());
5569 return static_cast<const mozilla::dom::Document
*>(this);
5572 inline nsISupports
* ToSupports(mozilla::dom::Document
* aDoc
) {
5573 return static_cast<nsINode
*>(aDoc
);
5576 #endif /* mozilla_dom_Document_h___ */