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 "nsWeakReference.h"
105 #include "nsWindowSizes.h"
106 #include "nsXULElement.h"
109 // XXX We need to include this here to ensure that DefaultDeleter for Servo
110 // types is specialized before the template is instantiated. Probably, this
111 // should be included at some other place already that's generated by cbindgen.
112 #include "mozilla/ServoBindingTypes.h"
114 // windows.h #defines CreateEvent
119 #ifdef MOZILLA_INTERNAL_API
120 # include "mozilla/dom/DocumentBinding.h"
124 class ElementCreationOptionsOrString
;
126 } // namespace mozilla
127 #endif // MOZILLA_INTERNAL_API
129 class InfallibleAllocPolicy
;
133 class gfxUserFontSet
;
134 class mozIDOMWindowProxy
;
135 class nsCachableElementsByNameNodeList
;
136 class nsCommandManager
;
138 class nsCycleCollectionTraversalCallback
;
139 class nsDOMCaretPosition
;
140 class nsDOMNavigationTiming
;
143 class nsFrameLoaderOwner
;
144 class nsGenericHTMLElement
;
145 class nsGlobalWindowInner
;
146 class nsHTMLDocument
;
147 class nsHtml5TreeOpExecutor
;
149 class nsIAsyncVerifyRedirectCallback
;
150 class nsIBFCacheEntry
;
152 class nsIContentSecurityPolicy
;
153 class nsIContentSink
;
154 class nsICookieJarSettings
;
155 class nsIDOMXULCommandDispatcher
;
157 class nsIDocShellTreeItem
;
158 class nsIDocumentEncoder
;
159 class nsIDocumentObserver
;
160 class nsIEventTarget
;
162 class nsIGlobalObject
;
163 class nsIHTMLCollection
;
164 class nsIInputStream
;
165 class nsILayoutHistoryState
;
166 class nsIObjectLoadingContent
;
167 class nsIPermissionDelegateHandler
;
168 class nsIRadioVisitor
;
171 class nsIScriptGlobalObject
;
172 class nsISecurityConsoleMessage
;
173 class nsISerialEventTarget
;
174 class nsIStructuredCloneContainer
;
176 class nsNodeInfoManager
;
177 class nsPIWindowRoot
;
180 class nsSimpleContentList
;
183 class nsViewportInfo
;
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
;
249 class HighlightRegistry
;
250 class HTMLAllCollection
;
251 class HTMLBodyElement
;
252 class HTMLInputElement
;
253 class HTMLMetaElement
;
254 class HTMLDialogElement
;
255 class HTMLSharedElement
;
256 class HTMLVideoElement
;
257 class HTMLImageElement
;
259 enum class InteractiveWidget
: uint8_t;
260 struct LifecycleCallbackArgs
;
263 class MediaQueryList
;
268 enum class OrientationType
: uint8_t;
269 class ProcessingInstruction
;
273 class ServiceWorkerDescriptor
;
283 class TrustedHTMLOrString
;
284 class OwningTrustedHTMLOrString
;
285 enum class ViewportFitType
: uint8_t;
286 class ViewTransition
;
287 class ViewTransitionUpdateCallback
;
288 class WakeLockSentinel
;
290 class WindowGlobalChild
;
291 class WindowProxyHolder
;
293 class WorkerDocumentListener
;
294 class XPathEvaluator
;
295 class XPathExpression
;
296 class XPathNSResolver
;
298 class BrowsingContext
;
300 class nsUnblockOnloadEvent
;
302 template <typename
, typename
>
303 class CallbackObjectHolder
;
305 enum class CallerType
: uint32_t;
308 NOT_ALLOWED
= 1 << 0, // Status 0
309 EVENT_HANDLING_SUPPRESSED
= 1 << 1, // Status 1
310 SUSPENDED
= 1 << 2, // Status 2
311 UNLOAD_LISTENER
= 1 << 3, // Status 3
312 REQUEST
= 1 << 4, // Status 4
313 ACTIVE_GET_USER_MEDIA
= 1 << 5, // Status 5
314 ACTIVE_PEER_CONNECTION
= 1 << 6, // Status 6
315 CONTAINS_EME_CONTENT
= 1 << 7, // Status 7
316 CONTAINS_MSE_CONTENT
= 1 << 8, // Status 8
317 HAS_ACTIVE_SPEECH_SYNTHESIS
= 1 << 9, // Status 9
318 HAS_USED_VR
= 1 << 10, // Status 10
319 CONTAINS_REMOTE_SUBFRAMES
= 1 << 11, // Status 11
320 NOT_ONLY_TOPLEVEL_IN_BCG
= 1 << 12, // Status 12
321 ABOUT_PAGE
= 1 << 13, // Status 13
322 RESTORING
= 1 << 14, // Status 14
323 BEFOREUNLOAD_LISTENER
= 1 << 15, // Status 15
324 ACTIVE_LOCK
= 1 << 16, // Status 16
325 ACTIVE_WEBTRANSPORT
= 1 << 17, // Status 17
329 namespace glean::perf
{
330 struct PageLoadExtra
;
332 } // namespace mozilla
334 namespace mozilla::net
{
335 class ChannelEventQueue
;
336 class EarlyHintConnectArgs
;
337 } // namespace mozilla::net
339 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
340 #define NS_IDOCUMENT_IID \
341 {0xce1f7627, 0x7109, 0x4977, {0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa}}
343 namespace mozilla::dom
{
346 class DOMStyleSheetSetList
;
347 class ResizeObserver
;
348 class ResizeObserverController
;
349 class PostMessageEvent
;
351 #define DEPRECATED_OPERATION(_op) e##_op,
352 enum class DeprecatedOperations
: uint16_t {
353 #include "nsDeprecatedOperationList.h"
354 eDeprecatedOperationCount
356 #undef DEPRECATED_OPERATION
358 class ExternalResourceMap
{
359 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
363 * A class that represents an external resource load that has begun but
364 * doesn't have a document yet. Observers can be registered on this object,
365 * and will be notified after the document is created. Observers registered
366 * after the document has been created will NOT be notified. When observers
367 * are notified, the subject will be the newly-created document, the topic
368 * will be "external-resource-document-created", and the data will be null.
369 * If document creation fails for some reason, observers will still be
370 * notified, with a null document pointer.
372 class ExternalResourceLoad
: public nsISupports
{
374 virtual ~ExternalResourceLoad() = default;
376 void AddObserver(nsIObserver
* aObserver
) {
377 MOZ_ASSERT(aObserver
, "Must have observer");
378 mObservers
.AppendElement(aObserver
);
381 const nsTArray
<nsCOMPtr
<nsIObserver
>>& Observers() { return mObservers
; }
384 AutoTArray
<nsCOMPtr
<nsIObserver
>, 8> mObservers
;
387 ExternalResourceMap();
390 * Request an external resource document. This does exactly what
391 * Document::RequestExternalResource is documented to do.
393 Document
* RequestResource(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
394 nsINode
* aRequestingNode
,
395 Document
* aDisplayDocument
,
396 ExternalResourceLoad
** aPendingLoad
);
399 * Enumerate the resource documents. See
400 * Document::EnumerateExternalResources.
402 void EnumerateResources(SubDocEnumFunc aCallback
);
405 * Traverse ourselves for cycle-collection
407 void Traverse(nsCycleCollectionTraversalCallback
* aCallback
) const;
410 * Shut ourselves down (used for cycle-collection unlink), as well
411 * as for document destruction.
414 mPendingLoads
.Clear();
416 mHaveShutDown
= true;
419 bool HaveShutDown() const { return mHaveShutDown
; }
421 // Needs to be public so we can traverse them sanely
422 struct ExternalResource
{
424 RefPtr
<Document
> mDocument
;
425 nsCOMPtr
<nsIDocumentViewer
> mViewer
;
426 nsCOMPtr
<nsILoadGroup
> mLoadGroup
;
429 // Hide all our viewers
432 // Show all our viewers
436 class PendingLoad
: public ExternalResourceLoad
, public nsIStreamListener
{
437 ~PendingLoad() = default;
440 explicit PendingLoad(Document
* aDisplayDocument
)
441 : mDisplayDocument(aDisplayDocument
) {}
444 NS_DECL_NSISTREAMLISTENER
445 NS_DECL_NSIREQUESTOBSERVER
448 * Start aURI loading. This will perform the necessary security checks and
451 nsresult
StartLoad(nsIURI
* aURI
, nsIReferrerInfo
* aReferrerInfo
,
452 nsINode
* aRequestingNode
);
454 * Set up an nsIDocumentViewer based on aRequest. This is guaranteed to
455 * put null in *aViewer and *aLoadGroup on all failures.
457 nsresult
SetupViewer(nsIRequest
* aRequest
, nsIDocumentViewer
** aViewer
,
458 nsILoadGroup
** aLoadGroup
);
461 RefPtr
<Document
> mDisplayDocument
;
462 nsCOMPtr
<nsIStreamListener
> mTargetListener
;
463 nsCOMPtr
<nsIURI
> mURI
;
465 friend class PendingLoad
;
467 class LoadgroupCallbacks final
: public nsIInterfaceRequestor
{
468 ~LoadgroupCallbacks() = default;
471 explicit LoadgroupCallbacks(nsIInterfaceRequestor
* aOtherCallbacks
)
472 : mCallbacks(aOtherCallbacks
) {}
474 NS_DECL_NSIINTERFACEREQUESTOR
476 // The only reason it's safe to hold a strong ref here without leaking is
477 // that the notificationCallbacks on a loadgroup aren't the docshell itself
478 // but a shim that holds a weak reference to the docshell.
479 nsCOMPtr
<nsIInterfaceRequestor
> mCallbacks
;
481 // Use shims for interfaces that docshell implements directly so that we
482 // don't hand out references to the docshell. The shims should all allow
483 // getInterface back on us, but other than that each one should only
484 // implement one interface.
486 // XXXbz I wish we could just derive the _allcaps thing from _i
487 #define DECL_SHIM(_i, _allcaps) \
488 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
492 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
493 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
494 NS_ASSERTION(mIfReq, "Expected non-null here"); \
495 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
498 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
499 NS_FORWARD_##_allcaps(mRealPtr->) private \
500 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
501 nsCOMPtr<_i> mRealPtr; \
504 DECL_SHIM(nsILoadContext
, NSILOADCONTEXT
)
505 DECL_SHIM(nsIProgressEventSink
, NSIPROGRESSEVENTSINK
)
506 DECL_SHIM(nsIChannelEventSink
, NSICHANNELEVENTSINK
)
511 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
512 * when this is called if the URI didn't result in an XML document. This
513 * function makes sure to remove the pending load for aURI, if any, from our
514 * hashtable, and to notify its observers, if any.
516 nsresult
AddExternalResource(nsIURI
* aURI
, nsIDocumentViewer
* aViewer
,
517 nsILoadGroup
* aLoadGroup
,
518 Document
* aDisplayDocument
);
520 nsClassHashtable
<nsURIHashKey
, ExternalResource
> mMap
;
521 nsRefPtrHashtable
<nsURIHashKey
, PendingLoad
> mPendingLoads
;
525 // The current status for a preload.
526 enum class SheetPreloadStatus
: uint8_t {
527 // There's no need to preload anything, the sheet is already in-memory.
529 // The load is in-progress. There's no guarantee that a load was started, it
530 // could be coalesced with other redundant loads.
532 // Something went wrong, and we errored out.
536 //----------------------------------------------------------------------
538 // Document interface. This is implemented by all document objects in
540 class Document
: public nsINode
,
541 public DocumentOrShadowRoot
,
542 public nsSupportsWeakReference
,
543 public nsIScriptObjectPrincipal
,
544 public SupportsWeakPtr
{
545 friend class DocumentOrShadowRoot
;
548 explicit Document(const char* aContentType
);
551 Document(const Document
&) = delete;
552 Document
& operator=(const Document
&) = delete;
555 using ExternalResourceLoad
= dom::ExternalResourceMap::ExternalResourceLoad
;
556 using ReferrerPolicyEnum
= dom::ReferrerPolicy
;
557 using AdoptedStyleSheetCloneCache
=
558 nsRefPtrHashtable
<nsPtrHashKey
<const StyleSheet
>, StyleSheet
>;
560 // nsINode overrides the new operator for DOM Arena allocation.
561 // to use the default one, we need to bring it back again
562 void* operator new(size_t aSize
) { return ::operator new(aSize
); }
565 * Called when XPCOM shutdown.
567 static void Shutdown();
569 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID
)
571 NS_DECL_ISUPPORTS_INHERITED
572 NS_IMETHOD_(void) DeleteCycleCollectable() override
;
574 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
576 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document
,
579 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
581 for (RefPtr obs : mObservers.ForwardRange()) { \
582 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
583 obs->func_ params_; \
586 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
588 if (PresShell* presShell = GetObservingPresShell()) { \
589 presShell->func_ params_; \
593 nsIPrincipal
* EffectiveCookiePrincipal() const;
595 nsIPrincipal
* EffectiveStoragePrincipal() const;
597 // nsIScriptObjectPrincipal
598 nsIPrincipal
* GetPrincipal() final
{ return NodePrincipal(); }
600 nsIPrincipal
* GetEffectiveCookiePrincipal() final
{
601 return EffectiveCookiePrincipal();
604 nsIPrincipal
* GetEffectiveStoragePrincipal() final
{
605 return EffectiveStoragePrincipal();
608 // You should probably not be using this function, since it performs no checks
609 // to ensure that the partitioned principal should really be used here. It is
610 // only designed to be used in very specific circumstances, such as when
611 // inheriting the document/storage principal.
612 nsIPrincipal
* PartitionedPrincipal() final
{ return mPartitionedPrincipal
; }
614 // Gets the appropriate principal to check the URI against a blocklist /
616 nsIPrincipal
* GetPrincipalForPrefBasedHacks() const;
618 void ClearActiveCookieAndStoragePrincipals() {
619 mActiveStoragePrincipal
= nullptr;
620 mActiveCookiePrincipal
= nullptr;
624 void GetEventTargetParent(EventChainPreVisitor
& aVisitor
) override
;
625 EventListenerManager
* GetOrCreateListenerManager() override
;
626 EventListenerManager
* GetExistingListenerManager() const override
;
628 // This helper class must be set when we dispatch beforeunload and unload
629 // events in order to avoid unterminate sync XHRs.
630 class MOZ_RAII PageUnloadingEventTimeStamp
{
631 RefPtr
<Document
> mDocument
;
635 explicit PageUnloadingEventTimeStamp(Document
* aDocument
)
636 : mDocument(aDocument
), mSet(false) {
637 MOZ_ASSERT(aDocument
);
638 if (mDocument
->mPageUnloadingEventTimeStamp
.IsNull()) {
639 mDocument
->SetPageUnloadingEventTimeStamp();
644 ~PageUnloadingEventTimeStamp() {
646 mDocument
->CleanUnloadEventsTimeStamp();
652 * Let the document know that we're starting to load data into it.
653 * @param aCommand The parser command. Must not be null.
654 * XXXbz It's odd to have that here.
655 * @param aChannel The channel the data will come from. The channel must be
656 * able to report its Content-Type.
657 * @param aLoadGroup The loadgroup this document should use from now on.
658 * Note that the document might not be the only thing using
660 * @param aContainer The container this document is in. This may be null.
661 * XXXbz maybe we should make it more explicit (eg make the
662 * container an nsIWebNavigation or nsIDocShell or
664 * @param [out] aDocListener the listener to pump data from the channel into.
665 * Generally this will be the parser this document
666 * sets up, or some sort of data-handler for media
668 * @param aReset whether the document should call Reset() on itself. If this
669 * is false, the document will NOT set its principal to the
670 * channel's owner, will not clear any event listeners that are
671 * already set on it, etc.
673 * Once this has been called, the document will return false for
674 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
675 * sure this happens is the responsibility of the caller of
676 * StartDocumentLoad().
678 * This function has an implementation, and does some setup, but does NOT set
679 * *aDocListener; this is the job of subclasses.
681 virtual nsresult
StartDocumentLoad(const char* aCommand
, nsIChannel
* aChannel
,
682 nsILoadGroup
* aLoadGroup
,
683 nsISupports
* aContainer
,
684 nsIStreamListener
** aDocListener
,
686 void StopDocumentLoad();
688 virtual void SetSuppressParserErrorElement(bool aSuppress
) {}
689 virtual bool SuppressParserErrorElement() { return false; }
691 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress
) {}
692 virtual bool SuppressParserErrorConsoleMessages() { return false; }
695 void InsertChildBefore(nsIContent
* aKid
, nsIContent
* aBeforeThis
,
696 bool aNotify
, ErrorResult
& aRv
) override
;
697 void RemoveChildNode(nsIContent
* aKid
, bool aNotify
,
698 const BatchRemovalState
* = nullptr) final
;
699 nsresult
Clone(dom::NodeInfo
* aNodeInfo
, nsINode
** aResult
) const override
{
700 return NS_ERROR_NOT_IMPLEMENTED
;
702 nsresult
CloneDocHelper(Document
* clone
) const;
704 Document
* GetLatestStaticClone() const { return mLatestStaticClone
; }
707 * Signal that the document title may have changed
708 * (see Document::GetTitle).
709 * @param aBoundTitleElement true if an HTML or SVG <title> element
710 * has just been bound to the document.
712 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement
);
715 * Return the URI for the document. May return null. If it ever stops being
716 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
717 * also never return null.
719 * The value returned corresponds to the "document's address" in
720 * HTML5. As such, it may change over the lifetime of the document, for
721 * instance as a result of the user navigating to a fragment identifier on
722 * the page, or as a result to a call to pushState() or replaceState().
724 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
726 nsIURI
* GetDocumentURI() const { return mDocumentURI
; }
729 * Return the original URI of the document. This is the same as the
730 * document's URI unless that has changed from its original value (for
731 * example, due to history.pushState() or replaceState() being invoked on the
734 * This method corresponds to the "creation URL" in HTML5 and, once set,
735 * doesn't change over the lifetime of the document.
737 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
739 nsIURI
* GetOriginalURI() const { return mOriginalURI
; }
742 * Return the base domain of the document. This has been computed using
743 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
744 * checks. When the URI of the document changes, this value is recomputed.
746 nsCString
GetBaseDomain() const { return mBaseDomain
; }
749 * Set the URI for the document. This also sets the document's original URI,
752 void SetDocumentURI(nsIURI
* aURI
);
755 * Set the URI for the document loaded via XHR, when accessed from
756 * chrome privileged script.
758 void SetChromeXHRDocURI(nsIURI
* aURI
) { mChromeXHRDocURI
= aURI
; }
761 * Set the base URI for the document loaded via XHR, when accessed from
762 * chrome privileged script.
764 void SetChromeXHRDocBaseURI(nsIURI
* aURI
) { mChromeXHRDocBaseURI
= aURI
; }
767 * The CSP in general is stored in the ClientInfo, but we also cache
768 * the CSP on the document so subresources loaded within a document
769 * can query that cached CSP instead of having to deserialize the CSP
772 * Please note that at the time of CSP parsing the Client is not
773 * available yet, hence we sync CSP of document and Client when the
774 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
776 nsIContentSecurityPolicy
* GetCsp() const;
777 void SetCsp(nsIContentSecurityPolicy
* aCSP
);
779 nsIContentSecurityPolicy
* GetPreloadCsp() const;
780 void SetPreloadCsp(nsIContentSecurityPolicy
* aPreloadCSP
);
782 void GetCspJSON(nsString
& aJSON
);
785 * Set referrer policy and upgrade-insecure-requests flags
787 void ApplySettingsFromCSP(bool aSpeculative
);
789 already_AddRefed
<nsIParser
> CreatorParserOrNull() {
790 nsCOMPtr
<nsIParser
> parser
= mParser
;
791 return parser
.forget();
795 * ReferrerInfo getter for Document.webidl.
797 nsIReferrerInfo
* ReferrerInfo() const { return GetReferrerInfo(); }
799 nsIReferrerInfo
* GetReferrerInfo() const { return mReferrerInfo
; }
801 nsIReferrerInfo
* GetPreloadReferrerInfo() const {
802 return mPreloadReferrerInfo
;
805 * Return the referrer policy of the document. Return "default" if there's no
806 * valid meta referrer tag found in the document.
807 * Referrer policy should be inherited from parent if the iframe is srcdoc
809 ReferrerPolicyEnum
GetReferrerPolicy() const;
812 * GetReferrerPolicy() for Document.webidl.
814 ReferrerPolicyEnum
ReferrerPolicy() const { return GetReferrerPolicy(); }
817 * If true, this flag indicates that all mixed content subresource
818 * loads for this document (and also embeded browsing contexts) will
821 bool GetBlockAllMixedContent(bool aPreload
) const {
823 return mBlockAllMixedContentPreloads
;
825 return mBlockAllMixedContent
;
829 * If true, this flag indicates that all subresource loads for this
830 * document need to be upgraded from http to https.
831 * This flag becomes true if the CSP of the document itself, or any
832 * of the document's ancestors up to the toplevel document makes use
833 * of the CSP directive 'upgrade-insecure-requests'.
835 bool GetUpgradeInsecureRequests(bool aPreload
) const {
837 return mUpgradeInsecurePreloads
;
839 return mUpgradeInsecureRequests
;
842 void SetReferrerInfo(nsIReferrerInfo
*);
845 * Referrer policy from <meta name="referrer" content=`policy`>
846 * will have higher priority than referrer policy from Referrer-Policy
847 * header. So override the old ReferrerInfo if we get one from meta
849 void UpdateReferrerInfoFromMeta(const nsAString
& aMetaReferrer
,
853 * Set the principals responsible for this document. Chances are, you do not
854 * want to be using this.
856 void SetPrincipals(nsIPrincipal
* aPrincipal
,
857 nsIPrincipal
* aPartitionedPrincipal
);
860 * Returns true if exempt from HTTPS-Only Mode upgrade.
862 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus
; }
865 * Return the LoadGroup for the document. May return null.
867 already_AddRefed
<nsILoadGroup
> GetDocumentLoadGroup() const {
868 nsCOMPtr
<nsILoadGroup
> group
= do_QueryReferent(mDocumentLoadGroup
);
869 return group
.forget();
873 * Return the fallback base URL for this document, as defined in the HTML
874 * specification. Note that this can return null if there is no document URI.
876 * XXXbz: This doesn't implement the bits for about:blank yet.
878 nsIURI
* GetFallbackBaseURI() const {
879 if (mIsSrcdocDocument
&& mParentDocument
) {
880 return mParentDocument
->GetDocBaseURI();
886 * Return the referrer from document URI as defined in the Referrer Policy
888 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
889 * While document is an iframe srcdoc document, let document be document's
890 * browsing context's browsing context container's node document.
891 * Then referrer should be document's URL
894 nsIURI
* GetDocumentURIAsReferrer() const {
895 if (mIsSrcdocDocument
&& mParentDocument
) {
896 return mParentDocument
->GetDocumentURIAsReferrer();
902 * Return the base URI for relative URIs in the document (the document uri
903 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
904 * returned URI could be null if there is no document URI. If the document is
905 * a srcdoc document and has no explicit base URL, return the parent
906 * document's base URL.
908 nsIURI
* GetDocBaseURI() const {
909 if (mDocumentBaseURI
) {
910 return mDocumentBaseURI
;
912 return GetFallbackBaseURI();
915 nsIURI
* GetBaseURI(bool aTryUseXHRDocBaseURI
= false) const final
;
917 void SetBaseURI(nsIURI
* aURI
);
920 * Resolves a URI based on the document's base URI.
922 Result
<OwningNonNull
<nsIURI
>, nsresult
> ResolveWithBaseURI(
923 const nsAString
& aURI
);
926 * Return the URL data which style system needs for resolving url value.
927 * This method attempts to use the cached object in mCachedURLData, but
928 * if the base URI, document URI, or principal has changed since last
929 * call to this function, or the function is called the first time for
930 * the document, a new one is created.
932 URLExtraData
* DefaultStyleAttrURLData();
933 nsIReferrerInfo
* ReferrerInfoForInternalCSSAndSVGResources();
936 * Get/Set the base target of a link in a document.
938 void GetBaseTarget(nsAString
& aBaseTarget
) const {
939 aBaseTarget
= mBaseTarget
;
942 void SetBaseTarget(const nsString
& aBaseTarget
) { mBaseTarget
= aBaseTarget
; }
945 * Return a standard name for the document's character set.
947 NotNull
<const Encoding
*> GetDocumentCharacterSet() const {
948 return mCharacterSet
;
952 * Set the document's character encoding.
954 void SetDocumentCharacterSet(NotNull
<const Encoding
*> aEncoding
);
956 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource
; }
958 // This method MUST be called before SetDocumentCharacterSet if
959 // you're planning to call both.
960 void SetDocumentCharacterSetSource(int32_t aCharsetSource
) {
961 mCharacterSetSource
= aCharsetSource
;
965 * Get the Content-Type of this document.
967 void GetContentType(nsAString
& aContentType
);
970 * Set the Content-Type of this document.
972 void SetContentType(const nsACString
& aContentType
);
975 * Return the language of this document, or null if not set.
977 nsAtom
* GetContentLanguage() const { return mContentLanguage
.get(); }
979 void GetContentLanguageForBindings(DOMString
&) const;
981 // The states BidiEnabled and MathMLEnabled should persist across multiple
982 // views (screen, print) of the same document.
985 * Check if the document contains bidi data.
986 * If so, we have to apply the Unicode Bidi Algorithm.
988 bool GetBidiEnabled() const { return mBidiEnabled
; }
991 * Indicate the document contains bidi data.
992 * Currently, we cannot disable bidi, because once bidi is enabled,
993 * it affects a frame model irreversibly, and plays even though
994 * the document no longer contains bidi data.
996 void SetBidiEnabled() { mBidiEnabled
= true; }
998 void SetMathMLEnabled() { mMathMLEnabled
= true; }
1001 * Ask this document whether it's the initial document in its window.
1003 bool IsInitialDocument() const { return mIsInitialDocumentInWindow
; }
1006 * Ask this document whether it has ever been a initial document in its
1009 bool IsEverInitialDocument() const { return mIsEverInitialDocumentInWindow
; }
1012 * Tell this document that it's the initial document in its window. See
1013 * comments on mIsInitialDocumentInWindow for when this should be called.
1015 void SetIsInitialDocument(bool aIsInitialDocument
);
1017 void SetLoadedAsData(bool aLoadedAsData
, bool aConsiderForMemoryReporting
);
1019 TimeStamp
GetLoadingOrRestoredFromBFCacheTimeStamp() const {
1020 return mLoadingOrRestoredFromBFCacheTimeStamp
;
1022 void SetLoadingOrRestoredFromBFCacheTimeStampToNow() {
1023 mLoadingOrRestoredFromBFCacheTimeStamp
= TimeStamp::Now();
1027 * Normally we assert if a runnable labeled with one DocGroup touches data
1028 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1029 * means that we can touch that document from any DocGroup without asserting.
1031 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches
= true; }
1034 * Get the bidi options for this document.
1035 * @see nsBidiUtils.h
1037 uint32_t GetBidiOptions() const { return mBidiOptions
; }
1040 * Set the bidi options for this document. This just sets the bits;
1041 * callers are expected to take action as needed if they want this
1042 * change to actually change anything immediately.
1043 * @see nsBidiUtils.h
1045 void SetBidiOptions(uint32_t aBidiOptions
) { mBidiOptions
= aBidiOptions
; }
1048 * Returns true if the document holds a CSP
1049 * delivered through an HTTP Header.
1051 bool GetHasCSPDeliveredThroughHeader() {
1052 return mHasCSPDeliveredThroughHeader
;
1056 * Return a promise which resolves to the content blocking events.
1058 using GetContentBlockingEventsPromise
= MozPromise
<uint32_t, bool, true>;
1059 [[nodiscard
]] RefPtr
<GetContentBlockingEventsPromise
>
1060 GetContentBlockingEvents();
1063 * Get the sandbox flags for this document.
1064 * @see nsSandboxFlags.h for the possible flags
1066 uint32_t GetSandboxFlags() const { return mSandboxFlags
; }
1068 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> GetEmbedderPolicy() const {
1069 return mEmbedderPolicy
;
1072 void SetEmbedderPolicy(
1073 const Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
>& aCOEP
) {
1074 mEmbedderPolicy
= aCOEP
;
1078 * Get string representation of sandbox flags (null if no flags are set)
1080 void GetSandboxFlagsAsString(nsAString
& aFlags
);
1083 * Set the sandbox flags for this document.
1084 * @see nsSandboxFlags.h for the possible flags
1086 void SetSandboxFlags(uint32_t sandboxFlags
) { mSandboxFlags
= sandboxFlags
; }
1089 * Called when the document was decoded as UTF-8 and decoder encountered no
1092 void EnableEncodingMenu() { mEncodingMenuDisabled
= false; }
1095 * Called to disable client access to cookies through the document.cookie API
1096 * from user JavaScript code.
1098 void DisableCookieAccess() { mDisableCookieAccess
= true; }
1100 bool CookieAccessDisabled() const { return mDisableCookieAccess
; }
1102 void SetLinkHandlingEnabled(bool aValue
) { mLinksEnabled
= aValue
; }
1103 bool LinkHandlingEnabled() { return mLinksEnabled
; }
1106 * Set compatibility mode for this document
1108 void SetCompatibilityMode(nsCompatibility aMode
);
1111 * Called to disable client access to document.write() API from user
1114 void SetDocWriteDisabled(bool aDisabled
) { mDisableDocWrite
= aDisabled
; }
1117 * Whether a document.write() call is in progress.
1119 bool IsWriting() const { return mWriteLevel
!= uint32_t(0); }
1122 * Access HTTP header data (this may also get set from other
1123 * sources, like HTML META tags).
1125 void GetHeaderData(nsAtom
* aHeaderField
, nsAString
& aData
) const;
1126 void SetHeaderData(nsAtom
* aheaderField
, const nsAString
& aData
);
1129 * Set Early Hint data, moves the arrays into the function, leaving the
1130 * passed variables empty
1132 void SetEarlyHints(nsTArray
<net::EarlyHintConnectArgs
>&& aEarlyHints
);
1133 const nsTArray
<net::EarlyHintConnectArgs
>& GetEarlyHints() const {
1138 * Create a new presentation shell that will use aContext for its
1139 * presentation context (presentation contexts <b>must not</b> be
1140 * shared among multiple presentation shells). The caller of this
1141 * method is responsible for calling BeginObservingDocument() on the
1142 * presshell if the presshell should observe document mutations.
1144 MOZ_CAN_RUN_SCRIPT already_AddRefed
<PresShell
> CreatePresShell(
1145 nsPresContext
* aContext
, nsViewManager
* aViewManager
);
1146 void DeletePresShell();
1148 PresShell
* GetPresShell() const {
1149 return GetBFCacheEntry() ? nullptr : mPresShell
;
1152 inline PresShell
* GetObservingPresShell() const;
1154 // Return whether the presshell for this document is safe to flush.
1155 bool IsSafeToFlush() const;
1157 inline nsPresContext
* GetPresContext() const;
1159 bool HasShellOrBFCacheEntry() const { return mPresShell
|| mBFCacheEntry
; }
1161 // Instead using this method, what you probably want is
1162 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1163 void DisallowBFCaching(uint32_t aStatus
= BFCacheStatus::NOT_ALLOWED
);
1165 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed
; }
1167 // Accepts null to clear the BFCache entry too.
1168 void SetBFCacheEntry(nsIBFCacheEntry
* aEntry
);
1170 nsIBFCacheEntry
* GetBFCacheEntry() const { return mBFCacheEntry
; }
1172 // Removes this document from the BFCache, if it is cached, and returns
1174 bool RemoveFromBFCacheSync();
1177 * Return the parent document of this document. Will return null
1178 * unless this document is within a compound document and has a
1179 * parent. Note that this parent chain may cross chrome boundaries.
1181 Document
* GetInProcessParentDocument() const { return mParentDocument
; }
1184 * Set the parent document of this document.
1186 void SetParentDocument(Document
* aParent
) {
1187 mParentDocument
= aParent
;
1189 RecomputeResistFingerprinting();
1190 mIgnoreDocGroupMismatches
= aParent
->mIgnoreDocGroupMismatches
;
1194 void SetCurrentContextPaint(const SVGContextPaint
* aContextPaint
) {
1195 mCurrentContextPaint
= aContextPaint
;
1198 const SVGContextPaint
* GetCurrentContextPaint() const {
1199 return mCurrentContextPaint
;
1203 * Set the sub document for aContent to aSubDoc.
1205 nsresult
SetSubDocumentFor(Element
* aContent
, Document
* aSubDoc
);
1208 * Get the sub document for aContent
1210 Document
* GetSubDocumentFor(nsIContent
* aContent
) const;
1213 * Get the content node for which this document is a sub document.
1215 Element
* GetEmbedderElement() const;
1218 * Return the doctype for this document.
1220 DocumentType
* GetDoctype() const;
1223 * Return the root element for this document.
1225 Element
* GetRootElement() const;
1227 Selection
* GetSelection(ErrorResult
& aRv
);
1229 void MakeBrowsingContextNonSynthetic();
1230 nsresult
HasStorageAccessSync(bool& aHasStorageAccess
);
1231 already_AddRefed
<Promise
> HasStorageAccess(ErrorResult
& aRv
);
1233 StorageAccessAPIHelper::PerformPermissionGrant
CreatePermissionGrantPromise(
1234 nsPIDOMWindowInner
* aInnerWindow
, nsIPrincipal
* aPrincipal
,
1235 bool aHasUserInteraction
, bool aRequireUserInteraction
,
1236 const Maybe
<nsCString
>& aTopLevelBaseDomain
, bool aFrameOnly
);
1238 already_AddRefed
<Promise
> RequestStorageAccess(ErrorResult
& aRv
);
1240 already_AddRefed
<Promise
> RequestStorageAccessForOrigin(
1241 const nsAString
& aThirdPartyOrigin
, const bool aRequireUserInteraction
,
1244 already_AddRefed
<Promise
> RequestStorageAccessUnderSite(
1245 const nsAString
& aSerializedSite
, ErrorResult
& aRv
);
1246 already_AddRefed
<Promise
> CompleteStorageAccessRequestFromSite(
1247 const nsAString
& aSerializedOrigin
, ErrorResult
& aRv
);
1249 bool UseRegularPrincipal() const;
1252 * Gets the event target to dispatch key events to if there is no focused
1253 * content in the document.
1255 virtual Element
* GetUnfocusedKeyEventTarget();
1258 * Retrieve information about the viewport as a data structure.
1259 * This will return information in the viewport META data section
1260 * of the document. This can be used in lieu of ProcessViewportInfo(),
1261 * which places the viewport information in the document header instead
1262 * of returning it directly.
1264 * @param aDisplaySize size of the on-screen display area for this
1265 * document, in device pixels.
1267 * NOTE: If the site is optimized for mobile (via the doctype), this
1268 * will return viewport information that specifies default information.
1270 nsViewportInfo
GetViewportInfo(const ScreenIntSize
& aDisplaySize
);
1272 void SetMetaViewportData(UniquePtr
<ViewportMetaData
> aData
);
1274 // Returns a ViewportMetaData for this document.
1275 ViewportMetaData
GetViewportMetaData() const;
1278 * True iff this doc will ignore manual character encoding overrides.
1280 virtual bool WillIgnoreCharsetOverride() { return true; }
1283 * Return whether the document was created by a srcdoc iframe.
1285 bool IsSrcdocDocument() const { return mIsSrcdocDocument
; }
1288 * Sets whether the document was created by a srcdoc iframe.
1290 void SetIsSrcdocDocument(bool aIsSrcdocDocument
) {
1291 mIsSrcdocDocument
= aIsSrcdocDocument
;
1295 * Gets the srcdoc string from within the channel (assuming both exist).
1296 * Returns a void string if this isn't a srcdoc document or if
1297 * the channel has not been set.
1299 nsresult
GetSrcdocData(nsAString
& aSrcdocData
);
1301 already_AddRefed
<AnonymousContent
> InsertAnonymousContent(bool aForce
,
1303 void RemoveAnonymousContent(AnonymousContent
&);
1305 * If aNode is a descendant of anonymous content inserted by
1306 * InsertAnonymousContent, this method returns the root element of the
1307 * inserted anonymous content (in other words, the clone of the aElement
1308 * that was passed to InsertAnonymousContent).
1310 Element
* GetAnonRootIfInAnonymousContentContainer(nsINode
* aNode
) const;
1311 nsTArray
<RefPtr
<AnonymousContent
>>& GetAnonymousContents() {
1312 return mAnonymousContents
;
1315 TimeStamp
GetPageUnloadingEventTimeStamp() const {
1316 if (!mParentDocument
) {
1317 return mPageUnloadingEventTimeStamp
;
1320 TimeStamp
parentTimeStamp(
1321 mParentDocument
->GetPageUnloadingEventTimeStamp());
1322 if (parentTimeStamp
.IsNull()) {
1323 return mPageUnloadingEventTimeStamp
;
1326 if (!mPageUnloadingEventTimeStamp
||
1327 parentTimeStamp
< mPageUnloadingEventTimeStamp
) {
1328 return parentTimeStamp
;
1331 return mPageUnloadingEventTimeStamp
;
1334 void NotifyLayerManagerRecreated();
1336 // Add an element to the list of elements that need their mapped attributes
1337 // resolved to a declaration block.
1339 // These are weak pointers, manually unschedule them when an element is
1340 // removed from the tree.
1341 void ScheduleForPresAttrEvaluation(Element
* aElement
);
1343 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1344 // generally when it's unbound from the tree.
1345 void UnscheduleForPresAttrEvaluation(Element
* aElement
);
1347 // Resolve all presentational attributes scheduled in
1348 // ScheduleForPresAttrEvaluation
1349 void ResolveScheduledPresAttrs() {
1350 if (mLazyPresElements
.IsEmpty()) {
1353 DoResolveScheduledPresAttrs();
1356 Maybe
<ClientInfo
> GetClientInfo() const;
1357 Maybe
<ClientState
> GetClientState() const;
1358 Maybe
<ServiceWorkerDescriptor
> GetController() const;
1360 // Given a node, get a weak reference to it and append that reference to
1361 // mBlockedNodesByClassifier. Can be used later on to look up a node in it.
1362 // (e.g., by the UI)
1364 void AddBlockedNodeByClassifier(nsINode
* aNode
) {
1366 mBlockedNodesByClassifier
.AppendElement(do_GetWeakReference(aNode
));
1370 // Returns the size of the mBlockedNodesByClassifier array.
1372 // This array contains nodes that have been blocked to prevent user tracking,
1373 // fingerprinting, cryptomining, etc. They most likely have had their
1374 // nsIChannel canceled by the URL classifier (Safebrowsing).
1376 // A script can subsequently use GetBlockedNodesByClassifier()
1377 // to get a list of references to these nodes.
1380 // This expresses how many tracking nodes have been blocked for this document
1381 // since its beginning, not how many of them are still around in the DOM tree.
1382 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1383 // array but they are not removed when those nodes are removed from the tree
1384 // or even garbage collected.
1385 size_t BlockedNodeByClassifierCount() const {
1386 return mBlockedNodesByClassifier
.Length();
1389 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1390 // This array contains nodes that have been blocked to prevent
1391 // user tracking. They most likely have had their nsIChannel
1392 // canceled by the URL classifier (Safebrowsing).
1393 already_AddRefed
<nsSimpleContentList
> BlockedNodesByClassifier() const;
1395 // Helper method that returns true if the document has storage-access sandbox
1397 bool StorageAccessSandboxed() const;
1399 // Helper method that returns true if storage access API is enabled and
1400 // the passed flag has storage-access sandbox flag.
1401 static bool StorageAccessSandboxed(uint32_t aSandboxFlags
);
1403 // Returns the cookie jar settings for this and sub contexts.
1404 nsICookieJarSettings
* CookieJarSettings();
1406 // Returns whether this document is using unpartitioned cookies
1407 bool UsingStorageAccess();
1409 // Returns whether the document is on the 3PCB exception list.
1410 bool IsOn3PCBExceptionList() const;
1412 // Returns whether the storage access permission of the document is granted by
1414 bool HasStorageAccessPermissionGrantedByAllowList();
1416 // Increments the document generation.
1417 inline void Changed() { ++mGeneration
; }
1419 // Returns the current generation.
1420 inline int32_t GetGeneration() const { return mGeneration
; }
1422 // Adds cached sizes values to aSizes if there's any
1423 // cached value and if the document generation hasn't
1424 // changed since the cache was created.
1425 // Returns true if sizes were added.
1426 bool GetCachedSizes(nsTabSizes
* aSizes
);
1428 // Sets the cache sizes for the current generation.
1429 void SetCachedSizes(nsTabSizes
* aSizes
);
1432 * Should be called when an element's editable changes as a result of
1433 * changing its contentEditable attribute/property.
1435 * The change should be +1 if the contentEditable attribute/property was
1436 * changed to true, -1 if it was changed to false.
1438 void ChangeContentEditableCount(Element
*, int32_t aChange
);
1439 MOZ_CAN_RUN_SCRIPT
void DeferredContentEditableCountChange(Element
*);
1441 enum class EditingState
: int8_t {
1450 * Returns the editing state of the document (not editable, contentEditable or
1453 EditingState
GetEditingState() const { return mEditingState
; }
1456 * Returns whether the document is editable.
1458 bool IsEditingOn() const {
1459 return GetEditingState() == EditingState::eDesignMode
||
1460 GetEditingState() == EditingState::eContentEditable
;
1463 class MOZ_STACK_CLASS nsAutoEditingState
{
1465 nsAutoEditingState(Document
* aDoc
, EditingState aState
)
1466 : mDoc(aDoc
), mSavedState(aDoc
->mEditingState
) {
1467 aDoc
->mEditingState
= aState
;
1469 ~nsAutoEditingState() { mDoc
->mEditingState
= mSavedState
; }
1472 RefPtr
<Document
> mDoc
;
1473 EditingState mSavedState
;
1475 friend class nsAutoEditingState
;
1478 * Set the editing state of the document. Don't use this if you want
1479 * to enable/disable editing, call EditingStateChanged() or
1482 void SetEditingState(EditingState aState
) { mEditingState
= aState
; }
1485 * Called when this Document's editor is destroyed.
1487 void TearingDownEditor();
1489 void SetKeyPressEventModel(uint16_t aKeyPressEventModel
);
1491 // Gets the next form number.
1493 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1494 // parser inserted form element.
1495 int32_t GetNextFormNumber() { return mNextFormNumber
++; }
1497 // Gets the next form control number.
1499 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1500 // parser inserted form control element.
1501 int32_t GetNextControlNumber() { return mNextControlNumber
++; }
1503 PreloadService
& Preloads() { return mPreloadService
; }
1505 bool HasThirdPartyChannel();
1507 bool ShouldIncludeInTelemetry() const;
1509 void AddMediaElementWithMSE();
1510 void RemoveMediaElementWithMSE();
1512 void DoNotifyPossibleTitleChange();
1514 void InitFeaturePolicy(const Variant
<Nothing
, FeaturePolicyInfo
, Element
*>&
1515 aContainerFeaturePolicy
);
1516 nsresult
InitFeaturePolicy(nsIChannel
* aChannel
);
1518 void EnsureNotEnteringAndExitFullscreen();
1521 friend class nsUnblockOnloadEvent
;
1523 nsresult
InitCSP(nsIChannel
* aChannel
);
1524 nsresult
InitCOEP(nsIChannel
* aChannel
);
1525 nsresult
InitDocPolicy(nsIChannel
* aChannel
);
1527 nsresult
InitReferrerInfo(nsIChannel
* aChannel
);
1529 void PostUnblockOnloadEvent();
1531 void DoUnblockOnload();
1533 void DoResolveScheduledPresAttrs();
1535 void RetrieveRelevantHeaders(nsIChannel
* aChannel
);
1537 void TryChannelCharset(nsIChannel
* aChannel
, int32_t& aCharsetSource
,
1538 NotNull
<const Encoding
*>& aEncoding
,
1539 nsHtml5TreeOpExecutor
* aExecutor
);
1541 MOZ_CAN_RUN_SCRIPT
void DispatchContentLoadedEvents();
1543 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1544 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void DispatchPageTransition(
1545 EventTarget
* aDispatchTarget
, const nsAString
& aType
, bool aInFrameSwap
,
1546 bool aPersisted
, bool aOnlySystemGroup
);
1548 // Call this before the document does something that will unbind all content.
1549 // That will stop us from doing a lot of work as each element is removed.
1550 void DestroyElementMaps();
1552 Element
* GetRootElementInternal() const;
1554 void SetPageUnloadingEventTimeStamp() {
1555 MOZ_ASSERT(!mPageUnloadingEventTimeStamp
);
1556 mPageUnloadingEventTimeStamp
= TimeStamp::NowLoRes();
1559 void CleanUnloadEventsTimeStamp() {
1560 MOZ_ASSERT(mPageUnloadingEventTimeStamp
);
1561 mPageUnloadingEventTimeStamp
= TimeStamp();
1565 * Clears any Servo element data stored on Elements in the document.
1567 void ClearStaleServoData();
1570 * Do the tree-disconnection that ResetToURI and document.open need to do.
1572 void DisconnectNodeTree();
1575 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1576 * "CheckKeyPressEventModel" event to check whether we should dispatch
1577 * keypress events in confluent model or split model. This should be
1578 * called only when mEditingState is changed to eDesignMode or
1579 * eConentEditable at first time.
1581 void MaybeDispatchCheckKeyPressEventModelEvent();
1583 /* Midas implementation */
1584 nsCommandManager
* GetMidasCommandManager();
1586 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
TurnEditingOff();
1588 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1589 // of places, and I'm pretty sure the exact ExecCommand call it
1590 // makes cannot actually run script.
1591 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult
EditingStateChanged();
1593 void MaybeEditingStateChanged();
1596 // Get the root <html> element, or return null if there isn't one (e.g.
1597 // if the root isn't <html>)
1598 Element
* GetHtmlElement() const;
1599 // Returns the first child of GetHtmlContent which has the given tag and is
1600 // not aContentToIgnore, or nullptr if that doesn't exist.
1601 Element
* GetHtmlChildElement(
1602 nsAtom
* aTag
, const nsIContent
* aContentToIgnore
= nullptr) const;
1603 // Get the canonical <body> element, or return null if there isn't one (e.g.
1604 // if the root isn't <html> or if the <body> isn't there)
1605 HTMLBodyElement
* GetBodyElement(
1606 const nsIContent
* aContentToIgnore
= nullptr) const;
1607 // Get the canonical <head> element, or return null if there isn't one (e.g.
1608 // if the root isn't <html> or if the <head> isn't there)
1609 Element
* GetHeadElement() const {
1610 return GetHtmlChildElement(nsGkAtoms::head
);
1612 // Get the "body" in the sense of document.body: The first <body> or
1613 // <frameset> that's a child of a root <html>
1614 nsGenericHTMLElement
* GetBody() const;
1615 // Set the "body" in the sense of document.body.
1616 void SetBody(nsGenericHTMLElement
* aBody
, ErrorResult
& rv
);
1617 // Get the "head" element in the sense of document.head.
1618 HTMLSharedElement
* GetHead() const;
1620 ServoStyleSet
* StyleSetForPresShell() const {
1621 MOZ_ASSERT(!!mStyleSet
.get());
1622 return mStyleSet
.get();
1625 inline ServoStyleSet
& EnsureStyleSet() const;
1627 // ShadowRoot has APIs that can change styles. This notifies the shell that
1628 // stlyes applicable in the shadow tree have potentially changed.
1629 void RecordShadowStyleChange(ShadowRoot
&);
1631 // Needs to be called any time the applicable style can has changed, in order
1632 // to schedule a style flush and setup all the relevant state.
1634 // If we know the stylesheet change applies only to a shadow tree we can avoid
1635 // some work (like updating the font-face-set / counter-styles / etc, as those
1637 void ApplicableStylesChanged(bool aKnownInShadowTree
= false);
1639 // Whether we filled the style set with any style sheet. Only meant to be used
1640 // from DocumentOrShadowRoot::Traverse.
1641 bool StyleSetFilled() const { return mStyleSetFilled
; }
1644 * Accessors to the collection of stylesheets owned by this document.
1645 * Style sheets are ordered, most significant last.
1648 void InsertSheetAt(size_t aIndex
, StyleSheet
&);
1651 * Add a stylesheet to the document
1653 * TODO(emilio): This is only used by parts of editor that are no longer in
1654 * use by m-c or c-c, so remove.
1656 void AddStyleSheet(StyleSheet
* aSheet
) {
1658 InsertSheetAt(SheetCount(), *aSheet
);
1662 * Notify the document that the applicable state of the sheet changed
1663 * and that observers should be notified and style sets updated
1665 void StyleSheetApplicableStateChanged(StyleSheet
&);
1666 void PostStyleSheetApplicableStateChangeEvent(StyleSheet
&);
1667 void PostStyleSheetRemovedEvent(StyleSheet
&);
1668 void PostCustomPropertyRegistered(const dom::PropertyDefinition
&);
1670 enum additionalSheetType
{
1674 AdditionalSheetTypeCount
1677 nsresult
LoadAdditionalStyleSheet(additionalSheetType aType
,
1679 nsresult
AddAdditionalStyleSheet(additionalSheetType aType
,
1680 StyleSheet
* aSheet
);
1681 void RemoveAdditionalStyleSheet(additionalSheetType aType
, nsIURI
* sheetURI
);
1683 StyleSheet
* GetFirstAdditionalAuthorSheet() {
1684 return mAdditionalSheets
[eAuthorSheet
].SafeElementAt(0);
1688 * Returns the index that aSheet should be inserted at to maintain document
1691 size_t FindDocStyleSheetInsertionPoint(const StyleSheet
& aSheet
);
1694 * Get this document's CSSLoader. This is guaranteed to not return null.
1696 css::Loader
* CSSLoader() const { return mCSSLoader
; }
1699 * Get this document's StyleImageLoader. This is guaranteed to not return
1702 css::ImageLoader
* StyleImageLoader() const { return mStyleImageLoader
; }
1705 * Get the channel that was passed to StartDocumentLoad or Reset for this
1706 * document. Note that this may be null in some cases (eg if
1707 * StartDocumentLoad or Reset were never called)
1709 nsIChannel
* GetChannel() const { return mChannel
; }
1712 * Get this document's attribute stylesheet. May return null if
1715 AttributeStyles
* GetAttributeStyles() const { return mAttributeStyles
.get(); }
1717 virtual void SetScriptGlobalObject(nsIScriptGlobalObject
* aGlobalObject
);
1720 * Get/set the object from which the context for the event/script handling can
1721 * be got. Normally GetScriptHandlingObject() returns the same object as
1722 * GetScriptGlobalObject(), but if the document is loaded as data,
1723 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1724 * aHasHadScriptHandlingObject is set true if document has had the object
1725 * for event/script handling. Do not process any events/script if the method
1726 * returns null, but aHasHadScriptHandlingObject is true.
1728 nsIScriptGlobalObject
* GetScriptHandlingObject(
1729 bool& aHasHadScriptHandlingObject
) const {
1730 aHasHadScriptHandlingObject
= mHasHadScriptHandlingObject
;
1731 return mScriptGlobalObject
? mScriptGlobalObject
.get()
1732 : GetScriptHandlingObjectInternal();
1734 void SetScriptHandlingObject(nsIScriptGlobalObject
* aScriptObject
);
1737 * Get the object that is used as the scope for all of the content
1738 * wrappers whose owner document is this document. Unlike the script global
1739 * object, this will only return null when the global object for this
1740 * document is truly gone. Use this object when you're trying to find a
1741 * content wrapper in XPConnect.
1743 nsIGlobalObject
* GetScopeObject() const;
1744 void SetScopeObject(nsIGlobalObject
* aGlobal
);
1747 * Return the window containing the document (the outer window).
1749 nsPIDOMWindowOuter
* GetWindow() const {
1750 return mWindow
? mWindow
->GetOuterWindow() : GetWindowInternal();
1753 bool IsInBackgroundWindow() const {
1754 auto* outer
= mWindow
? mWindow
->GetOuterWindow() : nullptr;
1755 return outer
&& outer
->IsBackground();
1759 * Return the inner window used as the script compilation scope for
1760 * this document. If you're not absolutely sure you need this, use
1763 nsPIDOMWindowInner
* GetInnerWindow() const {
1764 return mRemovedFromDocShell
? nullptr : mWindow
;
1768 * Return the outer window ID.
1770 uint64_t OuterWindowID() const {
1771 nsPIDOMWindowOuter
* window
= GetWindow();
1772 return window
? window
->WindowID() : 0;
1776 * Return the inner window ID.
1778 uint64_t InnerWindowID() const {
1779 nsPIDOMWindowInner
* window
= GetInnerWindow();
1780 return window
? window
->WindowID() : 0;
1784 * Return WindowGlobalChild that is associated with the inner window.
1786 WindowGlobalChild
* GetWindowGlobalChild() {
1787 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1792 * Return WindowContext associated with the inner window.
1794 WindowContext
* GetWindowContext() const {
1795 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1798 bool IsTopLevelWindowInactive() const {
1799 return mState
.HasState(DocumentState::WINDOW_INACTIVE
);
1803 * Get the script loader for this document
1805 dom::ScriptLoader
* ScriptLoader() { return mScriptLoader
; }
1808 * Add/Remove an element to the document's id and name hashes
1810 void AddToIdTable(Element
* aElement
, nsAtom
* aId
);
1811 void RemoveFromIdTable(Element
* aElement
, nsAtom
* aId
);
1812 void AddToNameTable(Element
* aElement
, nsAtom
* aName
);
1813 void RemoveFromNameTable(Element
* aElement
, nsAtom
* aName
);
1816 * Returns all elements in the top layer in the insertion order.
1818 nsTArray
<Element
*> GetTopLayer() const;
1820 bool TopLayerContains(Element
&) const;
1822 // Do the "fullscreen element ready check" from the fullscreen spec.
1823 // It returns true if the given element is allowed to go into fullscreen.
1824 // It is responsive to dispatch "fullscreenerror" event when necessary.
1825 bool FullscreenElementReadyCheck(FullscreenRequest
&);
1828 * When this is called on content process, this asynchronously requests that
1829 * the document make aElement the fullscreen element, and move into fullscreen
1830 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1831 * and it can be returned to fullscreen status by calling
1832 * RestorePreviousFullscreenState().
1833 * If on chrome process, this is synchronously.
1835 * Note that requesting fullscreen in a document also makes the element which
1836 * contains this document in this document's parent document fullscreen. i.e.
1837 * the <iframe> or <browser> that contains this document is also mode
1838 * fullscreen. This happens recursively in all ancestor documents.
1840 void RequestFullscreen(UniquePtr
<FullscreenRequest
> aRequest
,
1841 bool aApplyFullscreenDirectly
= false);
1844 void RequestFullscreenInContentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1845 bool aApplyFullscreenDirectly
);
1846 void RequestFullscreenInParentProcess(UniquePtr
<FullscreenRequest
> aRequest
,
1847 bool aApplyFullscreenDirectly
);
1849 // Pushes aElement onto the top layer
1850 void TopLayerPush(Element
&);
1852 // Removes the topmost element for which aPredicate returns true from the top
1853 // layer. The removed element, if any, is returned.
1854 Element
* TopLayerPop(FunctionRef
<bool(Element
*)> aPredicate
);
1856 // Removes the given element from the top layer. The removed element, if any,
1858 Element
* TopLayerPop(Element
&);
1860 MOZ_CAN_RUN_SCRIPT
bool TryAutoFocusCandidate(Element
& aElement
);
1863 // Removes all the elements with fullscreen flag set from the top layer, and
1864 // clears their fullscreen flag.
1865 void CleanupFullscreenState();
1867 // Pops the fullscreen element from the top layer and clears its
1868 // fullscreen flag. Returns whether there was any fullscreen element.
1869 enum class UpdateViewport
: bool { No
, Yes
};
1870 bool PopFullscreenElement(UpdateViewport
= UpdateViewport::Yes
);
1872 // Pushes the given element into the top of top layer and set fullscreen
1874 void SetFullscreenElement(Element
&);
1876 // Whether we has pending fullscreen request.
1877 bool HasPendingFullscreenRequests();
1880 * When Esc key is pressed, cancel the dialog element if the document is
1881 * blocked by the dialog or hide popover if popover is shown.
1883 MOZ_CAN_RUN_SCRIPT
void HandleEscKey();
1886 * Process any active CloseWatchers in the document, such
1887 * as fullscreen elements, popovers, dialogs.
1889 MOZ_CAN_RUN_SCRIPT
void ProcessCloseRequest();
1891 void AddModalDialog(HTMLDialogElement
&);
1892 void RemoveModalDialog(HTMLDialogElement
&);
1895 * Called when a frame in a child process has entered fullscreen or when a
1896 * fullscreen frame in a child process changes to another origin.
1897 * aFrameElement is the frame element which contains the child-process
1898 * fullscreen document.
1900 void RemoteFrameFullscreenChanged(Element
* aFrameElement
);
1903 * Called when a frame in a remote child document has rolled back fullscreen
1904 * so that all its top layer are empty; we must continue the
1905 * rollback in this parent process' doc tree branch which is fullscreen.
1906 * Note that only one branch of the document tree can have its documents in
1907 * fullscreen state at one time. We're in inconsistent state if a
1908 * fullscreen document has a parent and that parent isn't fullscreen. We
1909 * preserve this property across process boundaries.
1911 void RemoteFrameFullscreenReverted();
1914 * Restores the previous fullscreen element to fullscreen status. If there
1915 * is no former fullscreen element, this exits fullscreen, moving the
1916 * top-level browser window out of fullscreen mode.
1918 void RestorePreviousFullscreenState(UniquePtr
<FullscreenExit
>);
1921 * Returns true if this document is a fullscreen leaf document, i.e. it
1922 * is in fullscreen mode and has no fullscreen children.
1924 bool IsFullscreenLeaf();
1927 * Returns the document which is at the root of this document's branch
1928 * in the in-process document tree. Returns nullptr if the document isn't
1931 Document
* GetFullscreenRoot() const { return mFullscreenRoot
; }
1933 size_t CountFullscreenElements() const;
1936 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1939 void SetFullscreenRoot(Document
* aRoot
) { mFullscreenRoot
= aRoot
; }
1942 * Synchronously cleans up the fullscreen state on the given document.
1944 * Calling this without performing fullscreen transition could lead
1945 * to undesired effect (the transition happens after document state
1946 * flips), hence it should only be called either by nsGlobalWindow
1947 * when we have performed the transition, or when it is necessary to
1948 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1949 * should be called instead.
1951 * aDocument must not be null.
1953 static void ExitFullscreenInDocTree(Document
* aDocument
);
1956 * Ask the document to exit fullscreen state asynchronously.
1958 * Different from ExitFullscreenInDocTree(), this allows the window
1959 * to perform fullscreen transition first if any.
1961 * If aDocument is null, it will exit fullscreen from all documents
1964 static void AsyncExitFullscreen(Document
* aDocument
);
1967 * Handles any pending fullscreen in aDocument or its subdocuments.
1969 * Returns whether there is any fullscreen request handled.
1971 static bool HandlePendingFullscreenRequests(Document
* aDocument
);
1974 * Clear pending fullscreen in aDocument.
1976 static void ClearPendingFullscreenRequests(Document
* aDocument
);
1978 // ScreenOrientation related APIs
1980 void ClearOrientationPendingPromise();
1981 bool SetOrientationPendingPromise(Promise
* aPromise
);
1982 Promise
* GetOrientationPendingPromise() const {
1983 return mOrientationPendingPromise
;
1986 //----------------------------------------------------------------------
1988 // Document notification API's
1991 * Add a new observer of document change notifications. Whenever
1992 * content is changed, appended, inserted or removed the observers are
1993 * informed. An observer that is already observing the document must
1994 * not be added without being removed first.
1996 void AddObserver(nsIDocumentObserver
* aObserver
);
1999 * Remove an observer of document change notifications. This will
2000 * return false if the observer cannot be found.
2002 bool RemoveObserver(nsIDocumentObserver
* aObserver
);
2004 // Observation hooks used to propagate notifications to document observers.
2005 // BeginUpdate must be called before any batch of modifications of the
2006 // content model or of style data, EndUpdate must be called afterward.
2007 // To make this easy and painless, use the mozAutoDocUpdate helper class.
2010 uint32_t UpdateNestingLevel() { return mUpdateNestLevel
; }
2013 virtual void EndLoad();
2016 READYSTATE_UNINITIALIZED
= 0,
2017 READYSTATE_LOADING
= 1,
2018 READYSTATE_INTERACTIVE
= 3,
2019 READYSTATE_COMPLETE
= 4
2021 // Set the readystate of the document. If aUpdateTimingInformation is true,
2022 // this will record relevant timestamps in the document's performance timing.
2023 // Some consumers (document.open is the only one right now, actually) don't
2024 // want to do that, though.
2025 void SetReadyStateInternal(ReadyState
, bool aUpdateTimingInformation
= true);
2026 ReadyState
GetReadyStateEnum() { return mReadyState
; }
2028 void NotifyLoading(bool aNewParentIsLoading
, const ReadyState
& aCurrentState
,
2029 ReadyState aNewState
);
2031 void NotifyAbortedLoad();
2033 // Notify that an element changed state. This must happen under a
2034 // scriptblocker but NOT within a begin/end update.
2035 void ElementStateChanged(Element
*, ElementState
);
2037 // Update a set of document states that may have changed.
2038 // This should only be called by callers whose state is also reflected in the
2039 // implementation of Document::State.
2041 // aNotify controls whether we notify our DocumentStatesChanged observers.
2042 void UpdateDocumentStates(DocumentState aMaybeChangedStates
, bool aNotify
);
2044 void ResetDocumentDirection();
2046 // Observation hooks for style data to propagate notifications
2047 // to document observers
2048 void RuleChanged(StyleSheet
&, css::Rule
*, const StyleRuleChange
&);
2049 void RuleAdded(StyleSheet
&, css::Rule
&);
2050 void RuleRemoved(StyleSheet
&, css::Rule
&);
2051 void SheetCloned(StyleSheet
&) {}
2052 void ImportRuleLoaded(StyleSheet
&);
2055 * Flush notifications for this document and its parent documents
2056 * (since those may affect the layout of this one).
2058 void FlushPendingNotifications(FlushType aType
);
2061 * Another variant of the above FlushPendingNotifications. This function
2062 * takes a ChangesToFlush to specify whether throttled animations are flushed
2064 * If in doubt, use the above FlushPendingNotifications.
2066 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2067 void FlushPendingNotifications(ChangesToFlush aFlush
);
2070 * Calls FlushPendingNotifications on any external resources this document
2071 * has. If this document has no external resources or is an external resource
2072 * itself this does nothing. This should only be called with
2073 * aType >= FlushType::Style.
2075 void FlushExternalResources(FlushType aType
);
2077 void AddWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2078 void RemoveWorkerDocumentListener(WorkerDocumentListener
* aListener
);
2080 // Triggers an update of <svg:use> element shadow trees.
2081 void UpdateSVGUseElementShadowTrees() {
2082 if (mSVGUseElementsNeedingShadowTreeUpdate
.IsEmpty()) {
2085 DoUpdateSVGUseElementShadowTrees();
2089 * Only to be used inside Gecko, you can't really do anything with the
2090 * pointer outside Gecko anyway.
2092 nsNodeInfoManager
* NodeInfoManager() const { return mNodeInfoManager
; }
2095 * Reset the document using the given channel and loadgroup. This works
2096 * like ResetToURI, but also sets the document's channel to aChannel.
2097 * The principal of the document will be set from the channel.
2099 virtual void Reset(nsIChannel
* aChannel
, nsILoadGroup
* aLoadGroup
);
2102 * Reset this document to aURI, aLoadGroup, aPrincipal and
2103 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2104 * content principal based on aURI will be used.
2106 virtual void ResetToURI(nsIURI
* aURI
, nsILoadGroup
* aLoadGroup
,
2107 nsIPrincipal
* aPrincipal
,
2108 nsIPrincipal
* aPartitionedPrincipal
);
2111 * Set the container (docshell) for this document. Virtual so that
2112 * docshell can call it.
2114 virtual void SetContainer(nsDocShell
* aContainer
);
2117 * Get the container (docshell) for this document.
2119 nsISupports
* GetContainer() const;
2122 * Get the container's load context for this document.
2124 nsILoadContext
* GetLoadContext() const;
2127 * Get docshell the for this document.
2129 nsIDocShell
* GetDocShell() const;
2132 * Set and get XML declaration. If aVersion is null there is no declaration.
2133 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2134 * was no standalone parameter in the declaration, that it was given as no,
2135 * or that it was given as yes.
2137 void SetXMLDeclaration(const char16_t
* aVersion
, const char16_t
* aEncoding
,
2138 const int32_t aStandalone
);
2139 void GetXMLDeclaration(nsAString
& aVersion
, nsAString
& aEncoding
,
2140 nsAString
& Standalone
);
2143 * Returns the bits for the color-scheme specified by the
2144 * <meta name="color-scheme">.
2146 uint8_t GetColorSchemeBits() const { return mColorSchemeBits
; }
2149 * Traverses the DOM and computes the supported color schemes as per
2150 * https://html.spec.whatwg.org/#meta-color-scheme
2152 void RecomputeColorScheme();
2153 void AddColorSchemeMeta(HTMLMetaElement
&);
2154 void RemoveColorSchemeMeta(HTMLMetaElement
&);
2157 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2158 * regular HTML document with Content-Type "text/html", image documents and
2159 * media documents). Returns false for XHTML and any other documents parsed
2160 * by the XML parser.
2162 bool IsHTMLDocument() const { return mType
== eHTML
; }
2163 bool IsHTMLOrXHTML() const { return mType
== eHTML
|| mType
== eXHTML
; }
2164 bool IsImageDocument() const {
2165 return MediaDocumentKind() == MediaDocumentKind::Image
;
2167 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2168 bool IsSVGDocument() const { return mType
== eSVG
; }
2169 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2170 bool LoadsFullXULStyleSheetUpFront() {
2171 if (IsSVGDocument()) {
2174 return AllowXULXBL();
2177 bool IsScriptEnabled() const;
2180 * Returns true if this document was created from a nsXULPrototypeDocument.
2182 bool LoadedFromPrototype() const { return mPrototypeDocument
; }
2184 * Returns the prototype the document was created from, or null if it was not
2185 * created from a prototype.
2187 nsXULPrototypeDocument
* GetPrototype() const { return mPrototypeDocument
; }
2189 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument
; }
2190 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument
) {
2191 mIsTopLevelContentDocument
= aIsTopLevelContentDocument
;
2194 bool IsContentDocument() const { return mIsContentDocument
; }
2195 void SetIsContentDocument(bool aIsContentDocument
) {
2196 mIsContentDocument
= aIsContentDocument
;
2199 void ProcessMETATag(HTMLMetaElement
* aMetaElement
);
2201 * Create an element with the specified name, prefix and namespace ID.
2202 * Returns null if element name parsing failed.
2204 already_AddRefed
<Element
> CreateElem(const nsAString
& aName
, nsAtom
* aPrefix
,
2205 int32_t aNamespaceID
,
2206 const nsAString
* aIs
= nullptr);
2209 * Get the security info (i.e. SSL state etc) that the document got
2210 * from the channel/document that created the content of the
2215 nsITransportSecurityInfo
* GetSecurityInfo() { return mSecurityInfo
; }
2218 * Get the channel that failed to load and resulted in an error page, if it
2219 * exists. This is only relevant to error pages.
2221 nsIChannel
* GetFailedChannel() const { return mFailedChannel
; }
2224 * This function checks if the document that is trying to access
2225 * GetNetErrorInfo is a trusted about net error page or not.
2227 static bool CallerIsTrustedAboutNetError(JSContext
* aCx
, JSObject
* aObject
);
2230 * This function checks if the document that is trying to access
2231 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2233 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext
* aCx
,
2237 * Get security info like error code for a failed channel. This
2238 * property is only exposed to about:neterror documents.
2240 void GetNetErrorInfo(mozilla::dom::NetErrorInfo
& aInfo
, ErrorResult
& aRv
);
2243 * This function checks if the document that is trying to access
2244 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2246 static bool CallerIsTrustedAboutCertError(JSContext
* aCx
, JSObject
* aObject
);
2249 * This function checks if the privilege storage access api is available for
2250 * the caller. We only allow privilege SSA to be called by system principal
2251 * and webcompat extension.
2253 static bool CallerCanAccessPrivilegeSSA(JSContext
* aCx
, JSObject
* aObject
);
2256 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2257 * failed Channel. This property is only exposed for about:certerror
2260 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo
& aInfo
,
2264 * Set the channel that failed to load and resulted in an error page.
2265 * This is only relevant to error pages.
2267 void SetFailedChannel(nsIChannel
* aChannel
) { mFailedChannel
= aChannel
; }
2270 * Returns the default namespace ID used for elements created in this
2273 int32_t GetDefaultNamespaceID() const { return mDefaultElementType
; }
2275 void RemoveAllProperties();
2276 void RemoveAllPropertiesFor(nsINode
* aNode
);
2278 nsPropertyTable
& PropertyTable() { return mPropertyTable
; }
2281 * Sets the ID used to identify this part of the multipart document
2283 void SetPartID(uint32_t aID
) { mPartID
= aID
; }
2286 * Return the ID used to identify this part of the multipart document
2288 uint32_t GetPartID() const { return mPartID
; }
2291 * Sanitize the document by resetting all input elements and forms that have
2292 * autocomplete=off to their default values.
2293 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2295 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Sanitize();
2298 * Enumerate all subdocuments.
2299 * The enumerator callback should return CallState::Continue to continue
2300 * enumerating, or CallState::Stop to stop. This will never get passed a null
2303 using SubDocEnumFunc
= FunctionRef
<CallState(Document
&)>;
2304 void EnumerateSubDocuments(SubDocEnumFunc aCallback
);
2307 * Collect all the descendant documents for which |aCalback| returns true.
2308 * The callback function must not mutate any state for the given document.
2310 using nsDocTestFunc
= bool (*)(const Document
* aDocument
);
2311 void CollectDescendantDocuments(nsTArray
<RefPtr
<Document
>>& aDescendants
,
2312 nsDocTestFunc aCallback
) const;
2315 * Check whether it is safe to cache the presentation of this document
2316 * and all of its subdocuments (depending on the 3rd param). This method
2317 * checks the following conditions recursively:
2318 * - Some document types, such as plugin documents, cannot be safely cached.
2319 * - If there are any pending requests, we don't allow the presentation
2320 * to be cached. Ideally these requests would be suspended and resumed,
2321 * but that is difficult in some cases, such as XMLHttpRequest.
2322 * - If there are any beforeunload or unload listeners, we must fire them
2323 * for correctness, but this likely puts the document into a state where
2324 * it would not function correctly if restored.
2326 * |aNewRequest| should be the request for a new document which will
2327 * replace this document in the docshell. The new document's request
2328 * will be ignored when checking for active requests. If there is no
2329 * request associated with the new document, this parameter may be null.
2331 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2332 * combination is when we try to BFCache aNewRequest
2334 virtual bool CanSavePresentation(nsIRequest
* aNewRequest
,
2335 uint32_t& aBFCacheCombo
,
2336 bool aIncludeSubdocuments
,
2337 bool aAllowUnloadListeners
= true);
2340 * Pass principals if the correct ones are known when calling Init. That way
2341 * NodeInfoManager doesn't need to create a temporary null principal.
2343 virtual nsresult
Init(nsIPrincipal
* aPrincipal
,
2344 nsIPrincipal
* aPartitionedPrincipal
);
2347 * Notify the document that its associated DocumentViewer is being destroyed.
2348 * This releases circular references so that the document can go away.
2349 * Destroy() is only called on documents that have a content viewer.
2351 virtual void Destroy();
2354 * Notify the document that its associated DocumentViewer is no longer
2355 * the current viewer for the docshell. The document might still
2356 * be rendered in "zombie state" until the next document is ready.
2357 * The document should save form control state.
2359 void RemovedFromDocShell();
2362 * Get the layout history state that should be used to save and restore state
2363 * for nodes in this document. This may return null; if that happens state
2364 * saving and restoration is not possible.
2366 already_AddRefed
<nsILayoutHistoryState
> GetLayoutHistoryState() const;
2369 * Methods that can be used to prevent onload firing while an event that
2370 * should block onload is posted. onload is guaranteed to not fire until
2371 * either all calls to BlockOnload() have been matched by calls to
2372 * UnblockOnload() or the load has been stopped altogether (by the user
2373 * pressing the Stop button, say).
2377 * @param aFireSync whether to fire onload synchronously. If false,
2378 * onload will fire asynchronously after all onload blocks have been
2379 * removed. It will NOT fire from inside UnblockOnload. If true,
2380 * onload may fire from inside UnblockOnload.
2382 void UnblockOnload(bool aFireSync
);
2384 // Only BlockOnload should call this!
2385 void AsyncBlockOnload();
2387 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded
; }
2389 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnblockDOMContentLoaded();
2392 * Notification that the page has been shown, for documents which are loaded
2393 * into a DOM window. This corresponds to the completion of document load,
2394 * or to the page's presentation being restored into an existing DOM window.
2395 * This notification fires applicable DOM events to the content window. See
2396 * PageTransitionEvent.webidl for a description of the |aPersisted|
2397 * parameter. If aDispatchStartTarget is null, the pageshow event is
2398 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2399 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2400 * event is only dispatched to listeners in the system group.
2401 * Note: if aDispatchStartTarget isn't null, the showing state of the
2402 * document won't be altered.
2404 virtual void OnPageShow(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2405 bool aOnlySystemGroup
= false);
2408 * Notification that the page has been hidden, for documents which are loaded
2409 * into a DOM window. This corresponds to the unloading of the document, or
2410 * to the document's presentation being saved but removed from an existing
2411 * DOM window. This notification fires applicable DOM events to the content
2412 * window. See PageTransitionEvent.webidl for a description of the
2413 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2414 * event is dispatched on the ScriptGlobalObject for this document,
2415 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2416 * true, the event is only dispatched to listeners in the system group.
2417 * Note: if aDispatchStartTarget isn't null, the showing state of the
2418 * document won't be altered.
2420 void OnPageHide(bool aPersisted
, EventTarget
* aDispatchStartTarget
,
2421 bool aOnlySystemGroup
= false);
2424 * We record the set of links in the document that are relevant to
2428 * Notification that an element is a link that is relevant to style.
2430 void AddStyleRelevantLink(Link
* aLink
) {
2431 NS_ASSERTION(aLink
, "Passing in a null link. Expect crashes RSN!");
2433 NS_ASSERTION(!mStyledLinks
.Contains(aLink
),
2434 "Document already knows about this Link!");
2435 mStyledLinksCleared
= false;
2437 mStyledLinks
.Insert(aLink
);
2441 * Notification that an element is a link and its URI might have been
2442 * changed or the element removed. If the element is still a link relevant
2443 * to style, then someone must ensure that AddStyleRelevantLink is
2444 * (eventually) called on it again.
2446 void ForgetLink(Link
* aLink
) {
2447 MOZ_ASSERT(aLink
, "Passing in a null link. Expect crashes RSN!");
2448 MOZ_ASSERT(mStyledLinks
.Contains(aLink
) || mStyledLinksCleared
,
2449 "Document knows nothing about this Link!");
2450 mStyledLinks
.Remove(aLink
);
2453 // Refreshes the hrefs of all the links in the document.
2454 void RefreshLinkHrefs();
2457 * Support for window.matchMedia()
2460 already_AddRefed
<MediaQueryList
> MatchMedia(const nsACString
& aMediaQueryList
,
2461 CallerType aCallerType
);
2463 LinkedList
<MediaQueryList
>& MediaQueryLists() { return mDOMMediaQueryLists
; }
2465 using ContentIdentifiersForLCPType
=
2466 nsTHashMap
<NoMemMoveKey
<nsPtrHashKey
<const Element
>>,
2467 AutoTArray
<WeakPtr
<PreloaderBase
>, 1>>;
2469 ContentIdentifiersForLCPType
& ContentIdentifiersForLCP() {
2470 return mContentIdentifiersForLCP
;
2474 * Get the compatibility mode for this document
2476 nsCompatibility
GetCompatibilityMode() const { return mCompatMode
; }
2479 * Check whether we've ever fired a DOMTitleChanged event for this
2482 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange
; }
2485 * To batch DOMSubtreeModified, document needs to be informed when
2486 * a mutation event might be dispatched, even if the event isn't actually
2487 * created because there are no listeners for it.
2489 * @param aTarget is the target for the mutation event.
2491 void MayDispatchMutationEvent(nsINode
* aTarget
) {
2492 if (mSubtreeModifiedDepth
> 0) {
2493 mSubtreeModifiedTargets
.AppendObject(aTarget
);
2498 * Marks as not-going-to-be-collected for the given generation of
2501 void MarkUncollectableForCCGeneration(uint32_t aGeneration
) {
2502 mMarkedCCGeneration
= aGeneration
;
2506 * Gets the cycle collector generation this document is marked for.
2508 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration
; }
2511 * Returns whether this document is cookie averse. See
2512 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2514 bool IsCookieAverse() const {
2515 // If we are a document that "has no browsing context."
2516 if (!GetInnerWindow()) {
2520 // If we are a document "whose URL's scheme is not a network scheme."
2521 // NB: Explicitly allow file: URIs to store cookies.
2523 return !NodePrincipal()->SchemeIs("http") &&
2524 !NodePrincipal()->SchemeIs("https") &&
2525 !NodePrincipal()->SchemeIs("file");
2528 bool IsLoadedAsData() { return mLoadedAsData
; }
2530 void SetAddedToMemoryReportAsDataDocument() {
2531 mAddedToMemoryReportingAsDataDocument
= true;
2534 void UnregisterFromMemoryReportingForDataDocument();
2536 bool MayStartLayout() { return mMayStartLayout
; }
2538 void SetMayStartLayout(bool aMayStartLayout
);
2540 already_AddRefed
<nsIDocumentEncoder
> GetCachedEncoder();
2542 void SetCachedEncoder(already_AddRefed
<nsIDocumentEncoder
> aEncoder
);
2544 // In case of failure, the document really can't initialize the frame loader.
2545 nsresult
InitializeFrameLoader(nsFrameLoader
* aLoader
);
2546 // In case of failure, the caller must handle the error, for example by
2547 // finalizing frame loader asynchronously.
2548 nsresult
FinalizeFrameLoader(nsFrameLoader
* aLoader
, nsIRunnable
* aFinalizer
);
2549 // Removes the frame loader of aShell from the initialization list.
2550 void TryCancelFrameLoaderInitialization(nsIDocShell
* aShell
);
2553 * Check whether this document is a root document that is not an
2554 * external resource.
2556 bool IsRootDisplayDocument() const {
2557 return !mParentDocument
&& !mDisplayDocument
;
2560 bool ChromeRulesEnabled() const { return mChromeRulesEnabled
; }
2562 bool IsInChromeDocShell() const {
2563 const Document
* root
= this;
2564 while (const Document
* displayDoc
= root
->GetDisplayDocument()) {
2567 return root
->mInChromeDocShell
;
2570 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage
; }
2572 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage
= true; }
2574 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument
; }
2576 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument
= true; }
2578 bool IsResourceDoc() const {
2579 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2580 mHasDisplayDocument
; // Are we an external resource doc?
2584 * Get the document for which this document is an external resource. This
2585 * will be null if this document is not an external resource. Otherwise,
2586 * GetDisplayDocument() will return a non-null document, and
2587 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2589 Document
* GetDisplayDocument() const { return mDisplayDocument
; }
2592 * Set the display document for this document. aDisplayDocument must not be
2595 void SetDisplayDocument(Document
* aDisplayDocument
) {
2596 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2597 "Shouldn't set mDisplayDocument on documents that already "
2598 "have a presentation or a docshell or a window");
2599 MOZ_ASSERT(aDisplayDocument
, "Must not be null");
2600 MOZ_ASSERT(aDisplayDocument
!= this, "Should be different document");
2601 MOZ_ASSERT(!aDisplayDocument
->GetDisplayDocument(),
2602 "Display documents should not nest");
2603 mDisplayDocument
= aDisplayDocument
;
2604 mHasDisplayDocument
= !!aDisplayDocument
;
2608 * Request an external resource document for aURI. This will return the
2609 * resource document if available. If one is not available yet, it will
2610 * start loading as needed, and the pending load object will be returned in
2611 * aPendingLoad so that the caller can register an observer to wait for the
2612 * load. If this function returns null and doesn't return a pending load,
2613 * that means that there is no resource document for this URI and won't be
2614 * one in the future.
2616 * @param aURI the URI to get
2617 * @param aReferrerInfo the referrerInfo of the request
2618 * @param aRequestingNode the node making the request
2619 * @param aPendingLoad the pending load for this request, if any
2621 Document
* RequestExternalResource(nsIURI
* aURI
,
2622 nsIReferrerInfo
* aReferrerInfo
,
2623 nsINode
* aRequestingNode
,
2624 ExternalResourceLoad
** aPendingLoad
);
2627 * Enumerate the external resource documents associated with this document.
2628 * The enumerator callback should return CallState::Continue to continue
2629 * enumerating, or CallState::Stop to stop. This callback will never get
2630 * passed a null aDocument.
2632 void EnumerateExternalResources(SubDocEnumFunc aCallback
);
2634 dom::ExternalResourceMap
& ExternalResourceMap() {
2635 return mExternalResourceMap
;
2639 * Return whether the document is currently showing (in the sense of
2640 * OnPageShow() having been called already and OnPageHide() not having been
2643 bool IsShowing() const { return mIsShowing
; }
2645 * Return whether the document is currently visible (in the sense of
2646 * OnPageHide having been called and OnPageShow not yet having been called)
2648 bool IsVisible() const { return mVisible
; }
2650 void SetSuppressedEventListener(EventListener
* aListener
);
2652 EventListener
* GetSuppressedEventListener() {
2653 return mSuppressedEventListener
;
2657 * Return true when this document is active, i.e., an active document
2658 * in a content viewer and not in the bfcache.
2659 * This does NOT match the "active document" concept in the WHATWG spec -
2660 * see IsCurrentActiveDocument.
2662 bool IsActive() const;
2665 * Return true if this is the current active document for its
2666 * docshell. Note that a docshell may have multiple active documents
2667 * due to the bfcache -- this should be used when you need to
2668 * differentiate the *current* active document from any active
2671 bool IsCurrentActiveDocument() const {
2672 nsPIDOMWindowInner
* inner
= GetInnerWindow();
2673 return inner
&& inner
->IsCurrentInnerWindow() && inner
->GetDoc() == this;
2677 * Returns whether this document should perform image loads.
2679 bool ShouldLoadImages() const {
2680 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2681 // images can themselves have data: URL image references.
2682 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2686 void SetHasPrintCallbacks() {
2687 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2688 mHasPrintCallbacks
= true;
2691 bool HasPrintCallbacks() const { return mHasPrintCallbacks
; }
2694 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2695 * the document's activity changes such as OnPageHide, visibility, activity.
2696 * The ActivityObserver objects can be nsIObjectLoadingContent or
2697 * nsIDocumentActivity or HTMLMEdiaElement.
2699 void RegisterActivityObserver(nsISupports
* aSupports
);
2700 bool UnregisterActivityObserver(nsISupports
* aSupports
);
2701 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2702 using ActivityObserverEnumerator
= FunctionRef
<void(nsISupports
*)>;
2703 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator
);
2705 void NotifyActivityChanged();
2707 // Indicates whether mAnimationController has been (lazily) initialized.
2708 // If this returns true, we're promising that GetAnimationController()
2709 // will have a non-null return value.
2710 bool HasAnimationController() { return !!mAnimationController
; }
2712 // Getter for this document's SMIL Animation Controller. Performs lazy
2713 // initialization, if this document supports animation and if
2714 // mAnimationController isn't yet initialized.
2716 // If HasAnimationController is true, this is guaranteed to return non-null.
2717 SMILAnimationController
* GetAnimationController();
2719 // Gets the tracker for scroll-driven animations that are waiting to start.
2720 // Returns nullptr if there is no scroll-driven animation tracker for this
2721 // document which will be the case if there have never been any scroll-driven
2722 // animations in the document.
2723 ScrollTimelineAnimationTracker
* GetScrollTimelineAnimationTracker() {
2724 return mScrollTimelineAnimationTracker
;
2727 // Gets the tracker for scroll-driven animations that are waiting to start and
2728 // creates it if it doesn't already exist. As a result, the return value
2729 // will never be nullptr.
2730 ScrollTimelineAnimationTracker
* GetOrCreateScrollTimelineAnimationTracker();
2733 * Prevents user initiated events from being dispatched to the document and
2736 void SuppressEventHandling(uint32_t aIncrease
= 1);
2739 * Unsuppress event handling.
2740 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2743 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void UnsuppressEventHandlingAndFireEvents(
2746 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed
; }
2748 bool IsEventHandlingEnabled() const {
2749 return !EventHandlingSuppressed() && mScriptGlobalObject
;
2752 void MaybeScheduleFrameRequestCallbacks();
2753 bool ShouldFireFrameRequestCallbacks() const {
2754 // If this condition changes make sure to call
2755 // MaybeScheduleFrameRequestCallbacks at the right places.
2756 return mPresShell
&& IsEventHandlingEnabled();
2759 void DecreaseEventSuppression() {
2760 MOZ_ASSERT(mEventsSuppressed
);
2761 --mEventsSuppressed
;
2762 MaybeScheduleFrameRequestCallbacks();
2766 * Some clipboard commands are unconditionally enabled on some documents, so
2767 * as to always dispatch copy / paste events even though you'd normally not be
2770 bool AreClipboardCommandsUnconditionallyEnabled() const;
2773 * Note a ChannelEventQueue which has been suspended on the document's behalf
2774 * to prevent XHRs from running content scripts while event handling is
2775 * suppressed. The document is responsible for resuming the queue after
2776 * event handling is unsuppressed.
2778 void AddSuspendedChannelEventQueue(net::ChannelEventQueue
* aQueue
);
2781 * Returns true if a postMessage event should be suspended instead of running.
2782 * The document is responsible for running the event later, in the order they
2785 bool SuspendPostMessageEvent(PostMessageEvent
* aEvent
);
2788 * Run any suspended postMessage events, or clear them.
2790 void FireOrClearPostMessageEvents(bool aFireEvents
);
2792 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent
= true; }
2795 * Flag whether we're about to fire the window's load event for this document.
2797 void SetLoadEventFiring(bool aFiring
) { mLoadEventFiring
= aFiring
; }
2800 * Test whether we should be firing a load event for this document after a
2801 * document.close(). This is public and on Document, instead of being private
2802 * to Document, because we need to go through the normal docloader logic
2803 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2804 * semantics of firing the load event; we just don't want to fire the load
2805 * event if this tests true. So we need the docloader to be able to access
2808 * This method should only be called at the point when the load event is about
2809 * to be fired. It resets the "skip" flag, so it is not idempotent.
2811 bool SkipLoadEventAfterClose() {
2812 bool skip
= mSkipLoadEventAfterClose
;
2813 mSkipLoadEventAfterClose
= false;
2818 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2820 void IncrementIgnoreDestructiveWritesCounter() {
2821 ++mIgnoreDestructiveWritesCounter
;
2825 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2827 void DecrementIgnoreDestructiveWritesCounter() {
2828 --mIgnoreDestructiveWritesCounter
;
2831 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch
; }
2834 * Returns true if this document is allowed to contain XUL element and
2835 * use non-builtin XBL bindings.
2837 bool AllowXULXBL() {
2838 return mAllowXULXBL
== eTriTrue
? true
2839 : mAllowXULXBL
== eTriFalse
? false
2840 : InternalAllowXULXBL();
2844 * Returns true if this document is allowed to load DTDs from UI resources
2847 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks
; }
2849 void ForceEnableXULXBL() { mAllowXULXBL
= eTriTrue
; }
2851 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks
= true; }
2854 * Returns the template content owner document that owns the content of
2855 * HTMLTemplateElement.
2857 Document
* GetTemplateContentsOwner();
2859 Document
* GetTemplateContentsOwnerIfExists() const {
2860 return mTemplateContentsOwner
.get();
2863 bool IsTemplateContentsOwner() const {
2864 // Template contents owner documents are the template contents owner of
2866 return mTemplateContentsOwner
== this;
2870 * Returns true if this document is a static clone of a normal document.
2872 * We create static clones for print preview and printing (possibly other
2873 * things in future).
2875 * Note that static documents are also "loaded as data" (if this method
2876 * returns true, IsLoadedAsData() will also return true).
2878 bool IsStaticDocument() const { return mIsStaticDocument
; }
2881 * Clones the document along with any subdocuments, stylesheet, etc.
2883 * The resulting document and everything it contains (including any
2884 * sub-documents) are created purely via cloning. The returned documents and
2885 * any sub-documents are "loaded as data" documents to preserve the state as
2886 * it was during the clone process (we don't want external resources to load
2887 * and replace the cloned resources).
2889 * @param aCloneContainer The container for the clone document.
2890 * @param aDocumentViewer The viewer for the clone document. Must be the
2891 * viewer of aCloneContainer, but callers must have a
2892 * reference to it already and ensure it's not null.
2893 * @param aPrintSettings The print settings for this clone.
2894 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2896 already_AddRefed
<Document
> CreateStaticClone(
2897 nsIDocShell
* aCloneContainer
, nsIDocumentViewer
* aDocumentViewer
,
2898 nsIPrintSettings
* aPrintSettings
, bool* aOutHasInProcessPrintCallbacks
);
2901 * If this document is a static clone, this returns the original
2904 Document
* GetOriginalDocument() const {
2905 MOZ_ASSERT(!mOriginalDocument
|| !mOriginalDocument
->GetOriginalDocument());
2906 return mOriginalDocument
;
2910 * If this document is a static clone, let the original document know that
2911 * we're going away and then release our reference to it.
2913 void UnlinkOriginalDocumentIfStatic();
2916 * These are called by the parser as it encounters <picture> tags, the end of
2917 * said tags, and possible picture <source srcset> sources respectively. These
2918 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2919 * expected to be marked void.
2921 * NOTE that the parser does not attempt to track the current picture nesting
2922 * level or whether the given <source> tag is within a picture -- it is only
2923 * guaranteed to order these calls properly with respect to
2924 * ResolvePreLoadImage.
2927 void PreloadPictureOpened() { mPreloadPictureDepth
++; }
2929 void PreloadPictureClosed();
2931 void PreloadPictureImageSource(const nsAString
& aSrcsetAttr
,
2932 const nsAString
& aSizesAttr
,
2933 const nsAString
& aTypeAttr
,
2934 const nsAString
& aMediaAttr
);
2937 * Called by the parser to resolve an image for preloading. The parser will
2938 * call the PreloadPicture* functions to inform us of possible <picture>
2939 * nesting and possible sources, which are used to inform URL selection
2940 * responsive <picture> or <img srcset> images. Unset attributes are expected
2941 * to be marked void.
2942 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2943 * true, false otherwise.
2945 already_AddRefed
<nsIURI
> ResolvePreloadImage(nsIURI
* aBaseURI
,
2946 const nsAString
& aSrcAttr
,
2947 const nsAString
& aSrcsetAttr
,
2948 const nsAString
& aSizesAttr
,
2951 * Called by nsParser to preload images. Can be removed and code moved
2952 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2953 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2954 * be a void string if the attr is not present.
2955 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2956 * when this image is for loading <picture> or <img srcset> images.
2958 void MaybePreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2959 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2960 bool aLinkPreload
, const nsAString
& aFetchPriority
);
2961 void PreLoadImage(nsIURI
* uri
, const nsAString
& aCrossOriginAttr
,
2962 ReferrerPolicyEnum aReferrerPolicy
, bool aIsImgSet
,
2963 bool aLinkPreload
, uint64_t aEarlyHintPreloaderId
,
2964 const nsAString
& aFetchPriority
);
2967 * Called by images to forget an image preload when they start doing
2970 void ForgetImagePreload(nsIURI
* aURI
);
2973 * Called by the parser or the preload service to preload style sheets.
2974 * aCrossOriginAttr should be a void string if the attr is not present.
2976 SheetPreloadStatus
PreloadStyle(nsIURI
* aURI
, const Encoding
* aEncoding
,
2977 const nsAString
& aCrossOriginAttr
,
2978 ReferrerPolicyEnum aReferrerPolicy
,
2979 const nsAString
& aNonce
,
2980 const nsAString
& aIntegrity
,
2981 css::StylePreloadKind
,
2982 uint64_t aEarlyHintPreloaderId
,
2983 const nsAString
& aFetchPriority
);
2986 * Called by the chrome registry to load style sheets.
2988 * This always does a synchronous load, and parses as a normal document sheet.
2990 RefPtr
<StyleSheet
> LoadChromeSheetSync(nsIURI
* aURI
);
2993 * Returns true if the locale used for the document specifies a direction of
2994 * right to left. For chrome documents, this comes from the chrome registry.
2995 * This is used to determine the current state for the :-moz-locale-dir
2996 * pseudoclass so once can know whether a document is expected to be rendered
2997 * left-to-right or right-to-left.
2999 bool IsDocumentRightToLeft();
3002 * Called by Parser for link rel=preconnect
3004 void MaybePreconnect(nsIURI
* uri
, CORSMode aCORSMode
);
3007 * Set the document's pending state object (as serialized using structured
3010 void SetStateObject(nsIStructuredCloneContainer
* scContainer
);
3013 * Set the document's pending state object to the same state object as
3016 void SetStateObjectFrom(Document
* aDocument
) {
3017 SetStateObject(aDocument
->mStateObjectContainer
);
3020 // Whether we're a media document or not.
3021 enum class MediaDocumentKind
{
3027 virtual enum MediaDocumentKind
MediaDocumentKind() const {
3028 return MediaDocumentKind::NotMedia
;
3031 DocumentState
State() const { return mState
; }
3033 nsISupports
* GetCurrentContentSink();
3035 void ElementWithAutoFocusInserted(Element
* aAutoFocusCandidate
);
3036 MOZ_CAN_RUN_SCRIPT
void FlushAutoFocusCandidates();
3037 void ScheduleFlushAutoFocusCandidates();
3038 bool HasAutoFocusCandidates() const {
3039 return !mAutoFocusCandidates
.IsEmpty();
3042 void SetAutoFocusFired();
3044 void SetScrollToRef(nsIURI
* aDocumentURI
);
3045 MOZ_CAN_RUN_SCRIPT
void ScrollToRef();
3046 void ResetScrolledToRefAlready() { mScrolledToRefAlready
= false; }
3048 void SetChangeScrollPosWhenScrollingToRef(bool aValue
) {
3049 mChangeScrollPosWhenScrollingToRef
= aValue
;
3052 using DocumentOrShadowRoot::GetElementById
;
3053 using DocumentOrShadowRoot::GetElementsByClassName
;
3054 using DocumentOrShadowRoot::GetElementsByTagName
;
3055 using DocumentOrShadowRoot::GetElementsByTagNameNS
;
3057 DocumentTimeline
* Timeline();
3058 LinkedList
<DocumentTimeline
>& Timelines() { return mTimelines
; }
3059 void UpdateHiddenByContentVisibilityForAnimations();
3061 SVGSVGElement
* GetSVGRootElement() const;
3063 nsresult
ScheduleFrameRequestCallback(FrameRequestCallback
& aCallback
,
3065 void CancelFrameRequestCallback(uint32_t aHandle
);
3067 void ScheduleVideoFrameCallbacks(HTMLVideoElement
* aElement
);
3068 void CancelVideoFrameCallbacks(HTMLVideoElement
* aElement
);
3071 * Returns true if the handle refers to a callback that was canceled that
3072 * we did not find in our list of callbacks (e.g. because it is one of those
3073 * in the set of callbacks currently queued to be run).
3075 bool IsCanceledFrameRequestCallback(uint32_t aHandle
) const;
3078 * Put this document's video frame request callbacks into the provided
3079 * list, and forget about them.
3081 void TakeVideoFrameRequestCallbacks(
3082 nsTArray
<RefPtr
<HTMLVideoElement
>>& aVideoCallbacks
);
3085 * Put this document's frame request callbacks into the provided
3086 * list, and forget about them.
3088 void TakeFrameRequestCallbacks(nsTArray
<FrameRequest
>& aCallbacks
);
3090 /** Whether we have any scheduled frame request */
3091 bool HasFrameRequestCallbacks() const {
3092 return !mFrameRequestManager
.IsEmpty();
3096 * @return true if this document's frame request callbacks should be
3097 * throttled. We throttle requestAnimationFrame for documents which aren't
3098 * visible (e.g. scrolled out of the viewport).
3100 bool ShouldThrottleFrameRequests() const;
3102 // This returns true when the document tree is being teared down.
3103 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion
; }
3105 dom::ImageTracker
* ImageTracker();
3107 // Adds an element to mResponsiveContent when the element is
3108 // added to the tree.
3109 void AddResponsiveContent(HTMLImageElement
* aContent
) {
3110 MOZ_ASSERT(aContent
);
3111 mResponsiveContent
.Insert(aContent
);
3114 // Removes an element from mResponsiveContent when the element is
3115 // removed from the tree.
3116 void RemoveResponsiveContent(HTMLImageElement
* aContent
) {
3117 MOZ_ASSERT(aContent
);
3118 mResponsiveContent
.Remove(aContent
);
3121 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement
&);
3122 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement
& aElement
) {
3123 mSVGUseElementsNeedingShadowTreeUpdate
.Remove(&aElement
);
3126 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement
& aElement
) const {
3127 return mSVGUseElementsNeedingShadowTreeUpdate
.Contains(&aElement
);
3130 using ShadowRootSet
= nsTHashSet
<ShadowRoot
*>;
3132 void AddComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3133 mComposedShadowRoots
.Insert(&aShadowRoot
);
3136 void RemoveComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3137 mComposedShadowRoots
.Remove(&aShadowRoot
);
3140 // If you're considering using this, you probably want to use
3141 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3143 bool IsComposedDocShadowRoot(ShadowRoot
& aShadowRoot
) {
3144 return mComposedShadowRoots
.Contains(&aShadowRoot
);
3147 const ShadowRootSet
& ComposedShadowRoots() const {
3148 return mComposedShadowRoots
;
3151 // WebIDL method for chrome code.
3152 void GetConnectedShadowRoots(nsTArray
<RefPtr
<ShadowRoot
>>&) const;
3154 void SynchronouslyUpdateRemoteBrowserDimensions(
3155 bool aIncludeInactive
= false);
3157 // Notifies any responsive content added by AddResponsiveContent upon media
3158 // features values changing.
3159 void NotifyMediaFeatureValuesChanged();
3161 nsresult
GetStateObject(JS::MutableHandle
<JS::Value
> aState
);
3163 nsDOMNavigationTiming
* GetNavigationTiming() const { return mTiming
; }
3165 void SetNavigationTiming(nsDOMNavigationTiming
* aTiming
);
3167 inline void SetPageloadEventFeature(uint32_t aFeature
) {
3168 mPageloadEventFeatures
|= aFeature
;
3171 nsContentList
* ImageMapList();
3173 // Add aLink to the set of links that need their status resolved.
3174 void RegisterPendingLinkUpdate(Link
* aLink
);
3176 // Update state on links in mLinksToUpdate.
3177 void FlushPendingLinkUpdates();
3179 bool HasWarnedAbout(DeprecatedOperations aOperation
) const;
3181 DeprecatedOperations aOperation
, bool asError
= false,
3182 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3184 #define DOCUMENT_WARNING(_op) e##_op,
3185 enum DocumentWarnings
{
3186 #include "nsDocumentWarningList.h"
3187 eDocumentWarningCount
3189 #undef DOCUMENT_WARNING
3190 bool HasWarnedAbout(DocumentWarnings aWarning
) const;
3192 DocumentWarnings aWarning
, bool asError
= false,
3193 const nsTArray
<nsString
>& aParams
= nsTArray
<nsString
>()) const;
3195 // This method may fire a DOM event; if it does so it will happen
3198 // Whether the event fires is controlled by the argument.
3199 enum class DispatchVisibilityChange
{ No
, Yes
};
3200 void UpdateVisibilityState(
3201 DispatchVisibilityChange
= DispatchVisibilityChange::Yes
);
3203 // Posts an event to call UpdateVisibilityState.
3204 void PostVisibilityUpdateEvent();
3206 bool IsSyntheticDocument() const { return mIsSyntheticDocument
; }
3208 // Adds the size of a given node, which must not be a document node, to the
3209 // window sizes passed-in.
3210 static void AddSizeOfNodeTree(nsINode
&, nsWindowSizes
&);
3212 // Note: Document is a sub-class of nsINode, which has a
3213 // SizeOfExcludingThis function. However, because Document objects can
3214 // only appear at the top of the DOM tree, we have a specialized measurement
3215 // function which returns multiple sizes.
3216 virtual void DocAddSizeOfExcludingThis(nsWindowSizes
& aWindowSizes
) const;
3217 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3218 // because Document inherits from nsINode; see the comment above the
3219 // declaration of nsINode::SizeOfIncludingThis.
3220 virtual void DocAddSizeOfIncludingThis(nsWindowSizes
& aWindowSizes
) const;
3222 void ConstructUbiNode(void* storage
) override
;
3224 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers
; }
3226 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers
= true; }
3228 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers
; }
3230 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers
= true; }
3232 bool IsInSyncOperation() { return mInSyncOperationCount
!= 0; }
3234 void SetIsInSyncOperation(bool aSync
);
3236 bool CreatingStaticClone() const { return mCreatingStaticClone
; }
3239 * Creates a new element in the HTML namespace with a local name given by
3242 already_AddRefed
<Element
> CreateHTMLElement(nsAtom
* aTag
);
3245 nsIGlobalObject
* GetParentObject() const { return GetScopeObject(); }
3246 static already_AddRefed
<Document
> Constructor(const GlobalObject
& aGlobal
,
3248 DOMImplementation
* GetImplementation(ErrorResult
& rv
);
3249 [[nodiscard
]] nsresult
GetURL(nsString
& retval
) const;
3250 [[nodiscard
]] nsresult
GetDocumentURI(nsString
& retval
) const;
3251 // Return the URI for the document.
3252 // The returned value may differ if the document is loaded via XHR, and
3253 // when accessed from chrome privileged script and
3254 // from content privileged script for compatibility.
3255 void GetDocumentURIFromJS(nsString
& aDocumentURI
, CallerType aCallerType
,
3256 ErrorResult
& aRv
) const;
3257 void GetCompatMode(nsString
& retval
) const;
3258 void GetCharacterSet(nsAString
& retval
) const;
3259 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3260 // GetDoctype defined above
3261 Element
* GetDocumentElement() const { return GetRootElement(); }
3263 WindowContext
* GetTopLevelWindowContext() const;
3265 // If the top-level ancestor content document for this document is in the same
3266 // process, returns it. Otherwise, returns null. This function is not
3267 // Fission-compatible, and should not be used in new code.
3268 Document
* GetTopLevelContentDocumentIfSameProcess();
3269 const Document
* GetTopLevelContentDocumentIfSameProcess() const;
3271 // Returns the associated app window if this is a top-level chrome document,
3273 already_AddRefed
<nsIAppWindow
> GetAppWindowIfToplevelChrome() const;
3275 already_AddRefed
<Element
> CreateElement(
3276 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3278 already_AddRefed
<Element
> CreateElementNS(
3279 const nsAString
& aNamespaceURI
, const nsAString
& aQualifiedName
,
3280 const ElementCreationOptionsOrString
& aOptions
, ErrorResult
& rv
);
3281 already_AddRefed
<Element
> CreateXULElement(
3282 const nsAString
& aTagName
, const ElementCreationOptionsOrString
& aOptions
,
3284 already_AddRefed
<DocumentFragment
> CreateDocumentFragment() const;
3285 already_AddRefed
<nsTextNode
> CreateTextNode(const nsAString
& aData
) const;
3286 already_AddRefed
<nsTextNode
> CreateEmptyTextNode() const;
3287 already_AddRefed
<Comment
> CreateComment(const nsAString
& aData
) const;
3288 already_AddRefed
<ProcessingInstruction
> CreateProcessingInstruction(
3289 const nsAString
& target
, const nsAString
& data
, ErrorResult
& rv
) const;
3290 already_AddRefed
<nsINode
> ImportNode(nsINode
& aNode
, bool aDeep
,
3291 ErrorResult
& rv
) const;
3292 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3293 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode
* AdoptNode(
3294 nsINode
& aAdoptedNode
, ErrorResult
& rv
, bool aAcceptShadowRoot
= false);
3295 already_AddRefed
<Event
> CreateEvent(const nsAString
& aEventType
,
3296 CallerType aCallerType
,
3297 ErrorResult
& rv
) const;
3298 already_AddRefed
<nsRange
> CreateRange(ErrorResult
& rv
);
3299 already_AddRefed
<NodeIterator
> CreateNodeIterator(nsINode
& aRoot
,
3300 uint32_t aWhatToShow
,
3301 NodeFilter
* aFilter
,
3302 ErrorResult
& rv
) const;
3303 already_AddRefed
<TreeWalker
> CreateTreeWalker(nsINode
& aRoot
,
3304 uint32_t aWhatToShow
,
3305 NodeFilter
* aFilter
,
3306 ErrorResult
& rv
) const;
3307 // Deprecated WebIDL bits
3308 already_AddRefed
<CDATASection
> CreateCDATASection(const nsAString
& aData
,
3310 already_AddRefed
<Attr
> CreateAttribute(const nsAString
& aName
,
3312 already_AddRefed
<Attr
> CreateAttributeNS(const nsAString
& aNamespaceURI
,
3313 const nsAString
& aQualifiedName
,
3315 void GetInputEncoding(nsAString
& aInputEncoding
) const;
3316 already_AddRefed
<Location
> GetLocation() const;
3317 void GetDomain(nsAString
& aDomain
);
3318 void SetDomain(const nsAString
& aDomain
, mozilla::ErrorResult
& rv
);
3319 void GetCookie(nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3320 void SetCookie(const nsAString
& aCookie
, mozilla::ErrorResult
& rv
);
3321 void GetReferrer(nsACString
& aReferrer
) const;
3322 void GetLastModified(nsAString
& aLastModified
) const;
3323 void GetReadyState(nsAString
& aReadyState
) const;
3325 void GetTitle(nsAString
& aTitle
);
3326 void SetTitle(const nsAString
& aTitle
, ErrorResult
& rv
);
3327 void GetDir(nsAString
& aDirection
) const;
3328 void SetDir(const nsAString
& aDirection
);
3329 nsIHTMLCollection
* Images();
3330 nsIHTMLCollection
* Embeds();
3331 nsIHTMLCollection
* Plugins() { return Embeds(); }
3332 nsIHTMLCollection
* Links();
3333 nsIHTMLCollection
* Forms();
3334 nsIHTMLCollection
* Scripts();
3335 already_AddRefed
<nsContentList
> GetElementsByName(const nsAString
& aName
) {
3336 return GetFuncStringContentList
<nsCachableElementsByNameNodeList
>(
3337 this, MatchNameAttribute
, nullptr, UseExistingNameString
, aName
);
3339 Document
* Open(const mozilla::dom::Optional
<nsAString
>& /* unused */,
3340 const mozilla::dom::Optional
<nsAString
>& /* unused */,
3341 mozilla::ErrorResult
& aError
);
3342 mozilla::dom::Nullable
<mozilla::dom::WindowProxyHolder
> Open(
3343 const nsACString
& aURL
, const nsAString
& aName
,
3344 const nsAString
& aFeatures
, mozilla::ErrorResult
& rv
);
3345 void Close(mozilla::ErrorResult
& rv
);
3346 MOZ_CAN_RUN_SCRIPT
void Write(
3347 const mozilla::dom::Sequence
<OwningTrustedHTMLOrString
>& aText
,
3348 mozilla::ErrorResult
& rv
);
3349 MOZ_CAN_RUN_SCRIPT
void Writeln(
3350 const mozilla::dom::Sequence
<OwningTrustedHTMLOrString
>& aText
,
3351 mozilla::ErrorResult
& rv
);
3352 Nullable
<WindowProxyHolder
> GetDefaultView() const;
3353 Element
* GetActiveElement();
3354 enum class IncludeChromeOnly
: bool { No
, Yes
};
3355 // TODO(emilio): Audit callers and remove the default argument, some seem like
3356 // they could want the IncludeChromeOnly::Yes version.
3357 nsIContent
* GetUnretargetedFocusedContent(
3358 IncludeChromeOnly
= IncludeChromeOnly::No
) const;
3360 * Return true if this document or a subdocument has focus.
3362 bool HasFocus(ErrorResult
& rv
) const;
3365 * Return true if this document itself has focus.
3367 bool ThisDocumentHasFocus() const;
3369 void GetDesignMode(nsAString
& aDesignMode
);
3370 void SetDesignMode(const nsAString
& aDesignMode
,
3371 nsIPrincipal
& aSubjectPrincipal
, mozilla::ErrorResult
& rv
);
3372 void SetDesignMode(const nsAString
& aDesignMode
,
3373 const mozilla::Maybe
<nsIPrincipal
*>& aSubjectPrincipal
,
3374 mozilla::ErrorResult
& rv
);
3375 void SetDocumentEditableFlag(bool);
3377 bool ExecCommand(const nsAString
& aHTMLCommandName
, bool aShowUI
,
3378 const TrustedHTMLOrString
& aValue
,
3379 nsIPrincipal
& aSubjectPrincipal
, mozilla::ErrorResult
& aRv
);
3380 MOZ_CAN_RUN_SCRIPT
bool QueryCommandEnabled(const nsAString
& aHTMLCommandName
,
3381 nsIPrincipal
& aSubjectPrincipal
,
3382 mozilla::ErrorResult
& aRv
);
3383 MOZ_CAN_RUN_SCRIPT
bool QueryCommandIndeterm(
3384 const nsAString
& aHTMLCommandName
, mozilla::ErrorResult
& aRv
);
3385 MOZ_CAN_RUN_SCRIPT
bool QueryCommandState(const nsAString
& aHTMLCommandName
,
3386 mozilla::ErrorResult
& aRv
);
3387 MOZ_CAN_RUN_SCRIPT
bool QueryCommandSupported(
3388 const nsAString
& aHTMLCommandName
, mozilla::dom::CallerType aCallerType
,
3389 mozilla::ErrorResult
& aRv
);
3390 MOZ_CAN_RUN_SCRIPT
void QueryCommandValue(const nsAString
& aHTMLCommandName
,
3392 mozilla::ErrorResult
& aRv
);
3393 nsIHTMLCollection
* Applets();
3394 nsIHTMLCollection
* Anchors();
3395 TimeStamp
LastFocusTime() const;
3396 void SetLastFocusTime(const TimeStamp
& aFocusTime
);
3397 // Event handlers are all on nsINode already
3398 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3399 Element
* GetCurrentScript();
3400 void ReleaseCapture() const;
3401 void MozSetImageElement(const nsAString
& aImageElementId
, Element
* aElement
);
3402 nsIURI
* GetDocumentURIObject() const;
3403 // Not const because all the fullscreen goop is not const
3404 const char* GetFullscreenError(CallerType
);
3405 bool FullscreenEnabled(CallerType aCallerType
) {
3406 return !GetFullscreenError(aCallerType
);
3409 void GetWireframeWithoutFlushing(bool aIncludeNodes
, Nullable
<Wireframe
>&);
3411 MOZ_CAN_RUN_SCRIPT
void GetWireframe(bool aIncludeNodes
,
3412 Nullable
<Wireframe
>&);
3414 // Hides all popovers until the given end point, see
3415 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3416 MOZ_CAN_RUN_SCRIPT
void HideAllPopoversUntil(nsINode
& aEndpoint
,
3417 bool aFocusPreviousElement
,
3420 // Hides the given popover element, see
3421 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3422 MOZ_CAN_RUN_SCRIPT
void HidePopover(Element
& popover
,
3423 bool aFocusPreviousElement
,
3424 bool aFireEvents
, ErrorResult
& aRv
);
3426 // Returns a list of all the elements in the Document's top layer whose
3427 // popover attribute is in the auto state.
3428 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3429 nsTArray
<Element
*> AutoPopoverList() const;
3431 // Return document's auto popover list's last element.
3433 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3434 Element
* GetTopmostAutoPopover() const;
3436 // Adds/removes an element to/from the auto popover list.
3437 void AddToAutoPopoverList(Element
&);
3438 void RemoveFromAutoPopoverList(Element
&);
3440 void AddPopoverToTopLayer(Element
&);
3441 void RemovePopoverFromTopLayer(Element
&);
3443 Element
* GetTopLayerTop();
3444 // Return the fullscreen element in the top layer
3445 Element
* GetUnretargetedFullscreenElement() const;
3446 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3447 already_AddRefed
<Promise
> ExitFullscreen(ErrorResult
&);
3448 void ExitPointerLock() {
3449 PointerLockManager::Unlock("Document::ExitPointerLock", this);
3451 void GetFgColor(nsAString
& aFgColor
);
3452 void SetFgColor(const nsAString
& aFgColor
);
3453 void GetLinkColor(nsAString
& aLinkColor
);
3454 void SetLinkColor(const nsAString
& aLinkColor
);
3455 void GetVlinkColor(nsAString
& aAvlinkColor
);
3456 void SetVlinkColor(const nsAString
& aVlinkColor
);
3457 void GetAlinkColor(nsAString
& aAlinkColor
);
3458 void SetAlinkColor(const nsAString
& aAlinkColor
);
3459 void GetBgColor(nsAString
& aBgColor
);
3460 void SetBgColor(const nsAString
& aBgColor
);
3461 void Clear() const {
3464 void CaptureEvents();
3465 void ReleaseEvents();
3467 mozilla::dom::HTMLAllCollection
* All();
3469 static bool DocumentSupportsL10n(JSContext
* aCx
, JSObject
* aObject
);
3470 // Checks that the caller is either chrome or some addon.
3471 static bool IsCallerChromeOrAddon(JSContext
* aCx
, JSObject
* aObject
);
3473 bool Hidden() const { return mVisibilityState
!= VisibilityState::Visible
; }
3474 dom::VisibilityState
VisibilityState() const { return mVisibilityState
; }
3477 void GetSelectedStyleSheetSet(nsAString
& aSheetSet
);
3478 void SetSelectedStyleSheetSet(const nsAString
& aSheetSet
);
3479 void GetLastStyleSheetSet(nsAString
& aSheetSet
) {
3480 aSheetSet
= mLastStyleSheetSet
;
3482 const nsString
& GetCurrentStyleSheetSet() const {
3483 return mLastStyleSheetSet
.IsEmpty() ? mPreferredStyleSheetSet
3484 : mLastStyleSheetSet
;
3486 void SetPreferredStyleSheetSet(const nsAString
&);
3487 void GetPreferredStyleSheetSet(nsAString
& aSheetSet
) {
3488 aSheetSet
= mPreferredStyleSheetSet
;
3490 DOMStringList
* StyleSheetSets();
3491 void EnableStyleSheetsForSet(const nsAString
& aSheetSet
);
3494 * Retrieve the location of the caret position (DOM node and character
3495 * offset within that node), given a point.
3497 * @param aX Horizontal point at which to determine the caret position, in
3499 * @param aY Vertical point at which to determine the caret position, in
3502 already_AddRefed
<nsDOMCaretPosition
> CaretPositionFromPoint(
3503 float aX
, float aY
, const CaretPositionFromPointOptions
& aOptions
);
3505 Element
* GetScrollingElement();
3506 // A way to check whether a given element is what would get returned from
3507 // GetScrollingElement. It can be faster than comparing to the return value
3508 // of GetScrollingElement() due to being able to avoid flushes in various
3509 // cases. This method assumes that null is NOT passed.
3510 bool IsScrollingElement(Element
* aElement
);
3512 // QuerySelector and QuerySelectorAll already defined on nsINode
3514 UniquePtr
<XPathExpression
> CreateExpression(const nsAString
& aExpression
,
3515 XPathNSResolver
* aResolver
,
3517 nsINode
* CreateNSResolver(nsINode
& aNodeResolver
);
3518 already_AddRefed
<XPathResult
> Evaluate(
3519 JSContext
* aCx
, const nsAString
& aExpression
, nsINode
& aContextNode
,
3520 XPathNSResolver
* aResolver
, uint16_t aType
, JS::Handle
<JSObject
*> aResult
,
3522 // Touch event handlers already on nsINode
3523 already_AddRefed
<Touch
> CreateTouch(nsGlobalWindowInner
* aView
,
3524 EventTarget
* aTarget
, int32_t aIdentifier
,
3525 int32_t aPageX
, int32_t aPageY
,
3526 int32_t aScreenX
, int32_t aScreenY
,
3527 int32_t aClientX
, int32_t aClientY
,
3528 int32_t aRadiusX
, int32_t aRadiusY
,
3529 float aRotationAngle
, float aForce
);
3530 already_AddRefed
<TouchList
> CreateTouchList();
3531 already_AddRefed
<TouchList
> CreateTouchList(
3532 Touch
& aTouch
, const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3533 already_AddRefed
<TouchList
> CreateTouchList(
3534 const Sequence
<OwningNonNull
<Touch
>>& aTouches
);
3536 void SetStyleSheetChangeEventsEnabled(bool aValue
) {
3537 mStyleSheetChangeEventsEnabled
= aValue
;
3540 bool StyleSheetChangeEventsEnabled() const {
3541 return mStyleSheetChangeEventsEnabled
;
3544 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue
) {
3545 mDevToolsAnonymousAndShadowEventsEnabled
= aValue
;
3547 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3548 return mDevToolsAnonymousAndShadowEventsEnabled
;
3551 already_AddRefed
<Promise
> BlockParsing(Promise
& aPromise
,
3552 const BlockParsingOptions
& aOptions
,
3555 already_AddRefed
<nsIURI
> GetMozDocumentURIIfNotForErrorPages();
3557 Promise
* GetDocumentReadyForIdle(ErrorResult
& aRv
);
3559 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock
) {
3563 UnblockOnload(/* aFireSync = */ false);
3567 nsIDOMXULCommandDispatcher
* GetCommandDispatcher();
3568 bool HasXULBroadcastManager() const { return mXULBroadcastManager
; };
3569 void InitializeXULBroadcastManager();
3570 XULBroadcastManager
* GetXULBroadcastManager() const {
3571 return mXULBroadcastManager
;
3573 nsINode
* GetPopupRangeParent(ErrorResult
& aRv
);
3574 int32_t GetPopupRangeOffset(ErrorResult
& aRv
);
3576 bool DevToolsWatchingDOMMutations() const {
3577 return mDevToolsWatchingDOMMutations
;
3579 void SetDevToolsWatchingDOMMutations(bool aValue
);
3581 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3582 void EvaluateMediaQueriesAndReportChanges(bool aRecurse
);
3584 nsTHashSet
<RefPtr
<WakeLockSentinel
>>& ActiveWakeLocks(WakeLockType aType
);
3586 void UnlockAllWakeLocks(WakeLockType aType
);
3589 nsIHTMLCollection
* Children();
3590 uint32_t ChildElementCount();
3593 * Asserts IsHTMLOrXHTML, and can't return null.
3594 * Defined inline in nsHTMLDocument.h
3596 inline nsHTMLDocument
* AsHTMLDocument();
3597 inline const nsHTMLDocument
* AsHTMLDocument() const;
3600 * Asserts IsSVGDocument, and can't return null.
3601 * Defined inline in SVGDocument.h
3603 inline SVGDocument
* AsSVGDocument();
3604 inline const SVGDocument
* AsSVGDocument() const;
3607 * Asserts IsImageDocument, and can't return null.
3608 * Defined inline in ImageDocument.h
3610 inline ImageDocument
* AsImageDocument();
3611 inline const ImageDocument
* AsImageDocument() const;
3613 gfxUserFontSet
* GetUserFontSet();
3614 void FlushUserFontSet();
3615 void MarkUserFontSetDirty();
3616 FontFaceSet
* GetFonts() { return mFontFaceSet
; }
3619 FontFaceSet
* GetFonts(ErrorResult
&) { return Fonts(); }
3620 FontFaceSet
* Fonts();
3622 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded
; }
3624 bool IsSynthesized();
3626 // Records whether we will track use counters for this document, and if so,
3627 // which top-level document that page counters will be accumulated to.
3629 // Informs the parent process that page use counters will be sent once the
3630 // document goes away.
3631 void InitUseCounters();
3633 // Reports document use counters via telemetry. This method only has an
3634 // effect once per document, and so is called during document destruction.
3635 void ReportDocumentUseCounters();
3637 // Reports largest contentful paint via telemetry. We want the most up to
3638 // date value for LCP and so this is called during document destruction.
3641 // Report how lazyload performs for this document.
3642 void ReportDocumentLazyLoadCounters();
3644 // Sends page use counters to the parent process to accumulate against the
3645 // top-level document. Must be called while we still have access to our
3646 // WindowContext. This method has an effect each time it is called, and we
3647 // call it just before the document loses its window.
3648 void SendPageUseCounters();
3650 void SetUseCounter(UseCounter aUseCounter
) {
3651 mUseCounters
[aUseCounter
] = true;
3654 bool HasUseCounter(UseCounter aUseCounter
) const {
3655 return mUseCounters
[aUseCounter
];
3658 const StyleUseCounters
* GetStyleUseCounters() {
3659 return mStyleUseCounters
.get();
3662 // Propagate our use counters explicitly into the specified referencing
3665 // This is used for SVG image documents, which cannot be enumerated in the
3666 // referencing document's ReportUseCounters() like external resource documents
3668 void PropagateImageUseCounters(Document
* aReferencingDocument
);
3670 // Called to track whether this document has had any interaction.
3671 // This is used to track whether we should permit "beforeunload".
3672 void SetUserHasInteracted();
3673 bool UserHasInteracted() { return mUserHasInteracted
; }
3674 void ResetUserInteractionTimer();
3676 // Whether we're cloning the contents of an SVG use element.
3677 bool CloningForSVGUse() const { return mCloningForSVGUse
; }
3679 // If this is true, we're ignoring scrolling to a fragment.
3680 bool ForceLoadAtTop() const { return mForceLoadAtTop
; }
3682 // https://html.spec.whatwg.org/#concept-document-fire-mutation-events-flag
3683 bool FireMutationEvents() const { return mFireMutationEvents
; }
3684 void SetFireMutationEvents(bool aFire
) { mFireMutationEvents
= aFire
; }
3686 // https://w3c.github.io/trusted-types/dist/spec/#require-trusted-types-for-csp-directive
3687 bool HasPolicyWithRequireTrustedTypesForDirective() const {
3688 return mHasPolicyWithRequireTrustedTypesForDirective
;
3690 void SetHasPolicyWithRequireTrustedTypesForDirective(
3691 bool aHasPolicyWithRequireTrustedTypesForDirective
) {
3692 mHasPolicyWithRequireTrustedTypesForDirective
=
3693 aHasPolicyWithRequireTrustedTypesForDirective
;
3695 bool IsClipboardCopyTriggered() const { return mClipboardCopyTriggered
; }
3696 void ClearClipboardCopyTriggered() { mClipboardCopyTriggered
= false; }
3697 void SetClipboardCopyTriggered() { mClipboardCopyTriggered
= true; }
3699 // Even if mutation events are disabled by default,
3700 // dom.mutation_events.forceEnable can be used to enable them per site.
3701 bool MutationEventsEnabled();
3703 // This should be called when this document receives events which are likely
3704 // to be user interaction with the document, rather than the byproduct of
3705 // interaction with the browser (i.e. a keypress to scroll the view port,
3706 // keyboard shortcuts, etc). This is used to decide whether we should
3707 // permit autoplay audible media. This also gesture activates all other
3708 // content documents in this tab.
3709 void NotifyUserGestureActivation(
3710 UserActivation::Modifiers aModifiers
= UserActivation::Modifiers::None());
3712 // This function is used for mochitest only.
3713 void ClearUserGestureActivation();
3715 // Return true if NotifyUserGestureActivation() has been called on any
3716 // document in the document tree.
3717 bool HasBeenUserGestureActivated();
3719 // Returns true if this document was loaded with an user interaction,
3720 // allowing a text directive to be scrolled to if the document was loaded with
3721 // a text fragment. This call consumes this flag, ie. a subsequent call will
3723 bool ConsumeTextDirectiveUserActivation();
3725 // Reture timestamp of last user gesture in milliseconds relative to
3726 // navigation start timestamp.
3727 DOMHighResTimeStamp
LastUserGestureTimeStamp();
3729 // Return true if there is transient user gesture activation and it hasn't yet
3730 // timed out or hasn't been consumed.
3731 bool HasValidTransientUserGestureActivation() const;
3733 // Return true if HasValidTransientUserGestureActivation() would return true,
3734 // and consume the activation.
3735 bool ConsumeTransientUserGestureActivation();
3737 bool GetTransientUserGestureActivationModifiers(
3738 UserActivation::Modifiers
* aModifiers
);
3740 BrowsingContext
* GetBrowsingContext() const;
3742 // This document is a WebExtension page, it might be a background page, a
3743 // popup, a visible tab, a visible iframe ...e.t.c.
3744 bool IsExtensionPage() const;
3746 bool HasScriptsBlockedBySandbox() const;
3748 void ReportHasScrollLinkedEffect(const TimeStamp
& aTimeStamp
);
3749 bool HasScrollLinkedEffect() const;
3752 void AssertDocGroupMatchesKey() const;
3755 DocGroup
* GetDocGroup() const {
3757 AssertDocGroupMatchesKey();
3762 DocGroup
* GetDocGroupOrCreate();
3765 * If we're a sub-document, the parent document's layout can affect our style
3766 * and layout (due to the viewport size, viewport units, media queries...).
3768 * This function returns true if our parent document and our child document
3769 * can observe each other. If they cannot, then we don't need to synchronously
3770 * update the parent document layout every time the child document may need
3771 * up-to-date layout information.
3773 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3774 return GetInProcessParentDocument() &&
3775 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3778 void AddIntersectionObserver(DOMIntersectionObserver
& aObserver
) {
3779 MOZ_ASSERT(!mIntersectionObservers
.Contains(&aObserver
),
3780 "Intersection observer already in the list");
3781 mIntersectionObservers
.AppendElement(&aObserver
);
3783 void RemoveIntersectionObserver(DOMIntersectionObserver
& aObserver
) {
3784 // TODO(emilio): This can fail during unlink because Document unlink clears
3785 // the IntersectionObserver array, but it seems it wouldn't need to?
3786 // MOZ_ASSERT(mIntersectionObservers.Contains(&aObserver));
3787 mIntersectionObservers
.RemoveElement(&aObserver
);
3789 bool HasIntersectionObservers() const {
3790 return !mIntersectionObservers
.IsEmpty();
3793 // Update intersection observers in this document and all
3794 // same-process subdocuments.
3795 void UpdateIntersections(TimeStamp aNowTime
);
3796 // Update the EffectsInfo of remote browsers.
3797 void UpdateRemoteFrameEffects(bool aIncludeInactive
= false);
3798 MOZ_CAN_RUN_SCRIPT
void NotifyIntersectionObservers();
3800 DOMIntersectionObserver
* GetLazyLoadObserver() { return mLazyLoadObserver
; }
3801 DOMIntersectionObserver
& EnsureLazyLoadObserver();
3803 bool HasElementsWithLastRememberedSize() const {
3804 return !mElementsObservedForLastRememberedSize
.IsEmpty();
3806 void ObserveForLastRememberedSize(Element
&);
3807 void UnobserveForLastRememberedSize(Element
&);
3808 void UpdateLastRememberedSizes();
3810 // Dispatch a runnable related to the document.
3811 nsresult
Dispatch(already_AddRefed
<nsIRunnable
>&& aRunnable
) const;
3813 // The URLs passed to this function should match what
3814 // JS::DescribeScriptedCaller() returns, since this API is used to
3815 // determine whether some code is being called from a tracking script.
3816 void NoteScriptTrackingStatus(const nsACString
& aURL
, bool isTracking
);
3817 // The JSContext passed to this method represents the context that we want to
3818 // determine if it belongs to a tracker.
3819 bool IsScriptTracking(JSContext
* aCx
) const;
3821 // ResizeObserver usage.
3822 void AddResizeObserver(ResizeObserver
& aObserver
) {
3823 MOZ_ASSERT(!mResizeObservers
.Contains(&aObserver
));
3824 mResizeObservers
.AppendElement(&aObserver
);
3826 void RemoveResizeObserver(ResizeObserver
& aObserver
) {
3827 MOZ_ASSERT(mResizeObservers
.Contains(&aObserver
));
3828 mResizeObservers
.RemoveElement(&aObserver
);
3830 bool HasResizeObservers() const { return !mResizeObservers
.IsEmpty(); }
3832 void ScheduleResizeObserversNotification() const;
3834 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3835 * All observations in each ResizeObserver with element's depth more than
3836 * aDepth will be gathered.
3838 void GatherAllActiveResizeObservations(uint32_t aDepth
);
3840 * Calls BroadcastActiveObservations() for all ResizeObservers.
3841 * It also returns the shallowest depth of observed target elements with
3842 * active observations from all ResizeObservers or
3843 * numeric_limits<uint32_t>::max() if there aren't any active observations
3846 MOZ_CAN_RUN_SCRIPT
uint32_t BroadcastAllActiveResizeObservations();
3848 * Returns whether there is any ResizeObserver that has active
3851 bool HasAnyActiveResizeObservations() const;
3853 * Returns whether there is any ResizeObserver that has skipped observations.
3855 bool HasAnySkippedResizeObservations() const;
3857 * Determine proximity to viewport for content-visibility: auto elements and
3858 * notify resize observers.
3860 MOZ_CAN_RUN_SCRIPT
void
3861 DetermineProximityToViewportAndNotifyResizeObservers();
3863 already_AddRefed
<ViewTransition
> StartViewTransition(
3864 const Optional
<OwningNonNull
<ViewTransitionUpdateCallback
>>&);
3865 ViewTransition
* GetActiveViewTransition() const {
3866 return mActiveViewTransition
;
3868 void ClearActiveViewTransition();
3869 void PerformPendingViewTransitionOperations();
3870 void EnsureViewTransitionOperationsHappen();
3872 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3873 PermissionDelegateHandler
* GetPermissionDelegateHandler();
3875 // Notify the document that a fetch or a XHR request has completed
3876 // succesfully in this document. This is used by the password manager to infer
3877 // whether a form is submitted.
3878 void NotifyFetchOrXHRSuccess();
3880 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3881 void SetNotifyFetchSuccess(bool aShouldNotify
);
3883 // When this is set, removing a form or a password field from DOM
3884 // sends a Chrome-only event. This is now only used by the password manager
3885 // and formautofill.
3886 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify
);
3888 // This function is used by HTMLFormElement and HTMLInputElement to determin
3889 // whether to send an event when it is removed from DOM.
3890 bool ShouldNotifyFormOrPasswordRemoved() const {
3891 return mShouldNotifyFormOrPasswordRemoved
;
3894 HTMLEditor
* GetHTMLEditor() const;
3899 * For more information on DocumentL10n see
3900 * intl/l10n/docs/fluent/tutorial.rst
3905 * This is a public method exposed on Document WebIDL
3906 * to chrome only documents.
3908 DocumentL10n
* GetL10n() const { return mDocumentL10n
.get(); }
3911 * Whether there's any async l10n mutation work pending.
3913 * When this turns false, we fire the L10nMutationsFinished event.
3915 bool HasPendingL10nMutations() const;
3918 * This method should be called when the container
3919 * of l10n resources parsing is completed.
3921 * It triggers initial async fetch of the resources
3922 * as early as possible.
3924 * In HTML case this is </head>.
3925 * In XUL case this is </linkset>.
3927 void OnL10nResourceContainerParsed();
3930 * This method should be called when a link element
3931 * with rel="localization" is being added to the
3932 * l10n resource container element.
3934 void LocalizationLinkAdded(Element
* aLinkElement
);
3937 * This method should be called when a link element
3938 * with rel="localization" is being removed.
3940 void LocalizationLinkRemoved(Element
* aLinkElement
);
3943 * This method should be called as soon as the
3944 * parsing of the document is completed.
3946 * In HTML/XHTML this happens when we finish parsing
3947 * the document element.
3948 * In XUL it happens at `DoneWalking`, during
3949 * `MozBeforeInitialXULLayout`.
3951 void OnParsingCompleted();
3954 * This method is called when the initial translation
3955 * of the document is completed.
3957 * It unblocks the load event if translation was blocking it.
3959 * If the `aL10nCached` is set to `true`, and the document has
3960 * a prototype, it will set the `isL10nCached` flag on it.
3962 void InitialTranslationCompleted(bool aL10nCached
);
3965 * Returns whether the document allows localization.
3967 bool AllowsL10n() const;
3969 void SetAllowDeclarativeShadowRoots(bool aAllowDeclarativeShadowRoots
);
3970 bool AllowsDeclarativeShadowRoots() const;
3972 void SuspendDOMNotifications() {
3973 MOZ_ASSERT(IsHTMLDocument(),
3974 "Currently suspending DOM notifications is supported only on "
3976 mSuspendDOMNotifications
= true;
3979 void ResumeDOMNotifications() { mSuspendDOMNotifications
= false; }
3981 bool DOMNotificationsSuspended() const { return mSuspendDOMNotifications
; }
3984 RefPtr
<DocumentL10n
> mDocumentL10n
;
3987 * Return true when you want a document without explicitly specified viewport
3988 * dimensions/scale to be treated as if "width=device-width" had in fact been
3991 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3994 bool IsErrorPage() const;
3996 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3998 void SetCssUseCounterBits();
4000 void ParseWidthAndHeightInMetaViewport(const nsAString
& aWidthString
,
4001 const nsAString
& aHeightString
,
4004 // Parse scale values in viewport meta tag for a given |aHeaderField| which
4005 // represents the scale property and returns the scale value if it's valid.
4006 Maybe
<LayoutDeviceToScreenScale
> ParseScaleInHeader(nsAtom
* aHeaderField
);
4008 // Parse scale values in |aViewportMetaData| and set the values in
4009 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
4010 void ParseScalesInViewportMetaData(const ViewportMetaData
& aViewportMetaData
);
4012 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
4013 // stored in parent iframe or container's browsingContext (cross process)
4014 already_AddRefed
<mozilla::dom::FeaturePolicy
> GetParentFeaturePolicy();
4017 const OriginTrials
& Trials() const { return mTrials
; }
4019 dom::InteractiveWidget
InteractiveWidget() const {
4020 return mInteractiveWidgetMode
;
4024 void DoCacheAllKnownLangPrefs();
4025 void RecomputeLanguageFromCharset();
4026 bool GetSHEntryHasUserInteraction();
4028 void AppendAutoFocusCandidateToTopDocument(Element
* aAutoFocusCandidate
);
4031 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate
= true; }
4033 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate
; }
4035 void SetSHEntryHasUserInteraction(bool aHasInteraction
);
4037 nsAtom
* GetContentLanguageAsAtomForStyle() const;
4038 nsAtom
* GetLanguageForStyle() const;
4041 * Fetch the user's font preferences for the given aLanguage's
4044 const LangGroupFontPrefs
* GetFontPrefsForLang(
4045 nsAtom
* aLanguage
, bool* aNeedsToCache
= nullptr) const;
4047 void ForceCacheLang(nsAtom
* aLanguage
) {
4048 if (!mLanguagesUsed
.EnsureInserted(aLanguage
)) {
4051 GetFontPrefsForLang(aLanguage
);
4054 void CacheAllKnownLangPrefs() {
4055 if (!mMayNeedFontPrefsUpdate
) {
4058 DoCacheAllKnownLangPrefs();
4061 nsINode
* GetServoRestyleRoot() const { return mServoRestyleRoot
; }
4063 uint32_t GetServoRestyleRootDirtyBits() const {
4064 MOZ_ASSERT(mServoRestyleRoot
);
4065 MOZ_ASSERT(mServoRestyleRootDirtyBits
);
4066 return mServoRestyleRootDirtyBits
;
4069 void ClearServoRestyleRoot() {
4070 mServoRestyleRoot
= nullptr;
4071 mServoRestyleRootDirtyBits
= 0;
4074 inline void SetServoRestyleRoot(nsINode
* aRoot
, uint32_t aDirtyBits
);
4075 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits
);
4077 bool ShouldThrowOnDynamicMarkupInsertion() {
4078 return mThrowOnDynamicMarkupInsertionCounter
;
4081 void IncrementThrowOnDynamicMarkupInsertionCounter() {
4082 ++mThrowOnDynamicMarkupInsertionCounter
;
4085 void DecrementThrowOnDynamicMarkupInsertionCounter() {
4086 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter
);
4087 --mThrowOnDynamicMarkupInsertionCounter
;
4090 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter
; }
4092 void IncrementIgnoreOpensDuringUnloadCounter() {
4093 ++mIgnoreOpensDuringUnloadCounter
;
4096 void DecrementIgnoreOpensDuringUnloadCounter() {
4097 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter
);
4098 --mIgnoreOpensDuringUnloadCounter
;
4101 mozilla::dom::FeaturePolicy
* FeaturePolicy() const;
4104 * Find the (non-anonymous) content in this document for aFrame. It will
4105 * be aFrame's content node if that content is in this document and not
4106 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4107 * element containing the subdocument containing aFrame, and/or find the
4108 * nearest non-anonymous ancestor in this document.
4109 * Returns null if there is no such element.
4111 nsIContent
* GetContentInThisDocument(nsIFrame
* aFrame
) const;
4113 void ReportShadowDOMUsage();
4115 // Sets flags for media telemetry.
4116 void SetDocTreeHadMedia();
4118 dom::XPathEvaluator
* XPathEvaluator();
4120 void MaybeInitializeFinalizeFrameLoaders();
4122 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization
) {
4123 mDelayFrameLoaderInitialization
= aDelayFrameLoaderInitialization
;
4126 void SetPrototypeDocument(nsXULPrototypeDocument
* aPrototype
);
4128 nsIPermissionDelegateHandler
* PermDelegateHandler();
4130 // Returns whether this is a top-level about:blank page without an opener (and
4131 // thus likely not accessible by content). Likely because it shouldn't be used
4132 // for security checks for example, see bug 1860098.
4133 bool IsLikelyContentInaccessibleTopLevelAboutBlank() const;
4135 // CSS prefers-color-scheme media feature for this document.
4136 enum class IgnoreRFP
{ No
, Yes
};
4137 ColorScheme
PreferredColorScheme(IgnoreRFP
= IgnoreRFP::No
) const;
4138 // Returns the initial color-scheme used for this document based on the
4139 // color-scheme meta tag.
4140 ColorScheme
DefaultColorScheme() const;
4142 static bool HasRecentlyStartedForegroundLoads();
4144 static bool AutomaticStorageAccessPermissionCanBeGranted(
4145 nsIPrincipal
* aPrincipal
);
4147 already_AddRefed
<Promise
> AddCertException(bool aIsTemporary
,
4148 ErrorResult
& aError
);
4150 void ReloadWithHttpsOnlyException();
4152 // Subframes need to be static cloned after the main document has been
4153 // embedded within a script global. A `PendingFrameStaticClone` is a static
4154 // clone which has not yet been performed.
4156 // The getter returns a direct reference to an internal array which is
4157 // manipulated from within printing code.
4158 struct PendingFrameStaticClone
{
4159 PendingFrameStaticClone() = default;
4160 PendingFrameStaticClone(PendingFrameStaticClone
&&) = default;
4161 PendingFrameStaticClone
& operator=(PendingFrameStaticClone
&&) = default;
4162 ~PendingFrameStaticClone();
4164 RefPtr
<nsFrameLoaderOwner
> mElement
;
4165 RefPtr
<nsFrameLoader
> mStaticCloneOf
;
4167 void AddPendingFrameStaticClone(nsFrameLoaderOwner
* aElement
,
4168 nsFrameLoader
* aStaticCloneOf
);
4170 bool ShouldAvoidNativeTheme() const;
4172 static bool IsValidDomain(nsIURI
* aOrigHost
, nsIURI
* aNewURI
);
4174 // Inform a parent document that a BrowserBridgeChild has been created for
4175 // an OOP sub-document.
4176 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4177 void OOPChildLoadStarted(BrowserBridgeChild
* aChild
);
4179 // Inform a parent document that the BrowserBridgeChild for one of its
4180 // OOP sub-documents is done calling its onload handler.
4181 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4182 void OOPChildLoadDone(BrowserBridgeChild
* aChild
);
4184 void ClearOOPChildrenLoading();
4186 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading
.IsEmpty(); }
4188 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache
= true; }
4190 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache
; }
4193 * Get the `HighlightRegistry` which contains all highlights associated
4194 * with this document.
4196 class HighlightRegistry
& HighlightRegistry();
4199 * @brief Returns the `FragmentDirective` object which contains information
4200 * and functionality to extract or create text directives.
4201 * Guaranteed to be non-null.
4203 class FragmentDirective
* FragmentDirective();
4205 bool ShouldResistFingerprinting(RFPTarget aTarget
) const;
4206 bool IsInPrivateBrowsing() const;
4208 const Maybe
<RFPTargetSet
>& GetOverriddenFingerprintingSettings() const {
4209 return mOverriddenFingerprintingSettings
;
4212 // Recompute the current resist fingerprinting state. Returns true when
4213 // the state was changed.
4214 bool RecomputeResistFingerprinting();
4216 // Recompute the partitionKey for this document if needed. This is for
4217 // handling the case where the principal of the document is changed during the
4218 // loading, e.g. a sandboxed document. We only need to recompute for the
4219 // top-level content document.
4220 void MaybeRecomputePartitionKey();
4222 void RecordCanvasUsage(CanvasUsage
& aUsage
);
4223 void RecordFontFingerprinting();
4225 bool MayHaveDOMActivateListeners() const;
4227 void DropStyleSet();
4230 // Returns the WindowContext for the document that we will contribute
4231 // page use counters to.
4232 WindowContext
* GetWindowContextForPageUseCounters() const;
4234 void DoUpdateSVGUseElementShadowTrees();
4236 already_AddRefed
<nsIPrincipal
> MaybeDowngradePrincipal(
4237 nsIPrincipal
* aPrincipal
);
4239 void EnsureOnloadBlocker();
4241 void SendToConsole(nsCOMArray
<nsISecurityConsoleMessage
>& aMessages
);
4243 // Returns true if the scheme for the url for this document is "about".
4244 bool IsAboutPage() const;
4246 bool ContainsEMEContent();
4247 bool ContainsMSEContent();
4250 * Returns the title element of the document as defined by the HTML
4251 * specification, or null if there isn't one. For documents whose root
4252 * element is an <svg:svg>, this is the first <svg:title> element that's a
4253 * child of the root. For other documents, it's the first HTML title element
4256 Element
* GetTitleElement();
4258 void RecordNavigationTiming(ReadyState aReadyState
);
4260 // Recomputes the visibility state but doesn't set the new value.
4261 dom::VisibilityState
ComputeVisibilityState() const;
4263 // Since we wouldn't automatically play media from non-visited page, we need
4264 // to notify window when the page was first visited.
4265 void MaybeActiveMediaComponents();
4267 // Apply the fullscreen state to the document, and trigger related
4268 // events. It returns false if the fullscreen element ready check
4269 // fails and nothing gets changed.
4270 MOZ_CAN_RUN_SCRIPT_BOUNDARY
bool ApplyFullscreen(
4271 UniquePtr
<FullscreenRequest
>);
4273 void RemoveDocStyleSheetsFromStyleSets();
4274 void ResetStylesheetsToURI(nsIURI
* aURI
);
4275 void FillStyleSet();
4276 void FillStyleSetUserAndUASheets();
4277 void FillStyleSetDocumentSheets();
4278 void CompatibilityModeChanged();
4279 bool NeedsQuirksSheet() const {
4280 // SVG documents never load quirk.css.
4281 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4282 return mCompatMode
== eCompatibility_NavQuirks
&& !IsSVGDocument();
4284 void AddStyleSheetToStyleSets(StyleSheet
&);
4285 void RemoveStyleSheetFromStyleSets(StyleSheet
&);
4286 void NotifyStyleSheetApplicableStateChanged();
4287 // Just like EnableStyleSheetsForSet, but doesn't check whether
4288 // aSheetSet is null and allows the caller to control whether to set
4289 // aSheetSet as the preferred set in the CSSLoader.
4290 void EnableStyleSheetsForSetInternal(const nsAString
& aSheetSet
,
4291 bool aUpdateCSSLoader
);
4293 already_AddRefed
<nsIURI
> GetDomainURI();
4294 already_AddRefed
<nsIURI
> CreateInheritingURIForHost(
4295 const nsACString
& aHostString
);
4296 already_AddRefed
<nsIURI
> RegistrableDomainSuffixOfInternal(
4297 const nsAString
& aHostSuffixString
, nsIURI
* aOrigHost
);
4299 MOZ_CAN_RUN_SCRIPT
void WriteCommon(const nsAString
& aText
,
4300 bool aNewlineTerminate
, bool aIsTrusted
,
4301 mozilla::ErrorResult
& aRv
);
4302 // A version of WriteCommon used by WebIDL bindings
4303 MOZ_CAN_RUN_SCRIPT
void WriteCommon(
4304 const mozilla::dom::Sequence
<OwningTrustedHTMLOrString
>& aText
,
4305 bool aNewlineTerminate
, mozilla::ErrorResult
& rv
);
4307 void* GenerateParserKey(void);
4310 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4312 enum class ExecCommandParam
: uint8_t {
4313 // Always ignore it.
4315 // Treat the given parameter as-is. If the command requires it, use it.
4316 // Otherwise, ignore it.
4318 // Always treat it as boolean parameter.
4320 // Always treat it as boolean, but inverted.
4324 using GetEditorCommandFunc
= mozilla::EditorCommand
*();
4326 struct InternalCommandData
{
4327 const char* mXULCommandName
;
4328 mozilla::Command mCommand
; // uint8_t
4329 // How ConvertToInternalCommand() to treats aValue.
4330 // Its callers don't need to check this.
4331 ExecCommandParam mExecCommandParam
; // uint8_t
4332 GetEditorCommandFunc
* mGetEditorCommandFunc
;
4333 enum class CommandOnTextEditor
: uint8_t {
4336 FallThrough
, // Not disabled, but handled by HTMLEditor if there is one
4338 CommandOnTextEditor mCommandOnTextEditor
;
4340 InternalCommandData()
4341 : mXULCommandName(nullptr),
4342 mCommand(mozilla::Command::DoNothing
),
4343 mExecCommandParam(ExecCommandParam::Ignore
),
4344 mGetEditorCommandFunc(nullptr),
4345 mCommandOnTextEditor(CommandOnTextEditor::Disabled
) {}
4346 InternalCommandData(const char* aXULCommandName
, mozilla::Command aCommand
,
4347 ExecCommandParam aExecCommandParam
,
4348 GetEditorCommandFunc aGetEditorCommandFunc
,
4349 CommandOnTextEditor aCommandOnTextEditor
)
4350 : mXULCommandName(aXULCommandName
),
4352 mExecCommandParam(aExecCommandParam
),
4353 mGetEditorCommandFunc(aGetEditorCommandFunc
),
4354 mCommandOnTextEditor(aCommandOnTextEditor
) {}
4356 bool IsAvailableOnlyWhenEditable() const {
4357 return mCommand
!= mozilla::Command::Cut
&&
4358 mCommand
!= mozilla::Command::Copy
&&
4359 mCommand
!= mozilla::Command::Paste
&&
4360 mCommand
!= mozilla::Command::SetDocumentReadOnly
&&
4361 mCommand
!= mozilla::Command::SelectAll
;
4363 bool IsCutOrCopyCommand() const {
4364 return mCommand
== mozilla::Command::Cut
||
4365 mCommand
== mozilla::Command::Copy
;
4367 bool IsPasteCommand() const { return mCommand
== mozilla::Command::Paste
; }
4371 * AutoEditorCommandTarget considers which editor or global command manager
4372 * handles given command.
4374 class MOZ_RAII AutoEditorCommandTarget
{
4376 MOZ_CAN_RUN_SCRIPT
AutoEditorCommandTarget(
4377 Document
& aDocument
, const InternalCommandData
& aCommandData
);
4378 AutoEditorCommandTarget() = delete;
4379 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget
& aOther
) =
4382 bool DoNothing() const { return mDoNothing
; }
4383 MOZ_CAN_RUN_SCRIPT
bool IsEditable(Document
* aDocument
) const;
4384 bool IsEditor() const {
4385 MOZ_ASSERT_IF(mEditorCommand
, mActiveEditor
|| mHTMLEditor
);
4386 return !!mEditorCommand
;
4389 MOZ_CAN_RUN_SCRIPT
bool IsCommandEnabled() const;
4390 MOZ_CAN_RUN_SCRIPT nsresult
DoCommand(nsIPrincipal
* aPrincipal
) const;
4391 template <typename ParamType
>
4392 MOZ_CAN_RUN_SCRIPT nsresult
DoCommandParam(const ParamType
& aParam
,
4393 nsIPrincipal
* aPrincipal
) const;
4394 MOZ_CAN_RUN_SCRIPT nsresult
4395 GetCommandStateParams(nsCommandParams
& aParams
) const;
4397 // The returned editor's life is guaranteed while this instance is alive.
4398 EditorBase
* GetTargetEditor() const;
4401 RefPtr
<EditorBase
> mActiveEditor
;
4402 RefPtr
<HTMLEditor
> mHTMLEditor
;
4403 RefPtr
<EditorCommand
> mEditorCommand
;
4404 const InternalCommandData
& mCommandData
;
4405 bool mDoNothing
= false;
4409 * Helper method to initialize sInternalCommandDataHashtable.
4411 static void EnsureInitializeInternalCommandDataHashtable();
4414 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4415 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4416 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4417 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4418 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4419 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4420 * returns a copy of instance created with default constructor. I.e., its
4421 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4422 * is unsupported in such case.
4424 * @param aHTMLCommandName Command name in HTML, e.g., used by
4426 * @param aValue The value which is set to the 3rd parameter
4428 * @param aRv ErrorResult used for Trusted Type conversion.
4429 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4430 * Will be set to adjusted value for executing
4431 * the internal command.
4432 * @return Returns a copy of instance created with the
4433 * default constructor if there is no
4434 * corresponding internal command for
4435 * aHTMLCommandName or aValue is invalid for
4436 * found internal command when aAdjustedValue
4437 * is not nullptr. Otherwise, returns a copy of
4438 * instance registered in
4439 * sInternalCommandDataHashtable.
4441 MOZ_CAN_RUN_SCRIPT InternalCommandData
ConvertToInternalCommand(
4442 const nsAString
& aHTMLCommandName
,
4443 const TrustedHTMLOrString
* aValue
= nullptr, ErrorResult
* aRv
= nullptr,
4444 nsAString
* aAdjustedValue
= nullptr);
4447 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4448 * Since it's a bit field, not a bool member, therefore, we cannot use
4449 * AutoRestorer for it.
4451 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final
{
4453 AutoRunningExecCommandMarker() = delete;
4454 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker
&) =
4456 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4457 MOZ_CAN_RUN_SCRIPT
AutoRunningExecCommandMarker(Document
& aDocument
,
4458 nsIPrincipal
* aPrincipal
);
4459 ~AutoRunningExecCommandMarker() {
4460 if (mTreatAsUserInput
) {
4461 mDocument
.mIsRunningExecCommandByChromeOrAddon
=
4462 mHasBeenRunningByChromeOrAddon
;
4464 mDocument
.mIsRunningExecCommandByContent
= mHasBeenRunningByContent
;
4468 [[nodiscard
]] bool IsSafeToRun() const {
4469 // We don't allow nested calls of execCommand even if the caller is chrome
4471 if (mTreatAsUserInput
) {
4472 return !mHasBeenRunningByChromeOrAddon
&& !mHasBeenRunningByContent
;
4474 // If current call is by content, we should ignore whether nested with a
4475 // call by addon (or chrome script) because the caller wants to emulate
4476 // user input for making it undoable. So, we should treat the first
4477 // call as user input.
4478 return !mHasBeenRunningByContent
;
4482 Document
& mDocument
;
4483 bool mTreatAsUserInput
;
4484 bool mHasBeenRunningByContent
;
4485 bool mHasBeenRunningByChromeOrAddon
;
4488 // Mapping table from HTML command name to internal command.
4489 using InternalCommandDataHashtable
=
4490 nsTHashMap
<nsStringCaseInsensitiveHashKey
, InternalCommandData
>;
4491 static InternalCommandDataHashtable
* sInternalCommandDataHashtable
;
4493 mutable std::bitset
<static_cast<size_t>(
4494 DeprecatedOperations::eDeprecatedOperationCount
)>
4495 mDeprecationWarnedAbout
;
4496 mutable std::bitset
<eDocumentWarningCount
> mDocWarningWarnedAbout
;
4498 // Lazy-initialization to have mDocGroup initialized in prior to the
4499 UniquePtr
<ServoStyleSet
> mStyleSet
;
4502 // Never ever call this. Only call GetWindow!
4503 nsPIDOMWindowOuter
* GetWindowInternal() const;
4505 // Never ever call this. Only call GetScriptHandlingObject!
4506 nsIScriptGlobalObject
* GetScriptHandlingObjectInternal() const;
4508 // Never ever call this. Only call AllowXULXBL!
4509 bool InternalAllowXULXBL();
4512 * These methods should be called before and after dispatching
4514 * To make this easy and painless, use the mozAutoSubtreeModified helper
4517 void WillDispatchMutationEvent(nsINode
* aTarget
);
4518 void MutationEventDispatched(nsINode
* aTarget
);
4519 friend class mozAutoSubtreeModified
;
4521 virtual Element
* GetNameSpaceElement() override
{ return GetRootElement(); }
4523 nsCString
GetContentTypeInternal() const { return mContentType
; }
4525 // Helper for GetScrollingElement/IsScrollingElement.
4526 bool IsPotentiallyScrollable(HTMLBodyElement
* aBody
);
4528 void MaybeAllowStorageForOpenerAfterUserInteraction();
4530 void MaybeStoreUserInteractionAsPermission();
4532 // Helpers for GetElementsByName.
4533 static bool MatchNameAttribute(Element
* aElement
, int32_t aNamespaceID
,
4534 nsAtom
* aAtom
, void* aData
);
4535 static void* UseExistingNameString(nsINode
* aRootNode
, const nsString
* aName
);
4537 void MaybeResolveReadyForIdle();
4539 using AutomaticStorageAccessPermissionGrantPromise
=
4540 MozPromise
<bool, bool, true>;
4541 [[nodiscard
]] RefPtr
<AutomaticStorageAccessPermissionGrantPromise
>
4542 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation
,
4543 bool aIsThirdPartyTracker
);
4545 static void AddToplevelLoadingDocument(Document
* aDoc
);
4546 static void RemoveToplevelLoadingDocument(Document
* aDoc
);
4547 static AutoTArray
<Document
*, 8>* sLoadingForegroundTopLevelContentDocument
;
4548 friend class cycleCollection
;
4550 nsCOMPtr
<nsIReferrerInfo
> mPreloadReferrerInfo
;
4551 nsCOMPtr
<nsIReferrerInfo
> mReferrerInfo
;
4553 nsString mLastModified
;
4555 nsCOMPtr
<nsIURI
> mDocumentURI
;
4556 nsCOMPtr
<nsIURI
> mOriginalURI
;
4557 nsCOMPtr
<nsIURI
> mChromeXHRDocURI
;
4558 nsCOMPtr
<nsIURI
> mDocumentBaseURI
;
4559 nsCOMPtr
<nsIURI
> mChromeXHRDocBaseURI
;
4561 // The base domain of the document for third-party checks.
4562 nsCString mBaseDomain
;
4564 // A lazily-constructed URL data for style system to resolve URL values.
4565 RefPtr
<URLExtraData
> mCachedURLData
;
4566 nsCOMPtr
<nsIReferrerInfo
> mCachedReferrerInfoForInternalCSSAndSVGResources
;
4568 nsWeakPtr mDocumentLoadGroup
;
4570 WeakPtr
<nsDocShell
> mDocumentContainer
;
4572 NotNull
<const Encoding
*> mCharacterSet
;
4573 int32_t mCharacterSetSource
;
4575 OriginTrials mTrials
;
4577 // This is just a weak pointer; the parent document owns its children.
4578 Document
* mParentDocument
;
4580 // A reference to the element last returned from GetRootElement().
4581 Element
* mCachedRootElement
;
4583 // This is maintained by AutoSetRestoreSVGContextPaint.
4584 const SVGContextPaint
* mCurrentContextPaint
= nullptr;
4586 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4587 // which in turn holds a strong reference to this mNodeInfoManager.
4588 nsNodeInfoManager
* mNodeInfoManager
;
4589 RefPtr
<css::Loader
> mCSSLoader
;
4590 RefPtr
<css::ImageLoader
> mStyleImageLoader
;
4592 // The object that contains link color declarations (from the <body> mapped
4593 // attributes), mapped attribute caches, and inline style attribute caches.
4594 RefPtr
<AttributeStyles
> mAttributeStyles
;
4596 // Tracking for images in the document.
4597 RefPtr
<dom::ImageTracker
> mImageTracker
;
4599 // A hashtable of ShadowRoots belonging to the composed doc.
4601 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4602 ShadowRootSet mComposedShadowRoots
;
4604 using SVGUseElementSet
= nsTHashSet
<SVGUseElement
*>;
4606 // The set of <svg:use> elements that need a shadow tree reclone because the
4607 // tree they map to has changed.
4608 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate
;
4610 // The set of all object, embed, video/audio elements or
4611 // nsIObjectLoadingContent or DocumentActivity for which this is
4612 // the owner document. (They might not be in the document.)
4614 // These are non-owning pointers, the elements are responsible for removing
4615 // themselves when they go away.
4616 UniquePtr
<nsTHashSet
<nsISupports
*>> mActivityObservers
;
4618 // A hashtable of styled links keyed by address pointer.
4619 nsTHashSet
<Link
*> mStyledLinks
;
4621 // Indicates whether mStyledLinks was cleared or not. This is used to track
4622 // state so we can provide useful assertions to consumers of ForgetLink and
4623 // AddStyleRelevantLink.
4624 bool mStyledLinksCleared
;
4627 // The array of all links that need their status resolved. Links must add
4628 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4630 static const size_t kSegmentSize
= 128;
4632 using LinksToUpdateList
=
4633 SegmentedVector
<nsCOMPtr
<Link
>, kSegmentSize
, InfallibleAllocPolicy
>;
4635 LinksToUpdateList mLinksToUpdate
;
4637 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4638 RefPtr
<SMILAnimationController
> mAnimationController
;
4640 // Table of element properties for this document.
4641 nsPropertyTable mPropertyTable
;
4643 // Our cached .children collection
4644 nsCOMPtr
<nsIHTMLCollection
> mChildrenCollection
;
4646 // Various DOM lists
4647 RefPtr
<nsContentList
> mImages
;
4648 RefPtr
<nsContentList
> mEmbeds
;
4649 RefPtr
<nsContentList
> mLinks
;
4650 RefPtr
<nsContentList
> mForms
;
4651 RefPtr
<nsContentList
> mScripts
;
4652 nsCOMPtr
<nsIHTMLCollection
> mApplets
;
4653 RefPtr
<nsContentList
> mAnchors
;
4655 // container for per-context fonts (downloadable, SVG, etc.)
4656 RefPtr
<FontFaceSet
> mFontFaceSet
;
4658 // Last time this document or a one of its sub-documents was focused. If
4659 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4660 TimeStamp mLastFocusTime
;
4662 // Last time we found any scroll linked effect in this document.
4663 TimeStamp mLastScrollLinkedEffectDetectionTime
;
4665 DocumentState mState
{DocumentState::LTR_LOCALE
};
4667 RefPtr
<Promise
> mReadyForIdle
;
4669 RefPtr
<mozilla::dom::FeaturePolicy
> mFeaturePolicy
;
4671 // Permission Delegate Handler, lazily-initialized in
4672 // GetPermissionDelegateHandler
4673 RefPtr
<PermissionDelegateHandler
> mPermissionDelegateHandler
;
4675 bool mCachedStateObjectValid
: 1;
4676 bool mBlockAllMixedContent
: 1;
4677 bool mBlockAllMixedContentPreloads
: 1;
4678 bool mUpgradeInsecureRequests
: 1;
4679 bool mUpgradeInsecurePreloads
: 1;
4680 bool mDevToolsWatchingDOMMutations
: 1;
4682 // True if BIDI is enabled.
4683 bool mBidiEnabled
: 1;
4684 // True if we may need to recompute the language prefs for this document.
4685 bool mMayNeedFontPrefsUpdate
: 1;
4686 // True if a MathML element has ever been owned by this document.
4687 bool mMathMLEnabled
: 1;
4689 // True if this document is the initial document for a window. This should
4690 // basically be true only for documents that exist in newly-opened windows or
4691 // documents created to satisfy a GetDocument() on a window when there's no
4693 bool mIsInitialDocumentInWindow
: 1;
4695 // True if this document has ever been the initial document for a window. This
4696 // is useful to determine if a document that was the initial document at one
4697 // point, and became non-initial later.
4698 bool mIsEverInitialDocumentInWindow
: 1;
4700 bool mIgnoreDocGroupMismatches
: 1;
4702 // True if we're loaded as data and therefor has any dangerous stuff, such
4703 // as scripts and plugins, disabled.
4704 bool mLoadedAsData
: 1;
4706 // True if the document is considered for memory reporting as a
4708 bool mAddedToMemoryReportingAsDataDocument
: 1;
4710 // If true, whoever is creating the document has gotten it to the
4711 // point where it's safe to start layout on it.
4712 bool mMayStartLayout
: 1;
4714 // True iff we've ever fired a DOMTitleChanged event for this document
4715 bool mHaveFiredTitleChange
: 1;
4717 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4718 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4719 // before the initial load completes and when we're in bfcache or unloaded,
4721 bool mIsShowing
: 1;
4723 // State for IsVisible(). mVisible starts off true. It becomes false when
4724 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4725 // it's false only when we're in bfcache or unloaded.
4728 // True if our content viewer has been removed from the docshell
4729 // (it may still be displayed, but in zombie state). Form control data
4731 bool mRemovedFromDocShell
: 1;
4733 // True iff DNS prefetch is allowed for this document. Note that if the
4734 // document has no window, DNS prefetch won't be performed no matter what.
4735 bool mAllowDNSPrefetch
: 1;
4737 // True when this document is a static clone of a normal document
4738 bool mIsStaticDocument
: 1;
4740 // True while this document is being cloned to a static document.
4741 bool mCreatingStaticClone
: 1;
4743 // True if this static document has any <canvas> element with a
4744 // mozPrintCallback property at the time of the clone.
4745 bool mHasPrintCallbacks
: 1;
4747 // True iff the document is being unlinked or deleted.
4748 bool mInUnlinkOrDeletion
: 1;
4750 // True if document has ever had script handling object.
4751 bool mHasHadScriptHandlingObject
: 1;
4753 // True if we're an SVG document being used as an image.
4754 bool mIsBeingUsedAsImage
: 1;
4756 // True if our current document URI's scheme enables privileged CSS rules.
4757 bool mChromeRulesEnabled
: 1;
4759 // True if we're loaded in a chrome docshell.
4760 bool mInChromeDocShell
: 1;
4762 // True is this document is synthetic : stand alone image, video, audio
4764 bool mIsSyntheticDocument
: 1;
4766 // True is there is a pending runnable which will call
4767 // FlushPendingLinkUpdates().
4768 bool mHasLinksToUpdateRunnable
: 1;
4770 // True if we're flushing pending link updates.
4771 bool mFlushingPendingLinkUpdates
: 1;
4773 // True if a DOMMutationObserver is perhaps attached to a node in the
4775 bool mMayHaveDOMMutationObservers
: 1;
4777 // True if an nsIAnimationObserver is perhaps attached to a node in the
4779 bool mMayHaveAnimationObservers
: 1;
4781 // True if the document has a CSP delivered throuh a header
4782 bool mHasCSPDeliveredThroughHeader
: 1;
4784 // True if DisallowBFCaching has been called on this document.
4785 bool mBFCacheDisallowed
: 1;
4787 bool mHasHadDefaultView
: 1;
4789 // Whether style sheet change events will be dispatched for this document
4790 bool mStyleSheetChangeEventsEnabled
: 1;
4792 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4793 // will be dispatched for this document.
4794 bool mDevToolsAnonymousAndShadowEventsEnabled
: 1;
4796 // Whether the document was created by a srcdoc iframe.
4797 bool mIsSrcdocDocument
: 1;
4799 // Whether this document has a display document and thus is considered to
4800 // be a resource document. Normally this is the same as !!mDisplayDocument,
4801 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4802 // valid in the document's destructor.
4803 bool mHasDisplayDocument
: 1;
4805 // Is the current mFontFaceSet valid?
4806 bool mFontFaceSetDirty
: 1;
4808 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4809 // (e.g. we're not being parsed at all).
4810 bool mDidFireDOMContentLoaded
: 1;
4812 bool mIsTopLevelContentDocument
: 1;
4814 bool mIsContentDocument
: 1;
4816 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4817 bool mDidCallBeginLoad
: 1;
4819 // True if the encoding menu should be disabled.
4820 bool mEncodingMenuDisabled
: 1;
4822 // False if we've disabled link handling for elements inside this document,
4824 bool mLinksEnabled
: 1;
4826 // True if this document is for an SVG-in-OpenType font.
4827 bool mIsSVGGlyphsDocument
: 1;
4829 // True if the document is being destroyed.
4830 bool mInDestructor
: 1;
4832 // True if the document has been detached from its content viewer.
4833 bool mIsGoingAway
: 1;
4835 // Whether we have filled our style set with all the stylesheets.
4836 bool mStyleSetFilled
: 1;
4838 // Whether we have a quirks mode stylesheet in the style set.
4839 bool mQuirkSheetAdded
: 1;
4841 // True if this document has ever had an HTML or SVG <title> element
4843 bool mMayHaveTitleElement
: 1;
4845 bool mDOMLoadingSet
: 1;
4846 bool mDOMInteractiveSet
: 1;
4847 bool mDOMCompleteSet
: 1;
4848 bool mAutoFocusFired
: 1;
4850 bool mScrolledToRefAlready
: 1;
4851 bool mChangeScrollPosWhenScrollingToRef
: 1;
4853 bool mDelayFrameLoaderInitialization
: 1;
4855 bool mSynchronousDOMContentLoaded
: 1;
4857 // Set to true when the document is possibly controlled by the ServiceWorker.
4858 // Used to prevent multiple requests to ServiceWorkerManager.
4859 bool mMaybeServiceWorkerControlled
: 1;
4861 // These member variables cache information about the viewport so we don't
4862 // have to recalculate it each time.
4863 bool mAllowZoom
: 1;
4864 bool mValidScaleFloat
: 1;
4865 bool mValidMinScale
: 1;
4866 bool mValidMaxScale
: 1;
4867 bool mWidthStrEmpty
: 1;
4869 // Parser aborted. True if the parser of this document was forcibly
4870 // terminated instead of letting it finish at its own pace.
4871 bool mParserAborted
: 1;
4873 // Whether we have reported document use counters for this document with
4874 // Telemetry yet. Normally this is only done at document destruction time,
4875 // but for image documents (SVG documents) that are not guaranteed to be
4876 // destroyed, we report use counters when the image cache no longer has any
4877 // imgRequestProxys pointing to them. We track whether we ever reported use
4878 // counters so that we only report them once for the document.
4879 bool mReportedDocumentUseCounters
: 1;
4881 bool mHasReportedShadowDOMUsage
: 1;
4883 // Whether an event triggered by the refresh driver was delayed because this
4884 // document has suppressed events.
4885 bool mHasDelayedRefreshEvent
: 1;
4887 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4888 // to have the right semantics. See
4889 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4890 // flag that is set while the window's 'load' event is firing if this document
4891 // is the window's document.
4892 bool mLoadEventFiring
: 1;
4894 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4895 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4896 // What we have instead is a flag that is set if completion of our document
4897 // via document.close() should skip firing the load event. Note that this
4898 // flag is only relevant for HTML documents, but lives here for reasons that
4899 // are documented above on SkipLoadEventAfterClose().
4900 bool mSkipLoadEventAfterClose
: 1;
4902 // When false, the .cookies property is completely disabled
4903 bool mDisableCookieAccess
: 1;
4905 // When false, the document.write() API is disabled.
4906 bool mDisableDocWrite
: 1;
4908 // Has document.write() been called with a recursion depth higher than
4910 bool mTooDeepWriteRecursion
: 1;
4913 * Temporary flag that is set in EndUpdate() to ignore
4914 * MaybeEditingStateChanged() script runners from a nested scope.
4916 bool mPendingMaybeEditingStateChanged
: 1;
4918 // mHasBeenEditable is set to true when mEditingState is firstly set to
4919 // eDesignMode or eContentEditable.
4920 bool mHasBeenEditable
: 1;
4922 // While we're handling an execCommand call by web app, set
4924 bool mIsRunningExecCommandByContent
: 1;
4925 // While we're handling an execCommand call by an addon (or chrome script),
4927 bool mIsRunningExecCommandByChromeOrAddon
: 1;
4929 // True if we should change the readystate to complete after we fire
4930 // DOMContentLoaded. This happens when we abort a load and
4931 // nsDocumentViewer::EndLoad runs while we still have things blocking
4932 // DOMContentLoaded. We wait for those to complete, and then update the
4933 // readystate when they finish.
4934 bool mSetCompleteAfterDOMContentLoaded
: 1;
4936 // Set the true if a completed cached stylesheet was created for the document.
4937 bool mDidHitCompleteSheetCache
: 1;
4939 // Whether we have initialized mShouldReportUseCounters and
4940 // mShouldSendPageUseCounters, and sent any needed message to the parent
4941 // process to indicate that use counter data will be sent at some later point.
4942 bool mUseCountersInitialized
: 1;
4944 // Whether this document should report use counters.
4945 bool mShouldReportUseCounters
: 1;
4947 // Whether this document should send page use counters. Set to true after
4948 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4949 bool mShouldSendPageUseCounters
: 1;
4951 // Whether the user has interacted with the document or not:
4952 bool mUserHasInteracted
: 1;
4954 // We constantly update the user-interaction anti-tracking permission at any
4955 // user-interaction using a timer. This boolean value is set to true when this
4956 // timer is scheduled.
4957 bool mHasUserInteractionTimerScheduled
: 1;
4959 // Whether we should resist fingerprinting.
4960 bool mShouldResistFingerprinting
: 1;
4962 // Whether we are in private browsing mode.
4963 bool mIsInPrivateBrowsing
: 1;
4965 // Whether we're cloning the contents of an SVG use element.
4966 bool mCloningForSVGUse
: 1;
4968 bool mAllowDeclarativeShadowRoots
: 1;
4970 bool mSuspendDOMNotifications
: 1;
4972 bool mForceLoadAtTop
: 1;
4974 bool mFireMutationEvents
: 1;
4976 // Whether the document's CSP contains a require-trusted-types-for directive.
4977 bool mHasPolicyWithRequireTrustedTypesForDirective
: 1;
4979 // Whether a copy event happened. Used to detect when this happens
4980 // while a paste event is being handled in JS.
4981 bool mClipboardCopyTriggered
: 1;
4983 Maybe
<bool> mMutationEventsEnabled
;
4985 // The fingerprinting protections overrides for this document. The value will
4986 // override the default enabled fingerprinting protections for this document.
4987 // This will only get populated if these is one that comes from the local
4988 // fingerprinting protection override pref or WebCompat. Otherwise, a value of
4989 // Nothing() indicates no overrides are present for this document.
4990 Maybe
<RFPTargetSet
> mOverriddenFingerprintingSettings
;
4992 uint8_t mXMLDeclarationBits
;
4994 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4995 // use uint8_t to avoid having to include a bunch of style system headers
4997 uint8_t mColorSchemeBits
= 0;
4999 // Currently active onload blockers.
5000 uint32_t mOnloadBlockCount
;
5002 // Tracks if we are currently processing any document.write calls (either
5003 // implicit or explicit). Note that if a write call writes out something which
5004 // would block the parser, then mWriteLevel will be incorrect until the parser
5005 // finishes processing that script.
5006 uint32_t mWriteLevel
;
5008 uint32_t mContentEditableCount
;
5009 EditingState mEditingState
;
5011 // Compatibility mode
5012 nsCompatibility mCompatMode
;
5015 ReadyState mReadyState
;
5017 // Ancestor's loading state
5018 bool mAncestorIsLoading
;
5020 // Our visibility state
5021 dom::VisibilityState mVisibilityState
;
5024 eUnknown
, // should never be used
5033 uint8_t mDefaultElementType
;
5035 enum Tri
{ eTriUnset
= 0, eTriFalse
, eTriTrue
};
5039 bool mSkipDTDSecurityChecks
;
5041 // The document's script global object, the object from which the
5042 // document can get its script context and scope. This is the
5043 // *inner* window object.
5044 nsCOMPtr
<nsIScriptGlobalObject
> mScriptGlobalObject
;
5046 // If mIsStaticDocument is true, mOriginalDocument points to the original
5048 RefPtr
<Document
> mOriginalDocument
;
5050 // The bidi options for this document. What this bitfield means is
5051 // defined in nsBidiUtils.h
5052 uint32_t mBidiOptions
;
5054 // The sandbox flags on the document. These reflect the value of the sandbox
5055 // attribute of the associated IFRAME or CSP-protectable content, if existent.
5056 // These are set at load time and are immutable - see nsSandboxFlags.h for the
5058 uint32_t mSandboxFlags
;
5060 // The embedder policy obtained from parsing the HTTP response header or from
5061 // our opener if this is the initial about:blank document.
5062 Maybe
<nsILoadInfo::CrossOriginEmbedderPolicy
> mEmbedderPolicy
;
5064 RefPtr
<nsAtom
> mContentLanguage
;
5066 // The channel that got passed to Document::StartDocumentLoad(), if any.
5067 nsCOMPtr
<nsIChannel
> mChannel
;
5069 // The CSP for every load lives in the Client within the LoadInfo. For all
5070 // document-initiated subresource loads we can use that cached version of the
5071 // CSP so we do not have to deserialize the CSP from the Client all the time.
5072 nsCOMPtr
<nsIContentSecurityPolicy
> mCSP
;
5073 nsCOMPtr
<nsIContentSecurityPolicy
> mPreloadCSP
;
5076 nsCString mContentType
;
5079 // The document's security info
5080 nsCOMPtr
<nsITransportSecurityInfo
> mSecurityInfo
;
5082 // The channel that failed to load and resulted in an error page.
5083 // This only applies to error pages. Might be null.
5084 nsCOMPtr
<nsIChannel
> mFailedChannel
;
5086 // if this document is part of a multipart document,
5087 // the ID can be used to distinguish it from the other parts.
5090 // Cycle collector generation in which we're certain that this document
5091 // won't be collected
5092 uint32_t mMarkedCCGeneration
;
5094 PresShell
* mPresShell
;
5096 nsCOMArray
<nsINode
> mSubtreeModifiedTargets
;
5097 uint32_t mSubtreeModifiedDepth
;
5099 // All images in process of being preloaded. This is a hashtable so
5100 // we can remove them as the real image loads start; that way we
5101 // make sure to not keep the image load going when no one cares
5102 // about it anymore.
5103 nsRefPtrHashtable
<nsURIHashKey
, imgIRequest
> mPreloadingImages
;
5105 // A list of preconnects initiated by the preloader. This prevents
5106 // the same uri from being used more than once, and allows the dom
5107 // builder to not repeat the work of the preloader.
5108 nsTHashMap
<nsURIHashKey
, bool> mPreloadedPreconnects
;
5110 // Current depth of picture elements from parser
5111 uint32_t mPreloadPictureDepth
;
5113 // Set if we've found a URL for the current picture
5114 nsString mPreloadPictureFoundSource
;
5116 // If we're an external resource document, this will be non-null and will
5117 // point to our "display document": the one that all resource lookups should
5119 RefPtr
<Document
> mDisplayDocument
;
5121 uint32_t mEventsSuppressed
;
5123 // Any XHR ChannelEventQueues that were suspended on this document while
5124 // events were suppressed.
5125 nsTArray
<RefPtr
<net::ChannelEventQueue
>> mSuspendedQueues
;
5127 // Any postMessage events that were suspended on this document while events
5129 nsTArray
<RefPtr
<PostMessageEvent
>> mSuspendedPostMessageEvents
;
5131 RefPtr
<EventListener
> mSuppressedEventListener
;
5134 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5136 uint32_t mIgnoreDestructiveWritesCounter
;
5138 // Count of live static clones of this document.
5139 uint32_t mStaticCloneCount
;
5141 // If the document is currently printing (or in print preview) this will point
5142 // to the current static clone of this document. This is weak since the clone
5143 // also has a reference to this document.
5144 WeakPtr
<Document
> mLatestStaticClone
;
5146 // Array of nodes that have been blocked to prevent user tracking.
5147 // They most likely have had their nsIChannel canceled by the URL
5148 // classifier. (Safebrowsing)
5150 // Weak nsINode pointers are used to allow nodes to disappear.
5151 nsTArray
<nsWeakPtr
> mBlockedNodesByClassifier
;
5153 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5154 // updated on every set of mScriptGlobalObject.
5155 nsPIDOMWindowInner
* mWindow
;
5157 nsCOMPtr
<nsIDocumentEncoder
> mCachedEncoder
;
5159 FrameRequestManager mFrameRequestManager
;
5161 // This object allows us to evict ourself from the back/forward cache. The
5162 // pointer is non-null iff we're currently in the bfcache.
5163 nsIBFCacheEntry
* mBFCacheEntry
;
5166 nsString mBaseTarget
;
5168 nsCOMPtr
<nsIStructuredCloneContainer
> mStateObjectContainer
;
5169 JS::Heap
<JS::Value
> mCachedStateObject
;
5171 uint32_t mInSyncOperationCount
;
5173 UniquePtr
<dom::XPathEvaluator
> mXPathEvaluator
;
5175 nsTArray
<RefPtr
<AnonymousContent
>> mAnonymousContents
;
5177 uint32_t mBlockDOMContentLoaded
;
5179 // Our live MediaQueryLists
5180 LinkedList
<MediaQueryList
> mDOMMediaQueryLists
;
5182 // A hashmap to keep track of which {element, imgRequestProxy}
5183 // combination has been processed to avoid considering the same
5184 // element twice for LargestContentfulPaint.
5185 ContentIdentifiersForLCPType mContentIdentifiersForLCP
;
5187 // Array of observers
5188 nsTObserverArray
<nsIDocumentObserver
*> mObservers
;
5190 // Flags for use counters used directly by this document.
5191 UseCounters mUseCounters
;
5192 // Flags for use counters from resource documents, static clones,
5193 // and SVG images referenced by this document. Those documents propagate
5194 // their use counters up to here, which then count towards the top-level
5195 // document's page use counters.
5196 UseCounters mChildDocumentUseCounters
;
5198 // The CSS property use counters.
5199 UniquePtr
<StyleUseCounters
> mStyleUseCounters
;
5201 TimeStamp mPageUnloadingEventTimeStamp
;
5203 RefPtr
<DocGroup
> mDocGroup
;
5205 RefPtr
<nsCommandManager
> mMidasCommandManager
;
5207 // The set of all the tracking script URLs. URLs are added to this set by
5208 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5209 // existing in the set means the corresponding script isn't a tracking script.
5210 nsTHashSet
<nsCString
> mTrackingScripts
;
5212 // Pointer to our parser if we're currently in the process of being
5214 nsCOMPtr
<nsIParser
> mParser
;
5216 // If the document was created from the the prototype cache there will be a
5217 // reference to the prototype document to allow tracing.
5218 RefPtr
<nsXULPrototypeDocument
> mPrototypeDocument
;
5220 // Weak reference to our sink for in case we no longer have a parser. This
5221 // will allow us to flush out any pending stuff from the sink even if
5222 // EndLoad() has already happened.
5223 nsWeakPtr mWeakSink
;
5225 // Our update nesting level
5226 uint32_t mUpdateNestLevel
;
5228 // HTTPS-Only Mode Status
5229 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5230 uint32_t mHttpsOnlyStatus
;
5232 enum ViewportType
: uint8_t {
5238 ViewportType mViewportType
;
5240 // viewport-fit described by
5241 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5242 ViewportFitType mViewportFit
;
5244 // https://drafts.csswg.org/css-viewport/#interactive-widget-section
5245 dom::InteractiveWidget mInteractiveWidgetMode
;
5247 // XXXdholbert This should really be modernized to a nsTHashMap or similar,
5248 // though note that the modernization will need to take care to also convert
5249 // the special hash_table_ops logic (e.g. how SubDocClearEntry clears the
5250 // parent document as part of cleaning up an entry in this table).
5251 UniquePtr
<PLDHashTable
> mSubDocuments
;
5254 UniquePtr
<HeaderData
> mHeaderData
;
5256 nsTArray
<net::EarlyHintConnectArgs
> mEarlyHints
;
5258 class TitleChangeEvent
;
5259 nsRevocableEventPtr
<TitleChangeEvent
> mPendingTitleChangeEvent
;
5261 RefPtr
<nsDOMNavigationTiming
> mTiming
;
5263 // Recorded time of change to 'loading' state
5264 // or time of the page gets restored from BFCache.
5265 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp
;
5267 // Decided to use nsTObserverArray because it allows us to
5268 // remove candidates while iterating them and this is what
5269 // the spec defines. We could implement the spec without
5270 // using nsTObserverArray, however using nsTObserverArray is more clear.
5271 nsTObserverArray
<nsWeakPtr
> mAutoFocusCandidates
;
5273 nsCString mScrollToRef
;
5275 // Weak reference to the scope object (aka the script global object)
5276 // that, unlike mScriptGlobalObject, is never unset once set. This
5277 // is a weak reference to avoid leaks due to circular references.
5278 nsWeakPtr mScopeObject
;
5280 // Array of intersection observers with active observations.
5281 nsTArray
<DOMIntersectionObserver
*> mIntersectionObservers
;
5282 // Array of resize observers with active observations.
5283 nsTArray
<ResizeObserver
*> mResizeObservers
;
5285 RefPtr
<DOMIntersectionObserver
> mLazyLoadObserver
;
5287 // Elements observed for a last remembered size.
5288 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5289 nsTHashSet
<RefPtr
<Element
>> mElementsObservedForLastRememberedSize
;
5291 // Stack of top layer elements.
5292 nsTArray
<nsWeakPtr
> mTopLayer
;
5294 // The root of the doc tree in which this document is in. This is only
5295 // non-null when this document is in fullscreen mode.
5296 WeakPtr
<Document
> mFullscreenRoot
;
5298 RefPtr
<DOMImplementation
> mDOMImplementation
;
5300 RefPtr
<nsContentList
> mImageMaps
;
5302 // A set of responsive images keyed by address pointer.
5303 nsTHashSet
<HTMLImageElement
*> mResponsiveContent
;
5305 RefPtr
<DocumentTimeline
> mDocumentTimeline
;
5306 LinkedList
<DocumentTimeline
> mTimelines
;
5308 RefPtr
<dom::ScriptLoader
> mScriptLoader
;
5310 // Tracker for scroll-driven animations that are waiting to start.
5311 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5312 RefPtr
<ScrollTimelineAnimationTracker
> mScrollTimelineAnimationTracker
;
5314 // A document "without a browsing context" that owns the content of
5315 // HTMLTemplateElement.
5316 RefPtr
<Document
> mTemplateContentsOwner
;
5318 dom::ExternalResourceMap mExternalResourceMap
;
5320 // ScreenOrientation "pending promise" as described by
5321 // http://www.w3.org/TR/screen-orientation/
5322 RefPtr
<Promise
> mOrientationPendingPromise
;
5324 nsTArray
<RefPtr
<nsFrameLoader
>> mInitializableFrameLoaders
;
5325 nsTArray
<nsCOMPtr
<nsIRunnable
>> mFrameLoaderFinalizers
;
5326 RefPtr
<nsRunnableMethod
<Document
>> mFrameLoaderRunner
;
5328 nsTArray
<PendingFrameStaticClone
> mPendingFrameStaticClones
;
5330 // The layout history state that should be used by nodes in this
5331 // document. We only actually store a pointer to it when:
5332 // 1) We have no script global object.
5333 // 2) We haven't had Destroy() called on us yet.
5334 nsCOMPtr
<nsILayoutHistoryState
> mLayoutHistoryState
;
5336 // Mapping of wake lock types to sets of wake locks sentinels
5337 // https://w3c.github.io/screen-wake-lock/#internal-slots
5338 nsTHashMap
<WakeLockType
, nsTHashSet
<RefPtr
<WakeLockSentinel
>>> mActiveLocks
;
5340 // The parsed viewport metadata of the last modified <meta name=viewport>
5342 UniquePtr
<ViewportMetaData
> mLastModifiedViewportMetaData
;
5344 // A tree ordered list of all color-scheme meta tags in this document.
5346 // TODO(emilio): There are other meta tags in the spec that have a similar
5347 // processing model to color-scheme. We could store all in-document meta tags
5348 // here to get sane and fast <meta> element processing.
5349 TreeOrderedArray
<HTMLMetaElement
*> mColorSchemeMetaTags
;
5351 // These member variables cache information about the viewport so we don't
5352 // have to recalculate it each time.
5353 LayoutDeviceToScreenScale mScaleMinFloat
;
5354 LayoutDeviceToScreenScale mScaleMaxFloat
;
5355 LayoutDeviceToScreenScale mScaleFloat
;
5356 CSSToLayoutDeviceScale mPixelRatio
;
5360 CSSCoord mMinHeight
;
5361 CSSCoord mMaxHeight
;
5363 RefPtr
<EventListenerManager
> mListenerManager
;
5365 nsCOMPtr
<nsIRequest
> mOnloadBlocker
;
5367 // Gecko-internal sheets used for extensions and such.
5368 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5369 nsTArray
<RefPtr
<StyleSheet
>> mAdditionalSheets
[AdditionalSheetTypeCount
];
5371 // Member to store out last-selected stylesheet set.
5372 nsString mLastStyleSheetSet
;
5373 nsString mPreferredStyleSheetSet
;
5375 RefPtr
<DOMStyleSheetSetList
> mStyleSheetSetList
;
5377 // We lazily calculate declaration blocks for elements with mapped
5378 // attributes. This set contains all elements which need lazy resolution.
5379 nsTHashSet
<Element
*> mLazyPresElements
;
5381 nsTHashSet
<RefPtr
<nsAtom
>> mLanguagesUsed
;
5383 // TODO(emilio): Is this hot enough to warrant to be cached?
5384 RefPtr
<nsAtom
> mLanguageFromCharset
;
5386 // Restyle root for servo's style system.
5388 // We store this as an nsINode, rather than as an Element, so that we can
5389 // store the Document node as the restyle root if the entire document (along
5390 // with all document-level native-anonymous content) needs to be restyled.
5392 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5393 // root corresponds to.
5394 nsCOMPtr
<nsINode
> mServoRestyleRoot
;
5395 uint32_t mServoRestyleRootDirtyBits
;
5397 // Used in conjunction with the create-an-element-for-the-token algorithm to
5398 // prevent custom element constructors from being able to use document.open(),
5399 // document.close(), and document.write() when they are invoked by the parser.
5400 uint32_t mThrowOnDynamicMarkupInsertionCounter
;
5402 // Count of unload/beforeunload/pagehide operations in progress.
5403 uint32_t mIgnoreOpensDuringUnloadCounter
;
5405 nsCOMPtr
<nsIDOMXULCommandDispatcher
>
5406 mCommandDispatcher
; // [OWNER] of the focus tracker
5408 RefPtr
<XULBroadcastManager
> mXULBroadcastManager
;
5409 RefPtr
<XULPersist
> mXULPersist
;
5410 RefPtr
<ChromeObserver
> mChromeObserver
;
5412 RefPtr
<HTMLAllCollection
> mAll
;
5414 // https://drafts.csswg.org/css-view-transitions-1/#document-active-view-transition
5415 RefPtr
<ViewTransition
> mActiveViewTransition
;
5417 nsTHashSet
<RefPtr
<WorkerDocumentListener
>> mWorkerListeners
;
5419 // Pres shell resolution saved before entering fullscreen mode.
5420 float mSavedResolution
;
5422 nsCOMPtr
<nsICookieJarSettings
> mCookieJarSettings
;
5424 bool mHasStoragePermission
;
5426 // Document generation. Gets incremented everytime it changes.
5427 int32_t mGeneration
;
5429 // Cached TabSizes values for the document.
5430 int32_t mCachedTabSizeGeneration
;
5431 nsTabSizes mCachedTabSizes
;
5433 // This is equal to document's principal but with an isolation key. See
5434 // StoragePrincipalHelper.h to know more.
5435 nsCOMPtr
<nsIPrincipal
> mPartitionedPrincipal
;
5437 // The cached storage principal for this document.
5438 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5439 // which is required due to its CloneDocHelper() call site. :-(
5440 mutable nsCOMPtr
<nsIPrincipal
> mActiveStoragePrincipal
;
5442 // The cached cookie principal for this document.
5443 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5444 // which is required due to its CloneDocHelper() call site. :-(
5445 mutable nsCOMPtr
<nsIPrincipal
> mActiveCookiePrincipal
;
5447 // See GetNextFormNumber and GetNextControlNumber.
5448 int32_t mNextFormNumber
;
5449 int32_t mNextControlNumber
;
5451 uint32_t mMediaElementWithMSECount
= 0;
5453 // Scope preloads per document. This is used by speculative loading as well.
5454 PreloadService mPreloadService
;
5456 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5457 bool mShouldNotifyFetchSuccess
;
5459 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5460 bool mShouldNotifyFormOrPasswordRemoved
;
5462 // Bitfield to be collected in the pageload event, recording relevant features
5463 // used in the document
5464 uint32_t mPageloadEventFeatures
= 0;
5466 // Record page load telemetry
5467 void RecordPageLoadEventTelemetry(
5468 glean::perf::PageLoadExtra
& aEventTelemetryData
);
5470 // Accumulate JS telemetry collected
5471 void AccumulateJSTelemetry(
5472 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5474 // Accumulate page load metrics
5475 void AccumulatePageLoadTelemetry(
5476 glean::perf::PageLoadExtra
& aEventTelemetryDataOut
);
5478 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5479 // Not holding strong refs here since we don't actually use the BBCs.
5480 nsTArray
<const BrowserBridgeChild
*> mOOPChildrenLoading
;
5482 // Registry of custom highlight definitions associated with this document.
5483 RefPtr
<class HighlightRegistry
> mHighlightRegistry
;
5485 // Used for tracking a number of recent canvas extractions (e.g. toDataURL),
5486 // this is used for a canvas fingerprinter detection heuristic.
5487 nsTArray
<CanvasUsage
> mCanvasUsage
;
5488 uint64_t mLastCanvasUsage
= 0;
5490 RefPtr
<class FragmentDirective
> mFragmentDirective
;
5491 UniquePtr
<RadioGroupContainer
> mRadioGroupContainer
;
5494 // Needs to be public because the bindings code pokes at it.
5495 JS::ExpandoAndGeneration mExpandoAndGeneration
;
5497 bool HasPendingInitialTranslation();
5499 nsRefPtrHashtable
<nsRefPtrHashKey
<Element
>, nsXULPrototypeElement
>
5502 void LoadEventFired();
5504 RadioGroupContainer
& OwnedRadioGroupContainer();
5506 MOZ_CAN_RUN_SCRIPT
static already_AddRefed
<Document
> ParseHTMLUnsafe(
5507 GlobalObject
& aGlobal
, const TrustedHTMLOrString
& aHTML
,
5508 ErrorResult
& aError
);
5511 NS_DEFINE_STATIC_IID_ACCESSOR(Document
, NS_IDOCUMENT_IID
)
5514 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5515 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5516 * object is deleted.
5518 class MOZ_STACK_CLASS mozAutoSubtreeModified
{
5521 * @param aSubTreeOwner The document in which a subtree will be modified.
5522 * @param aTarget The target of the possible DOMSubtreeModified event.
5523 * Can be nullptr, in which case mozAutoSubtreeModified
5524 * is just used to batch DOM mutations.
5526 mozAutoSubtreeModified(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5527 UpdateTarget(aSubtreeOwner
, aTarget
);
5530 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5532 void UpdateTarget(Document
* aSubtreeOwner
, nsINode
* aTarget
) {
5533 if (mSubtreeOwner
) {
5534 mSubtreeOwner
->MutationEventDispatched(mTarget
);
5538 mSubtreeOwner
= aSubtreeOwner
;
5539 if (mSubtreeOwner
) {
5540 mSubtreeOwner
->WillDispatchMutationEvent(mTarget
);
5545 nsCOMPtr
<nsINode
> mTarget
;
5546 RefPtr
<Document
> mSubtreeOwner
;
5549 enum class SyncOperationBehavior
{ eSuspendInput
, eAllowInput
};
5551 class AutoWalkBrowsingContextGroup
{
5553 virtual ~AutoWalkBrowsingContextGroup() = default;
5556 void SuppressBrowsingContext(BrowsingContext
* aContext
);
5557 void SuppressBrowsingContextGroup(BrowsingContextGroup
* aGroup
);
5558 void UnsuppressDocuments() {
5559 for (const auto& doc
: mDocuments
) {
5560 UnsuppressDocument(doc
);
5563 virtual void SuppressDocument(Document
* aDocument
) = 0;
5564 virtual void UnsuppressDocument(Document
* aDocument
) = 0;
5565 AutoTArray
<RefPtr
<Document
>, 16> mDocuments
;
5568 class MOZ_RAII nsAutoSyncOperation
: private AutoWalkBrowsingContextGroup
{
5570 explicit nsAutoSyncOperation(Document
* aDocument
,
5571 SyncOperationBehavior aSyncBehavior
);
5572 ~nsAutoSyncOperation();
5575 void SuppressDocument(Document
* aDocument
) override
;
5576 void UnsuppressDocument(Document
* aDocument
) override
;
5579 uint32_t mMicroTaskLevel
;
5580 const SyncOperationBehavior mSyncBehavior
;
5581 RefPtr
<BrowsingContext
> mBrowsingContext
;
5584 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final
{
5586 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document
* aDocument
)
5587 : mDocument(aDocument
) {
5588 mDocument
->IncrementThrowOnDynamicMarkupInsertionCounter();
5591 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5592 mDocument
->DecrementThrowOnDynamicMarkupInsertionCounter();
5596 Document
* mDocument
;
5599 class MOZ_RAII IgnoreOpensDuringUnload final
{
5601 explicit IgnoreOpensDuringUnload(Document
* aDoc
) : mDoc(aDoc
) {
5602 mDoc
->IncrementIgnoreOpensDuringUnloadCounter();
5605 ~IgnoreOpensDuringUnload() {
5606 mDoc
->DecrementIgnoreOpensDuringUnloadCounter();
5613 bool IsInFocusedTab(Document
* aDoc
);
5615 // This covers all cases covered by IsInFocusedTab, but also ensures that
5616 // focused tab is "active" meaning not occluded.
5617 bool IsInActiveTab(Document
* aDoc
);
5619 } // namespace mozilla::dom
5621 NON_VIRTUAL_ADDREF_RELEASE(mozilla::dom::Document
)
5623 // XXX These belong somewhere else
5624 nsresult
NS_NewHTMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5625 nsIPrincipal
* aPrincipal
,
5626 nsIPrincipal
* aPartitionedPrincipal
,
5627 bool aLoadedAsData
= false);
5629 nsresult
NS_NewXMLDocument(mozilla::dom::Document
** aInstancePtrResult
,
5630 nsIPrincipal
* aPrincipal
,
5631 nsIPrincipal
* aPartitionedPrincipal
,
5632 bool aLoadedAsData
= false,
5633 bool aIsPlainDocument
= false);
5635 nsresult
NS_NewSVGDocument(mozilla::dom::Document
** aInstancePtrResult
,
5636 nsIPrincipal
* aPrincipal
,
5637 nsIPrincipal
* aPartitionedPrincipal
);
5639 nsresult
NS_NewImageDocument(mozilla::dom::Document
** aInstancePtrResult
,
5640 nsIPrincipal
* aPrincipal
,
5641 nsIPrincipal
* aPartitionedPrincipal
);
5643 nsresult
NS_NewVideoDocument(mozilla::dom::Document
** aInstancePtrResult
,
5644 nsIPrincipal
* aPrincipal
,
5645 nsIPrincipal
* aPartitionedPrincipal
);
5647 // Enum for requesting a particular type of document when creating a doc
5648 enum DocumentFlavor
{
5649 DocumentFlavorLegacyGuess
, // compat with old code until made HTML5-compliant
5650 DocumentFlavorHTML
, // HTMLDocument with HTMLness bit set to true
5651 DocumentFlavorSVG
, // SVGDocument
5652 DocumentFlavorXML
, // XMLDocument
5653 DocumentFlavorPlain
, // Just a Document
5656 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5657 // -- this method will not attempt to get a principal based on aDocumentURI.
5658 // Also, both aDocumentURI and aBaseURI must not be null.
5659 nsresult
NS_NewDOMDocument(
5660 mozilla::dom::Document
** aInstancePtrResult
, const nsAString
& aNamespaceURI
,
5661 const nsAString
& aQualifiedName
, mozilla::dom::DocumentType
* aDoctype
,
5662 nsIURI
* aDocumentURI
, nsIURI
* aBaseURI
, nsIPrincipal
* aPrincipal
,
5663 bool aLoadedAsData
, nsIGlobalObject
* aEventObject
, DocumentFlavor aFlavor
);
5665 inline mozilla::dom::Document
* nsINode::GetOwnerDocument() const {
5666 mozilla::dom::Document
* ownerDoc
= OwnerDoc();
5668 return ownerDoc
!= this ? ownerDoc
: nullptr;
5671 inline nsINode
* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5673 inline mozilla::dom::Document
* nsINode::AsDocument() {
5674 MOZ_ASSERT(IsDocument());
5675 return static_cast<mozilla::dom::Document
*>(this);
5678 inline const mozilla::dom::Document
* nsINode::AsDocument() const {
5679 MOZ_ASSERT(IsDocument());
5680 return static_cast<const mozilla::dom::Document
*>(this);
5683 inline nsISupports
* ToSupports(mozilla::dom::Document
* aDoc
) {
5684 return static_cast<nsINode
*>(aDoc
);
5687 #endif /* mozilla_dom_Document_h___ */