Bug 1884792 - Remove chrome-only :-moz-lwtheme pseudo-class. r=desktop-theme-reviewer...
[gecko.git] / dom / base / Document.h
blob59f4c685b1cd4e7f4f5a3e81bc9c1762e1117bf6
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___
10 #include <bitset>
11 #include <cstddef>
12 #include <cstdint>
13 #include <new>
14 #include <utility>
15 #include "ErrorList.h"
16 #include "MainThreadUtils.h"
17 #include "Units.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"
60 #include "nsAtom.h"
61 #include "nsCOMArray.h"
62 #include "nsCOMPtr.h"
63 #include "nsClassHashtable.h"
64 #include "nsCompatibility.h"
65 #include "nsContentListDeclarations.h"
66 #include "nsCycleCollectionParticipant.h"
67 #include "nsTHashMap.h"
68 #include "nsDebug.h"
69 #include "nsGkAtoms.h"
70 #include "nsHashKeys.h"
71 #include "nsIChannel.h"
72 #include "nsIChannelEventSink.h"
73 #include "nsID.h"
74 #include "nsIDocumentViewer.h"
75 #include "nsIInterfaceRequestor.h"
76 #include "nsILoadContext.h"
77 #include "nsILoadGroup.h"
78 #include "nsILoadInfo.h"
79 #include "nsINode.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"
91 #include "nsIURI.h"
92 #include "nsIWeakReferenceUtils.h"
93 #include "nsLiteralString.h"
94 #include "nsPIDOMWindow.h"
95 #include "nsPropertyTable.h"
96 #include "nsRefPtrHashtable.h"
97 #include "nsString.h"
98 #include "nsTArray.h"
99 #include "nsTHashSet.h"
100 #include "nsTLiteralString.h"
101 #include "nsTObserverArray.h"
102 #include "nsThreadUtils.h"
103 #include "nsURIHashKey.h"
104 #include "nsViewportInfo.h"
105 #include "nsWeakReference.h"
106 #include "nsWindowSizes.h"
107 #include "nsXULElement.h"
108 #include "nscore.h"
110 // XXX We need to include this here to ensure that DefaultDeleter for Servo
111 // types is specialized before the template is instantiated. Probably, this
112 // should be included at some other place already that's generated by cbindgen.
113 #include "mozilla/ServoBindingTypes.h"
115 // windows.h #defines CreateEvent
116 #ifdef CreateEvent
117 # undef CreateEvent
118 #endif
120 #ifdef MOZILLA_INTERNAL_API
121 # include "mozilla/dom/DocumentBinding.h"
122 #else
123 namespace mozilla {
124 namespace dom {
125 class ElementCreationOptionsOrString;
126 } // namespace dom
127 } // namespace mozilla
128 #endif // MOZILLA_INTERNAL_API
130 class InfallibleAllocPolicy;
131 class JSObject;
132 class JSTracer;
133 class PLDHashTable;
134 class gfxUserFontSet;
135 class mozIDOMWindowProxy;
136 class nsCachableElementsByNameNodeList;
137 class nsCommandManager;
138 class nsContentList;
139 class nsCycleCollectionTraversalCallback;
140 class nsDOMCaretPosition;
141 class nsDOMNavigationTiming;
142 class nsDocShell;
143 class nsFrameLoader;
144 class nsFrameLoaderOwner;
145 class nsGenericHTMLElement;
146 class nsGlobalWindowInner;
147 class nsHTMLDocument;
148 class nsHtml5TreeOpExecutor;
149 class nsIAppWindow;
150 class nsIAsyncVerifyRedirectCallback;
151 class nsIBFCacheEntry;
152 class nsIContent;
153 class nsIContentSecurityPolicy;
154 class nsIContentSink;
155 class nsICookieJarSettings;
156 class nsIDOMXULCommandDispatcher;
157 class nsIDocShell;
158 class nsIDocShellTreeItem;
159 class nsIDocumentEncoder;
160 class nsIDocumentObserver;
161 class nsIEventTarget;
162 class nsIFrame;
163 class nsIGlobalObject;
164 class nsIHTMLCollection;
165 class nsIInputStream;
166 class nsILayoutHistoryState;
167 class nsIObjectLoadingContent;
168 class nsIPermissionDelegateHandler;
169 class nsIRadioVisitor;
170 class nsIRequest;
171 class nsIRunnable;
172 class nsIScriptGlobalObject;
173 class nsISecurityConsoleMessage;
174 class nsISerialEventTarget;
175 class nsIStructuredCloneContainer;
176 class nsIVariant;
177 class nsNodeInfoManager;
178 class nsPIWindowRoot;
179 class nsPresContext;
180 class nsRange;
181 class nsSimpleContentList;
182 class nsTextNode;
183 class nsViewManager;
184 class nsXULPrototypeDocument;
185 struct JSContext;
186 struct nsFont;
188 namespace mozilla {
189 class AbstractThread;
190 class AttributeStyles;
191 class CanvasUsage;
192 class StyleSheet;
193 class EditorBase;
194 class EditorCommand;
195 class Encoding;
196 class ErrorResult;
197 class EventListenerManager;
198 class FullscreenExit;
199 class FullscreenRequest;
200 class HTMLEditor;
201 struct LangGroupFontPrefs;
202 class PermissionDelegateHandler;
203 class PresShell;
204 class ScrollTimelineAnimationTracker;
205 class ServoStyleSet;
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;
213 template <typename>
214 class OwningNonNull;
215 struct URLExtraData;
217 namespace css {
218 class Loader;
219 class ImageLoader;
220 class Rule;
221 } // namespace css
223 namespace dom {
224 class AnonymousContent;
225 class Attr;
226 class XULBroadcastManager;
227 class XULPersist;
228 class BrowserBridgeChild;
229 class ChromeObserver;
230 class ClientInfo;
231 class ClientState;
232 class CDATASection;
233 class Comment;
234 class CSSImportRule;
235 class DocumentL10n;
236 class DocumentFragment;
237 class DocumentTimeline;
238 class DocumentType;
239 class DOMImplementation;
240 class DOMIntersectionObserver;
241 class DOMStringList;
242 class Event;
243 class EventListener;
244 struct FailedCertSecurityInfo;
245 class FeaturePolicy;
246 class FontFaceSet;
247 class FrameRequestCallback;
248 class ImageTracker;
249 class HighlightRegistry;
250 class HTMLAllCollection;
251 class HTMLBodyElement;
252 class HTMLInputElement;
253 class HTMLMetaElement;
254 class HTMLDialogElement;
255 class HTMLSharedElement;
256 class HTMLImageElement;
257 struct LifecycleCallbackArgs;
258 class Link;
259 class Location;
260 class MediaQueryList;
261 struct NetErrorInfo;
262 class NodeFilter;
263 class NodeInfo;
264 class NodeIterator;
265 enum class OrientationType : uint8_t;
266 class ProcessingInstruction;
267 class Promise;
268 class ScriptLoader;
269 class Selection;
270 class ServiceWorkerDescriptor;
271 class ShadowRoot;
272 class SVGDocument;
273 class SVGElement;
274 class SVGSVGElement;
275 class SVGUseElement;
276 class ImageDocument;
277 class Touch;
278 class TouchList;
279 class TreeWalker;
280 enum class ViewportFitType : uint8_t;
281 class WakeLockSentinel;
282 class WindowContext;
283 class WindowGlobalChild;
284 class WindowProxyHolder;
285 struct Wireframe;
286 class WorkerDocumentListener;
287 class XPathEvaluator;
288 class XPathExpression;
289 class XPathNSResolver;
290 class XPathResult;
291 class BrowsingContext;
293 class nsUnblockOnloadEvent;
295 template <typename, typename>
296 class CallbackObjectHolder;
298 enum class CallerType : uint32_t;
300 enum BFCacheStatus {
301 NOT_ALLOWED = 1 << 0, // Status 0
302 EVENT_HANDLING_SUPPRESSED = 1 << 1, // Status 1
303 SUSPENDED = 1 << 2, // Status 2
304 UNLOAD_LISTENER = 1 << 3, // Status 3
305 REQUEST = 1 << 4, // Status 4
306 ACTIVE_GET_USER_MEDIA = 1 << 5, // Status 5
307 ACTIVE_PEER_CONNECTION = 1 << 6, // Status 6
308 CONTAINS_EME_CONTENT = 1 << 7, // Status 7
309 CONTAINS_MSE_CONTENT = 1 << 8, // Status 8
310 HAS_ACTIVE_SPEECH_SYNTHESIS = 1 << 9, // Status 9
311 HAS_USED_VR = 1 << 10, // Status 10
312 CONTAINS_REMOTE_SUBFRAMES = 1 << 11, // Status 11
313 NOT_ONLY_TOPLEVEL_IN_BCG = 1 << 12, // Status 12
314 ABOUT_PAGE = 1 << 13, // Status 13
315 RESTORING = 1 << 14, // Status 14
316 BEFOREUNLOAD_LISTENER = 1 << 15, // Status 15
317 ACTIVE_LOCK = 1 << 16, // Status 16
318 ACTIVE_WEBTRANSPORT = 1 << 17, // Status 17
321 } // namespace dom
322 namespace glean::perf {
323 struct PageLoadExtra;
325 } // namespace mozilla
327 namespace mozilla::net {
328 class ChannelEventQueue;
329 class EarlyHintConnectArgs;
330 } // namespace mozilla::net
332 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
333 #define NS_IDOCUMENT_IID \
335 0xce1f7627, 0x7109, 0x4977, { \
336 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
340 namespace mozilla::dom {
342 class Document;
343 class DOMStyleSheetSetList;
344 class ResizeObserver;
345 class ResizeObserverController;
346 class PostMessageEvent;
348 #define DEPRECATED_OPERATION(_op) e##_op,
349 enum class DeprecatedOperations : uint16_t {
350 #include "nsDeprecatedOperationList.h"
351 eDeprecatedOperationCount
353 #undef DEPRECATED_OPERATION
355 class ExternalResourceMap {
356 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
358 public:
360 * A class that represents an external resource load that has begun but
361 * doesn't have a document yet. Observers can be registered on this object,
362 * and will be notified after the document is created. Observers registered
363 * after the document has been created will NOT be notified. When observers
364 * are notified, the subject will be the newly-created document, the topic
365 * will be "external-resource-document-created", and the data will be null.
366 * If document creation fails for some reason, observers will still be
367 * notified, with a null document pointer.
369 class ExternalResourceLoad : public nsISupports {
370 public:
371 virtual ~ExternalResourceLoad() = default;
373 void AddObserver(nsIObserver* aObserver) {
374 MOZ_ASSERT(aObserver, "Must have observer");
375 mObservers.AppendElement(aObserver);
378 const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
380 protected:
381 AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
384 ExternalResourceMap();
387 * Request an external resource document. This does exactly what
388 * Document::RequestExternalResource is documented to do.
390 Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
391 nsINode* aRequestingNode,
392 Document* aDisplayDocument,
393 ExternalResourceLoad** aPendingLoad);
396 * Enumerate the resource documents. See
397 * Document::EnumerateExternalResources.
399 void EnumerateResources(SubDocEnumFunc aCallback);
402 * Traverse ourselves for cycle-collection
404 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
407 * Shut ourselves down (used for cycle-collection unlink), as well
408 * as for document destruction.
410 void Shutdown() {
411 mPendingLoads.Clear();
412 mMap.Clear();
413 mHaveShutDown = true;
416 bool HaveShutDown() const { return mHaveShutDown; }
418 // Needs to be public so we can traverse them sanely
419 struct ExternalResource {
420 ~ExternalResource();
421 RefPtr<Document> mDocument;
422 nsCOMPtr<nsIDocumentViewer> mViewer;
423 nsCOMPtr<nsILoadGroup> mLoadGroup;
426 // Hide all our viewers
427 void HideViewers();
429 // Show all our viewers
430 void ShowViewers();
432 protected:
433 class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
434 ~PendingLoad() = default;
436 public:
437 explicit PendingLoad(Document* aDisplayDocument)
438 : mDisplayDocument(aDisplayDocument) {}
440 NS_DECL_ISUPPORTS
441 NS_DECL_NSISTREAMLISTENER
442 NS_DECL_NSIREQUESTOBSERVER
445 * Start aURI loading. This will perform the necessary security checks and
446 * so forth.
448 nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
449 nsINode* aRequestingNode);
451 * Set up an nsIDocumentViewer based on aRequest. This is guaranteed to
452 * put null in *aViewer and *aLoadGroup on all failures.
454 nsresult SetupViewer(nsIRequest* aRequest, nsIDocumentViewer** aViewer,
455 nsILoadGroup** aLoadGroup);
457 private:
458 RefPtr<Document> mDisplayDocument;
459 nsCOMPtr<nsIStreamListener> mTargetListener;
460 nsCOMPtr<nsIURI> mURI;
462 friend class PendingLoad;
464 class LoadgroupCallbacks final : public nsIInterfaceRequestor {
465 ~LoadgroupCallbacks() = default;
467 public:
468 explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
469 : mCallbacks(aOtherCallbacks) {}
470 NS_DECL_ISUPPORTS
471 NS_DECL_NSIINTERFACEREQUESTOR
472 private:
473 // The only reason it's safe to hold a strong ref here without leaking is
474 // that the notificationCallbacks on a loadgroup aren't the docshell itself
475 // but a shim that holds a weak reference to the docshell.
476 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
478 // Use shims for interfaces that docshell implements directly so that we
479 // don't hand out references to the docshell. The shims should all allow
480 // getInterface back on us, but other than that each one should only
481 // implement one interface.
483 // XXXbz I wish we could just derive the _allcaps thing from _i
484 #define DECL_SHIM(_i, _allcaps) \
485 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
486 ~_i##Shim() {} \
488 public: \
489 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
490 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
491 NS_ASSERTION(mIfReq, "Expected non-null here"); \
492 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
494 NS_DECL_ISUPPORTS \
495 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
496 NS_FORWARD_##_allcaps(mRealPtr->) private \
497 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
498 nsCOMPtr<_i> mRealPtr; \
501 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
502 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
503 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
504 #undef DECL_SHIM
508 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
509 * when this is called if the URI didn't result in an XML document. This
510 * function makes sure to remove the pending load for aURI, if any, from our
511 * hashtable, and to notify its observers, if any.
513 nsresult AddExternalResource(nsIURI* aURI, nsIDocumentViewer* aViewer,
514 nsILoadGroup* aLoadGroup,
515 Document* aDisplayDocument);
517 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
518 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
519 bool mHaveShutDown;
522 // The current status for a preload.
523 enum class SheetPreloadStatus : uint8_t {
524 // There's no need to preload anything, the sheet is already in-memory.
525 AlreadyComplete,
526 // The load is in-progress. There's no guarantee that a load was started, it
527 // could be coalesced with other redundant loads.
528 InProgress,
529 // Something went wrong, and we errored out.
530 Errored,
533 //----------------------------------------------------------------------
535 // Document interface. This is implemented by all document objects in
536 // Gecko.
537 class Document : public nsINode,
538 public DocumentOrShadowRoot,
539 public nsSupportsWeakReference,
540 public nsIScriptObjectPrincipal,
541 public SupportsWeakPtr {
542 friend class DocumentOrShadowRoot;
544 protected:
545 explicit Document(const char* aContentType);
546 virtual ~Document();
548 Document(const Document&) = delete;
549 Document& operator=(const Document&) = delete;
551 public:
552 using ExternalResourceLoad = dom::ExternalResourceMap::ExternalResourceLoad;
553 using ReferrerPolicyEnum = dom::ReferrerPolicy;
554 using AdoptedStyleSheetCloneCache =
555 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
557 // nsINode overrides the new operator for DOM Arena allocation.
558 // to use the default one, we need to bring it back again
559 void* operator new(size_t aSize) { return ::operator new(aSize); }
562 * Called when XPCOM shutdown.
564 static void Shutdown();
566 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
568 NS_DECL_ISUPPORTS_INHERITED
569 NS_IMETHOD_(void) DeleteCycleCollectable() override;
571 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
573 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
574 nsINode)
576 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
577 do { \
578 for (RefPtr obs : mObservers.ForwardRange()) { \
579 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
580 obs->func_ params_; \
583 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
584 looks bogus. */ \
585 if (PresShell* presShell = GetObservingPresShell()) { \
586 presShell->func_ params_; \
588 } while (0)
590 nsIPrincipal* EffectiveCookiePrincipal() const;
592 nsIPrincipal* EffectiveStoragePrincipal() const;
594 // nsIScriptObjectPrincipal
595 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
597 nsIPrincipal* GetEffectiveCookiePrincipal() final {
598 return EffectiveCookiePrincipal();
601 nsIPrincipal* GetEffectiveStoragePrincipal() final {
602 return EffectiveStoragePrincipal();
605 // You should probably not be using this function, since it performs no checks
606 // to ensure that the partitioned principal should really be used here. It is
607 // only designed to be used in very specific circumstances, such as when
608 // inheriting the document/storage principal.
609 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
611 // Gets the appropriate principal to check the URI against a blocklist /
612 // allowlist.
613 nsIPrincipal* GetPrincipalForPrefBasedHacks() const;
615 void ClearActiveCookieAndStoragePrincipals() {
616 mActiveStoragePrincipal = nullptr;
617 mActiveCookiePrincipal = nullptr;
620 // EventTarget
621 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
622 EventListenerManager* GetOrCreateListenerManager() override;
623 EventListenerManager* GetExistingListenerManager() const override;
625 // This helper class must be set when we dispatch beforeunload and unload
626 // events in order to avoid unterminate sync XHRs.
627 class MOZ_RAII PageUnloadingEventTimeStamp {
628 RefPtr<Document> mDocument;
629 bool mSet;
631 public:
632 explicit PageUnloadingEventTimeStamp(Document* aDocument)
633 : mDocument(aDocument), mSet(false) {
634 MOZ_ASSERT(aDocument);
635 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
636 mDocument->SetPageUnloadingEventTimeStamp();
637 mSet = true;
641 ~PageUnloadingEventTimeStamp() {
642 if (mSet) {
643 mDocument->CleanUnloadEventsTimeStamp();
649 * Let the document know that we're starting to load data into it.
650 * @param aCommand The parser command. Must not be null.
651 * XXXbz It's odd to have that here.
652 * @param aChannel The channel the data will come from. The channel must be
653 * able to report its Content-Type.
654 * @param aLoadGroup The loadgroup this document should use from now on.
655 * Note that the document might not be the only thing using
656 * this loadgroup.
657 * @param aContainer The container this document is in. This may be null.
658 * XXXbz maybe we should make it more explicit (eg make the
659 * container an nsIWebNavigation or nsIDocShell or
660 * something)?
661 * @param [out] aDocListener the listener to pump data from the channel into.
662 * Generally this will be the parser this document
663 * sets up, or some sort of data-handler for media
664 * documents.
665 * @param aReset whether the document should call Reset() on itself. If this
666 * is false, the document will NOT set its principal to the
667 * channel's owner, will not clear any event listeners that are
668 * already set on it, etc.
670 * Once this has been called, the document will return false for
671 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
672 * sure this happens is the responsibility of the caller of
673 * StartDocumentLoad().
675 * This function has an implementation, and does some setup, but does NOT set
676 * *aDocListener; this is the job of subclasses.
678 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
679 nsILoadGroup* aLoadGroup,
680 nsISupports* aContainer,
681 nsIStreamListener** aDocListener,
682 bool aReset) = 0;
683 void StopDocumentLoad();
685 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
686 virtual bool SuppressParserErrorElement() { return false; }
688 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
689 virtual bool SuppressParserErrorConsoleMessages() { return false; }
691 // nsINode
692 void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
693 bool aNotify, ErrorResult& aRv) override;
694 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
695 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
696 return NS_ERROR_NOT_IMPLEMENTED;
698 nsresult CloneDocHelper(Document* clone) const;
700 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
703 * Signal that the document title may have changed
704 * (see Document::GetTitle).
705 * @param aBoundTitleElement true if an HTML or SVG <title> element
706 * has just been bound to the document.
708 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
711 * Return the URI for the document. May return null. If it ever stops being
712 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
713 * also never return null.
715 * The value returned corresponds to the "document's address" in
716 * HTML5. As such, it may change over the lifetime of the document, for
717 * instance as a result of the user navigating to a fragment identifier on
718 * the page, or as a result to a call to pushState() or replaceState().
720 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
722 nsIURI* GetDocumentURI() const { return mDocumentURI; }
725 * Return the original URI of the document. This is the same as the
726 * document's URI unless that has changed from its original value (for
727 * example, due to history.pushState() or replaceState() being invoked on the
728 * document).
730 * This method corresponds to the "creation URL" in HTML5 and, once set,
731 * doesn't change over the lifetime of the document.
733 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
735 nsIURI* GetOriginalURI() const { return mOriginalURI; }
738 * Return the base domain of the document. This has been computed using
739 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
740 * checks. When the URI of the document changes, this value is recomputed.
742 nsCString GetBaseDomain() const { return mBaseDomain; }
745 * Set the URI for the document. This also sets the document's original URI,
746 * if it's null.
748 void SetDocumentURI(nsIURI* aURI);
751 * Set the URI for the document loaded via XHR, when accessed from
752 * chrome privileged script.
754 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
757 * Set the base URI for the document loaded via XHR, when accessed from
758 * chrome privileged script.
760 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
763 * The CSP in general is stored in the ClientInfo, but we also cache
764 * the CSP on the document so subresources loaded within a document
765 * can query that cached CSP instead of having to deserialize the CSP
766 * from the Client.
768 * Please note that at the time of CSP parsing the Client is not
769 * available yet, hence we sync CSP of document and Client when the
770 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
772 nsIContentSecurityPolicy* GetCsp() const;
773 void SetCsp(nsIContentSecurityPolicy* aCSP);
775 nsIContentSecurityPolicy* GetPreloadCsp() const;
776 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
778 void GetCspJSON(nsString& aJSON);
781 * Set referrer policy and upgrade-insecure-requests flags
783 void ApplySettingsFromCSP(bool aSpeculative);
785 already_AddRefed<nsIParser> CreatorParserOrNull() {
786 nsCOMPtr<nsIParser> parser = mParser;
787 return parser.forget();
791 * ReferrerInfo getter for Document.webidl.
793 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
795 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
797 nsIReferrerInfo* GetPreloadReferrerInfo() const {
798 return mPreloadReferrerInfo;
801 * Return the referrer policy of the document. Return "default" if there's no
802 * valid meta referrer tag found in the document.
803 * Referrer policy should be inherited from parent if the iframe is srcdoc
805 ReferrerPolicyEnum GetReferrerPolicy() const;
808 * GetReferrerPolicy() for Document.webidl.
810 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
813 * If true, this flag indicates that all mixed content subresource
814 * loads for this document (and also embeded browsing contexts) will
815 * be blocked.
817 bool GetBlockAllMixedContent(bool aPreload) const {
818 if (aPreload) {
819 return mBlockAllMixedContentPreloads;
821 return mBlockAllMixedContent;
825 * If true, this flag indicates that all subresource loads for this
826 * document need to be upgraded from http to https.
827 * This flag becomes true if the CSP of the document itself, or any
828 * of the document's ancestors up to the toplevel document makes use
829 * of the CSP directive 'upgrade-insecure-requests'.
831 bool GetUpgradeInsecureRequests(bool aPreload) const {
832 if (aPreload) {
833 return mUpgradeInsecurePreloads;
835 return mUpgradeInsecureRequests;
838 void SetReferrerInfo(nsIReferrerInfo*);
841 * Referrer policy from <meta name="referrer" content=`policy`>
842 * will have higher priority than referrer policy from Referrer-Policy
843 * header. So override the old ReferrerInfo if we get one from meta
845 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
846 bool aPreload);
849 * Set the principals responsible for this document. Chances are, you do not
850 * want to be using this.
852 void SetPrincipals(nsIPrincipal* aPrincipal,
853 nsIPrincipal* aPartitionedPrincipal);
856 * Returns true if exempt from HTTPS-Only Mode upgrade.
858 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
861 * Return the LoadGroup for the document. May return null.
863 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
864 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
865 return group.forget();
869 * Return the fallback base URL for this document, as defined in the HTML
870 * specification. Note that this can return null if there is no document URI.
872 * XXXbz: This doesn't implement the bits for about:blank yet.
874 nsIURI* GetFallbackBaseURI() const {
875 if (mIsSrcdocDocument && mParentDocument) {
876 return mParentDocument->GetDocBaseURI();
878 return mDocumentURI;
882 * Return the referrer from document URI as defined in the Referrer Policy
883 * specification.
884 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
885 * While document is an iframe srcdoc document, let document be document's
886 * browsing context's browsing context container's node document.
887 * Then referrer should be document's URL
890 nsIURI* GetDocumentURIAsReferrer() const {
891 if (mIsSrcdocDocument && mParentDocument) {
892 return mParentDocument->GetDocumentURIAsReferrer();
894 return mDocumentURI;
898 * Return the base URI for relative URIs in the document (the document uri
899 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
900 * returned URI could be null if there is no document URI. If the document is
901 * a srcdoc document and has no explicit base URL, return the parent
902 * document's base URL.
904 nsIURI* GetDocBaseURI() const {
905 if (mDocumentBaseURI) {
906 return mDocumentBaseURI;
908 return GetFallbackBaseURI();
911 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
913 void SetBaseURI(nsIURI* aURI);
916 * Resolves a URI based on the document's base URI.
918 Result<OwningNonNull<nsIURI>, nsresult> ResolveWithBaseURI(
919 const nsAString& aURI);
922 * Return the URL data which style system needs for resolving url value.
923 * This method attempts to use the cached object in mCachedURLData, but
924 * if the base URI, document URI, or principal has changed since last
925 * call to this function, or the function is called the first time for
926 * the document, a new one is created.
928 URLExtraData* DefaultStyleAttrURLData();
929 nsIReferrerInfo* ReferrerInfoForInternalCSSAndSVGResources();
932 * Get/Set the base target of a link in a document.
934 void GetBaseTarget(nsAString& aBaseTarget) const {
935 aBaseTarget = mBaseTarget;
938 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
941 * Return a standard name for the document's character set.
943 NotNull<const Encoding*> GetDocumentCharacterSet() const {
944 return mCharacterSet;
948 * Set the document's character encoding.
950 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
952 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
954 // This method MUST be called before SetDocumentCharacterSet if
955 // you're planning to call both.
956 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
957 mCharacterSetSource = aCharsetSource;
961 * Get the Content-Type of this document.
963 void GetContentType(nsAString& aContentType);
966 * Set the Content-Type of this document.
968 void SetContentType(const nsACString& aContentType);
971 * Return the language of this document, or null if not set.
973 nsAtom* GetContentLanguage() const { return mContentLanguage.get(); }
975 void GetContentLanguageForBindings(DOMString&) const;
977 // The states BidiEnabled and MathMLEnabled should persist across multiple
978 // views (screen, print) of the same document.
981 * Check if the document contains bidi data.
982 * If so, we have to apply the Unicode Bidi Algorithm.
984 bool GetBidiEnabled() const { return mBidiEnabled; }
987 * Indicate the document contains bidi data.
988 * Currently, we cannot disable bidi, because once bidi is enabled,
989 * it affects a frame model irreversibly, and plays even though
990 * the document no longer contains bidi data.
992 void SetBidiEnabled() { mBidiEnabled = true; }
994 void SetMathMLEnabled() { mMathMLEnabled = true; }
997 * Ask this document whether it's the initial document in its window.
999 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
1002 * Ask this document whether it has ever been a initial document in its
1003 * window.
1005 bool IsEverInitialDocument() const { return mIsEverInitialDocumentInWindow; }
1008 * Tell this document that it's the initial document in its window. See
1009 * comments on mIsInitialDocumentInWindow for when this should be called.
1011 void SetIsInitialDocument(bool aIsInitialDocument);
1013 void SetLoadedAsData(bool aLoadedAsData, bool aConsiderForMemoryReporting);
1015 TimeStamp GetLoadingOrRestoredFromBFCacheTimeStamp() const {
1016 return mLoadingOrRestoredFromBFCacheTimeStamp;
1018 void SetLoadingOrRestoredFromBFCacheTimeStampToNow() {
1019 mLoadingOrRestoredFromBFCacheTimeStamp = TimeStamp::Now();
1023 * Normally we assert if a runnable labeled with one DocGroup touches data
1024 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1025 * means that we can touch that document from any DocGroup without asserting.
1027 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1030 * Get the bidi options for this document.
1031 * @see nsBidiUtils.h
1033 uint32_t GetBidiOptions() const { return mBidiOptions; }
1036 * Set the bidi options for this document. This just sets the bits;
1037 * callers are expected to take action as needed if they want this
1038 * change to actually change anything immediately.
1039 * @see nsBidiUtils.h
1041 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1044 * Returns true if the document holds a CSP
1045 * delivered through an HTTP Header.
1047 bool GetHasCSPDeliveredThroughHeader() {
1048 return mHasCSPDeliveredThroughHeader;
1052 * Return a promise which resolves to the content blocking events.
1054 using GetContentBlockingEventsPromise = MozPromise<uint32_t, bool, true>;
1055 [[nodiscard]] RefPtr<GetContentBlockingEventsPromise>
1056 GetContentBlockingEvents();
1059 * Get the sandbox flags for this document.
1060 * @see nsSandboxFlags.h for the possible flags
1062 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1064 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1065 return mEmbedderPolicy;
1068 void SetEmbedderPolicy(
1069 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1070 mEmbedderPolicy = aCOEP;
1074 * Get string representation of sandbox flags (null if no flags are set)
1076 void GetSandboxFlagsAsString(nsAString& aFlags);
1079 * Set the sandbox flags for this document.
1080 * @see nsSandboxFlags.h for the possible flags
1082 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1085 * Called when the document was decoded as UTF-8 and decoder encountered no
1086 * errors.
1088 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1091 * Called to disable client access to cookies through the document.cookie API
1092 * from user JavaScript code.
1094 void DisableCookieAccess() { mDisableCookieAccess = true; }
1096 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1097 bool LinkHandlingEnabled() { return mLinksEnabled; }
1100 * Set compatibility mode for this document
1102 void SetCompatibilityMode(nsCompatibility aMode);
1105 * Called to disable client access to document.write() API from user
1106 * JavaScript code.
1108 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1111 * Whether a document.write() call is in progress.
1113 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1116 * Access HTTP header data (this may also get set from other
1117 * sources, like HTML META tags).
1119 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1120 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1123 * Set Early Hint data, moves the arrays into the function, leaving the
1124 * passed variables empty
1126 void SetEarlyHints(nsTArray<net::EarlyHintConnectArgs>&& aEarlyHints);
1127 const nsTArray<net::EarlyHintConnectArgs>& GetEarlyHints() const {
1128 return mEarlyHints;
1132 * Create a new presentation shell that will use aContext for its
1133 * presentation context (presentation contexts <b>must not</b> be
1134 * shared among multiple presentation shells). The caller of this
1135 * method is responsible for calling BeginObservingDocument() on the
1136 * presshell if the presshell should observe document mutations.
1138 MOZ_CAN_RUN_SCRIPT already_AddRefed<PresShell> CreatePresShell(
1139 nsPresContext* aContext, nsViewManager* aViewManager);
1140 void DeletePresShell();
1142 PresShell* GetPresShell() const {
1143 return GetBFCacheEntry() ? nullptr : mPresShell;
1146 inline PresShell* GetObservingPresShell() const;
1148 // Return whether the presshell for this document is safe to flush.
1149 bool IsSafeToFlush() const;
1151 inline nsPresContext* GetPresContext() const;
1153 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1155 // Instead using this method, what you probably want is
1156 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1157 void DisallowBFCaching(uint32_t aStatus = BFCacheStatus::NOT_ALLOWED);
1159 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1161 // Accepts null to clear the BFCache entry too.
1162 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1164 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1166 // Removes this document from the BFCache, if it is cached, and returns
1167 // true if it was.
1168 bool RemoveFromBFCacheSync();
1171 * Return the parent document of this document. Will return null
1172 * unless this document is within a compound document and has a
1173 * parent. Note that this parent chain may cross chrome boundaries.
1175 Document* GetInProcessParentDocument() const { return mParentDocument; }
1178 * Set the parent document of this document.
1180 void SetParentDocument(Document* aParent) {
1181 mParentDocument = aParent;
1182 if (aParent) {
1183 RecomputeResistFingerprinting();
1184 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1188 void SetCurrentContextPaint(const SVGContextPaint* aContextPaint) {
1189 mCurrentContextPaint = aContextPaint;
1192 const SVGContextPaint* GetCurrentContextPaint() const {
1193 return mCurrentContextPaint;
1197 * Set the sub document for aContent to aSubDoc.
1199 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1202 * Get the sub document for aContent
1204 Document* GetSubDocumentFor(nsIContent* aContent) const;
1207 * Get the content node for which this document is a sub document.
1209 Element* GetEmbedderElement() const;
1212 * Return the doctype for this document.
1214 DocumentType* GetDoctype() const;
1217 * Return the root element for this document.
1219 Element* GetRootElement() const;
1221 Selection* GetSelection(ErrorResult& aRv);
1223 void MakeBrowsingContextNonSynthetic();
1224 nsresult HasStorageAccessSync(bool& aHasStorageAccess);
1225 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1227 StorageAccessAPIHelper::PerformPermissionGrant CreatePermissionGrantPromise(
1228 nsPIDOMWindowInner* aInnerWindow, nsIPrincipal* aPrincipal,
1229 bool aHasUserInteraction, bool aRequireUserInteraction,
1230 const Maybe<nsCString>& aTopLevelBaseDomain, bool aFrameOnly);
1232 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1234 already_AddRefed<Promise> RequestStorageAccessForOrigin(
1235 const nsAString& aThirdPartyOrigin, const bool aRequireUserInteraction,
1236 ErrorResult& aRv);
1238 already_AddRefed<Promise> RequestStorageAccessUnderSite(
1239 const nsAString& aSerializedSite, ErrorResult& aRv);
1240 already_AddRefed<Promise> CompleteStorageAccessRequestFromSite(
1241 const nsAString& aSerializedOrigin, ErrorResult& aRv);
1243 bool UseRegularPrincipal() const;
1246 * Gets the event target to dispatch key events to if there is no focused
1247 * content in the document.
1249 virtual Element* GetUnfocusedKeyEventTarget();
1252 * Retrieve information about the viewport as a data structure.
1253 * This will return information in the viewport META data section
1254 * of the document. This can be used in lieu of ProcessViewportInfo(),
1255 * which places the viewport information in the document header instead
1256 * of returning it directly.
1258 * @param aDisplaySize size of the on-screen display area for this
1259 * document, in device pixels.
1261 * NOTE: If the site is optimized for mobile (via the doctype), this
1262 * will return viewport information that specifies default information.
1264 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1266 void SetMetaViewportData(UniquePtr<ViewportMetaData> aData);
1268 // Returns a ViewportMetaData for this document.
1269 ViewportMetaData GetViewportMetaData() const;
1272 * True iff this doc will ignore manual character encoding overrides.
1274 virtual bool WillIgnoreCharsetOverride() { return true; }
1277 * Return whether the document was created by a srcdoc iframe.
1279 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1282 * Sets whether the document was created by a srcdoc iframe.
1284 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1285 mIsSrcdocDocument = aIsSrcdocDocument;
1289 * Gets the srcdoc string from within the channel (assuming both exist).
1290 * Returns a void string if this isn't a srcdoc document or if
1291 * the channel has not been set.
1293 nsresult GetSrcdocData(nsAString& aSrcdocData);
1295 already_AddRefed<AnonymousContent> InsertAnonymousContent(bool aForce,
1296 ErrorResult&);
1297 void RemoveAnonymousContent(AnonymousContent&);
1299 * If aNode is a descendant of anonymous content inserted by
1300 * InsertAnonymousContent, this method returns the root element of the
1301 * inserted anonymous content (in other words, the clone of the aElement
1302 * that was passed to InsertAnonymousContent).
1304 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1305 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1306 return mAnonymousContents;
1309 TimeStamp GetPageUnloadingEventTimeStamp() const {
1310 if (!mParentDocument) {
1311 return mPageUnloadingEventTimeStamp;
1314 TimeStamp parentTimeStamp(
1315 mParentDocument->GetPageUnloadingEventTimeStamp());
1316 if (parentTimeStamp.IsNull()) {
1317 return mPageUnloadingEventTimeStamp;
1320 if (!mPageUnloadingEventTimeStamp ||
1321 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1322 return parentTimeStamp;
1325 return mPageUnloadingEventTimeStamp;
1328 void NotifyLayerManagerRecreated();
1330 // Add an element to the list of elements that need their mapped attributes
1331 // resolved to a declaration block.
1333 // These are weak pointers, manually unschedule them when an element is
1334 // removed from the tree.
1335 void ScheduleForPresAttrEvaluation(Element* aElement);
1337 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1338 // generally when it's unbound from the tree.
1339 void UnscheduleForPresAttrEvaluation(Element* aElement);
1341 // Resolve all presentational attributes scheduled in
1342 // ScheduleForPresAttrEvaluation
1343 void ResolveScheduledPresAttrs() {
1344 if (mLazyPresElements.IsEmpty()) {
1345 return;
1347 DoResolveScheduledPresAttrs();
1350 Maybe<ClientInfo> GetClientInfo() const;
1351 Maybe<ClientState> GetClientState() const;
1352 Maybe<ServiceWorkerDescriptor> GetController() const;
1354 // Given a node, get a weak reference to it and append that reference to
1355 // mBlockedNodesByClassifier. Can be used later on to look up a node in it.
1356 // (e.g., by the UI)
1357 // /
1358 void AddBlockedNodeByClassifier(nsINode* aNode) {
1359 if (aNode) {
1360 mBlockedNodesByClassifier.AppendElement(do_GetWeakReference(aNode));
1364 // Returns the size of the mBlockedNodesByClassifier array.
1366 // This array contains nodes that have been blocked to prevent user tracking,
1367 // fingerprinting, cryptomining, etc. They most likely have had their
1368 // nsIChannel canceled by the URL classifier (Safebrowsing).
1370 // A script can subsequently use GetBlockedNodesByClassifier()
1371 // to get a list of references to these nodes.
1373 // Note:
1374 // This expresses how many tracking nodes have been blocked for this document
1375 // since its beginning, not how many of them are still around in the DOM tree.
1376 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1377 // array but they are not removed when those nodes are removed from the tree
1378 // or even garbage collected.
1379 size_t BlockedNodeByClassifierCount() const {
1380 return mBlockedNodesByClassifier.Length();
1383 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1384 // This array contains nodes that have been blocked to prevent
1385 // user tracking. They most likely have had their nsIChannel
1386 // canceled by the URL classifier (Safebrowsing).
1387 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1389 // Helper method that returns true if the document has storage-access sandbox
1390 // flag.
1391 bool StorageAccessSandboxed() const;
1393 // Helper method that returns true if storage access API is enabled and
1394 // the passed flag has storage-access sandbox flag.
1395 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1397 // Returns the cookie jar settings for this and sub contexts.
1398 nsICookieJarSettings* CookieJarSettings();
1400 // Returns whether this document is using unpartitioned cookies
1401 bool UsingStorageAccess();
1403 // Returns whether the storage access permission of the document is granted by
1404 // the allow list.
1405 bool HasStorageAccessPermissionGrantedByAllowList();
1407 // Increments the document generation.
1408 inline void Changed() { ++mGeneration; }
1410 // Returns the current generation.
1411 inline int32_t GetGeneration() const { return mGeneration; }
1413 // Adds cached sizes values to aSizes if there's any
1414 // cached value and if the document generation hasn't
1415 // changed since the cache was created.
1416 // Returns true if sizes were added.
1417 bool GetCachedSizes(nsTabSizes* aSizes);
1419 // Sets the cache sizes for the current generation.
1420 void SetCachedSizes(nsTabSizes* aSizes);
1423 * Should be called when an element's editable changes as a result of
1424 * changing its contentEditable attribute/property.
1426 * The change should be +1 if the contentEditable attribute/property was
1427 * changed to true, -1 if it was changed to false.
1429 void ChangeContentEditableCount(Element*, int32_t aChange);
1430 MOZ_CAN_RUN_SCRIPT void DeferredContentEditableCountChange(Element*);
1432 enum class EditingState : int8_t {
1433 eTearingDown = -2,
1434 eSettingUp = -1,
1435 eOff = 0,
1436 eDesignMode,
1437 eContentEditable
1441 * Returns the editing state of the document (not editable, contentEditable or
1442 * designMode).
1444 EditingState GetEditingState() const { return mEditingState; }
1447 * Returns whether the document is editable.
1449 bool IsEditingOn() const {
1450 return GetEditingState() == EditingState::eDesignMode ||
1451 GetEditingState() == EditingState::eContentEditable;
1454 class MOZ_STACK_CLASS nsAutoEditingState {
1455 public:
1456 nsAutoEditingState(Document* aDoc, EditingState aState)
1457 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1458 aDoc->mEditingState = aState;
1460 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1462 private:
1463 RefPtr<Document> mDoc;
1464 EditingState mSavedState;
1466 friend class nsAutoEditingState;
1469 * Set the editing state of the document. Don't use this if you want
1470 * to enable/disable editing, call EditingStateChanged() or
1471 * SetDesignMode().
1473 void SetEditingState(EditingState aState) { mEditingState = aState; }
1476 * Called when this Document's editor is destroyed.
1478 void TearingDownEditor();
1480 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1482 // Gets the next form number.
1484 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1485 // parser inserted form element.
1486 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1488 // Gets the next form control number.
1490 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1491 // parser inserted form control element.
1492 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1494 PreloadService& Preloads() { return mPreloadService; }
1496 bool HasThirdPartyChannel();
1498 bool ShouldIncludeInTelemetry() const;
1500 void AddMediaElementWithMSE();
1501 void RemoveMediaElementWithMSE();
1503 void DoNotifyPossibleTitleChange();
1505 void InitFeaturePolicy();
1506 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1508 void EnsureNotEnteringAndExitFullscreen();
1510 protected:
1511 friend class nsUnblockOnloadEvent;
1513 nsresult InitCSP(nsIChannel* aChannel);
1514 nsresult InitCOEP(nsIChannel* aChannel);
1516 nsresult InitReferrerInfo(nsIChannel* aChannel);
1518 void PostUnblockOnloadEvent();
1520 void DoUnblockOnload();
1522 void DoResolveScheduledPresAttrs();
1524 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1526 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1527 NotNull<const Encoding*>& aEncoding,
1528 nsHtml5TreeOpExecutor* aExecutor);
1530 MOZ_CAN_RUN_SCRIPT void DispatchContentLoadedEvents();
1532 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1533 MOZ_CAN_RUN_SCRIPT_BOUNDARY void DispatchPageTransition(
1534 EventTarget* aDispatchTarget, const nsAString& aType, bool aInFrameSwap,
1535 bool aPersisted, bool aOnlySystemGroup);
1537 // Call this before the document does something that will unbind all content.
1538 // That will stop us from doing a lot of work as each element is removed.
1539 void DestroyElementMaps();
1541 Element* GetRootElementInternal() const;
1543 void SetPageUnloadingEventTimeStamp() {
1544 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1545 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1548 void CleanUnloadEventsTimeStamp() {
1549 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1550 mPageUnloadingEventTimeStamp = TimeStamp();
1554 * Clears any Servo element data stored on Elements in the document.
1556 void ClearStaleServoData();
1559 * Do the tree-disconnection that ResetToURI and document.open need to do.
1561 void DisconnectNodeTree();
1564 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1565 * "CheckKeyPressEventModel" event to check whether we should dispatch
1566 * keypress events in confluent model or split model. This should be
1567 * called only when mEditingState is changed to eDesignMode or
1568 * eConentEditable at first time.
1570 void MaybeDispatchCheckKeyPressEventModelEvent();
1572 /* Midas implementation */
1573 nsCommandManager* GetMidasCommandManager();
1575 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1577 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1578 // of places, and I'm pretty sure the exact ExecCommand call it
1579 // makes cannot actually run script.
1580 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1582 void MaybeEditingStateChanged();
1584 public:
1585 // Get the root <html> element, or return null if there isn't one (e.g.
1586 // if the root isn't <html>)
1587 Element* GetHtmlElement() const;
1588 // Returns the first child of GetHtmlContent which has the given tag,
1589 // or nullptr if that doesn't exist.
1590 Element* GetHtmlChildElement(nsAtom* aTag);
1591 // Get the canonical <body> element, or return null if there isn't one (e.g.
1592 // if the root isn't <html> or if the <body> isn't there)
1593 HTMLBodyElement* GetBodyElement();
1594 // Get the canonical <head> element, or return null if there isn't one (e.g.
1595 // if the root isn't <html> or if the <head> isn't there)
1596 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1597 // Get the "body" in the sense of document.body: The first <body> or
1598 // <frameset> that's a child of a root <html>
1599 nsGenericHTMLElement* GetBody();
1600 // Set the "body" in the sense of document.body.
1601 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1602 // Get the "head" element in the sense of document.head.
1603 HTMLSharedElement* GetHead();
1605 ServoStyleSet* StyleSetForPresShell() const {
1606 MOZ_ASSERT(!!mStyleSet.get());
1607 return mStyleSet.get();
1610 inline ServoStyleSet& EnsureStyleSet() const;
1612 // ShadowRoot has APIs that can change styles. This notifies the shell that
1613 // stlyes applicable in the shadow tree have potentially changed.
1614 void RecordShadowStyleChange(ShadowRoot&);
1616 // Needs to be called any time the applicable style can has changed, in order
1617 // to schedule a style flush and setup all the relevant state.
1619 // If we know the stylesheet change applies only to a shadow tree we can avoid
1620 // some work (like updating the font-face-set / counter-styles / etc, as those
1621 // are global).
1622 void ApplicableStylesChanged(bool aKnownInShadowTree = false);
1624 // Whether we filled the style set with any style sheet. Only meant to be used
1625 // from DocumentOrShadowRoot::Traverse.
1626 bool StyleSetFilled() const { return mStyleSetFilled; }
1629 * Accessors to the collection of stylesheets owned by this document.
1630 * Style sheets are ordered, most significant last.
1633 void InsertSheetAt(size_t aIndex, StyleSheet&);
1636 * Add a stylesheet to the document
1638 * TODO(emilio): This is only used by parts of editor that are no longer in
1639 * use by m-c or c-c, so remove.
1641 void AddStyleSheet(StyleSheet* aSheet) {
1642 MOZ_ASSERT(aSheet);
1643 InsertSheetAt(SheetCount(), *aSheet);
1647 * Notify the document that the applicable state of the sheet changed
1648 * and that observers should be notified and style sets updated
1650 void StyleSheetApplicableStateChanged(StyleSheet&);
1651 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1652 void PostStyleSheetRemovedEvent(StyleSheet&);
1653 void PostCustomPropertyRegistered(const dom::PropertyDefinition&);
1655 enum additionalSheetType {
1656 eAgentSheet,
1657 eUserSheet,
1658 eAuthorSheet,
1659 AdditionalSheetTypeCount
1662 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1663 nsIURI* aSheetURI);
1664 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1665 StyleSheet* aSheet);
1666 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1668 StyleSheet* GetFirstAdditionalAuthorSheet() {
1669 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1673 * Returns the index that aSheet should be inserted at to maintain document
1674 * ordering.
1676 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1679 * Get this document's CSSLoader. This is guaranteed to not return null.
1681 css::Loader* CSSLoader() const { return mCSSLoader; }
1684 * Get this document's StyleImageLoader. This is guaranteed to not return
1685 * null.
1687 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1690 * Get the channel that was passed to StartDocumentLoad or Reset for this
1691 * document. Note that this may be null in some cases (eg if
1692 * StartDocumentLoad or Reset were never called)
1694 nsIChannel* GetChannel() const { return mChannel; }
1697 * Get this document's attribute stylesheet. May return null if
1698 * there isn't one.
1700 AttributeStyles* GetAttributeStyles() const { return mAttributeStyles.get(); }
1702 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1705 * Get/set the object from which the context for the event/script handling can
1706 * be got. Normally GetScriptHandlingObject() returns the same object as
1707 * GetScriptGlobalObject(), but if the document is loaded as data,
1708 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1709 * aHasHadScriptHandlingObject is set true if document has had the object
1710 * for event/script handling. Do not process any events/script if the method
1711 * returns null, but aHasHadScriptHandlingObject is true.
1713 nsIScriptGlobalObject* GetScriptHandlingObject(
1714 bool& aHasHadScriptHandlingObject) const {
1715 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1716 return mScriptGlobalObject ? mScriptGlobalObject.get()
1717 : GetScriptHandlingObjectInternal();
1719 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1722 * Get the object that is used as the scope for all of the content
1723 * wrappers whose owner document is this document. Unlike the script global
1724 * object, this will only return null when the global object for this
1725 * document is truly gone. Use this object when you're trying to find a
1726 * content wrapper in XPConnect.
1728 nsIGlobalObject* GetScopeObject() const;
1729 void SetScopeObject(nsIGlobalObject* aGlobal);
1732 * Return the window containing the document (the outer window).
1734 nsPIDOMWindowOuter* GetWindow() const {
1735 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1738 bool IsInBackgroundWindow() const {
1739 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1740 return outer && outer->IsBackground();
1744 * Return the inner window used as the script compilation scope for
1745 * this document. If you're not absolutely sure you need this, use
1746 * GetWindow().
1748 nsPIDOMWindowInner* GetInnerWindow() const {
1749 return mRemovedFromDocShell ? nullptr : mWindow;
1753 * Return the outer window ID.
1755 uint64_t OuterWindowID() const {
1756 nsPIDOMWindowOuter* window = GetWindow();
1757 return window ? window->WindowID() : 0;
1761 * Return the inner window ID.
1763 uint64_t InnerWindowID() const {
1764 nsPIDOMWindowInner* window = GetInnerWindow();
1765 return window ? window->WindowID() : 0;
1769 * Return WindowGlobalChild that is associated with the inner window.
1771 WindowGlobalChild* GetWindowGlobalChild() {
1772 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1773 : nullptr;
1777 * Return WindowContext associated with the inner window.
1779 WindowContext* GetWindowContext() const {
1780 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1783 bool IsTopLevelWindowInactive() const {
1784 return mState.HasState(DocumentState::WINDOW_INACTIVE);
1788 * Get the script loader for this document
1790 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1793 * Add/Remove an element to the document's id and name hashes
1795 void AddToIdTable(Element* aElement, nsAtom* aId);
1796 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1797 void AddToNameTable(Element* aElement, nsAtom* aName);
1798 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1801 * Returns all elements in the top layer in the insertion order.
1803 nsTArray<Element*> GetTopLayer() const;
1805 bool TopLayerContains(Element&) const;
1807 // Do the "fullscreen element ready check" from the fullscreen spec.
1808 // It returns true if the given element is allowed to go into fullscreen.
1809 // It is responsive to dispatch "fullscreenerror" event when necessary.
1810 bool FullscreenElementReadyCheck(FullscreenRequest&);
1813 * When this is called on content process, this asynchronously requests that
1814 * the document make aElement the fullscreen element, and move into fullscreen
1815 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1816 * and it can be returned to fullscreen status by calling
1817 * RestorePreviousFullscreenState().
1818 * If on chrome process, this is synchronously.
1820 * Note that requesting fullscreen in a document also makes the element which
1821 * contains this document in this document's parent document fullscreen. i.e.
1822 * the <iframe> or <browser> that contains this document is also mode
1823 * fullscreen. This happens recursively in all ancestor documents.
1825 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1826 bool aApplyFullscreenDirectly = false);
1828 private:
1829 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1830 bool aApplyFullscreenDirectly);
1831 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1832 bool aApplyFullscreenDirectly);
1834 // Pushes aElement onto the top layer
1835 void TopLayerPush(Element&);
1837 // Removes the topmost element for which aPredicate returns true from the top
1838 // layer. The removed element, if any, is returned.
1839 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicate);
1841 // Removes the given element from the top layer. The removed element, if any,
1842 // is returned.
1843 Element* TopLayerPop(Element&);
1845 MOZ_CAN_RUN_SCRIPT bool TryAutoFocusCandidate(Element& aElement);
1847 public:
1848 // Removes all the elements with fullscreen flag set from the top layer, and
1849 // clears their fullscreen flag.
1850 void CleanupFullscreenState();
1852 // Pops the fullscreen element from the top layer and clears its
1853 // fullscreen flag. Returns whether there was any fullscreen element.
1854 enum class UpdateViewport : bool { No, Yes };
1855 bool PopFullscreenElement(UpdateViewport = UpdateViewport::Yes);
1857 // Pushes the given element into the top of top layer and set fullscreen
1858 // flag.
1859 void SetFullscreenElement(Element&);
1861 // Whether we has pending fullscreen request.
1862 bool HasPendingFullscreenRequests();
1865 * When Esc key is pressed, cancel the dialog element if the document is
1866 * blocked by the dialog or hide popover if popover is shown.
1868 MOZ_CAN_RUN_SCRIPT void HandleEscKey();
1870 void AddModalDialog(HTMLDialogElement&);
1871 void RemoveModalDialog(HTMLDialogElement&);
1874 * Called when a frame in a child process has entered fullscreen or when a
1875 * fullscreen frame in a child process changes to another origin.
1876 * aFrameElement is the frame element which contains the child-process
1877 * fullscreen document.
1879 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1882 * Called when a frame in a remote child document has rolled back fullscreen
1883 * so that all its top layer are empty; we must continue the
1884 * rollback in this parent process' doc tree branch which is fullscreen.
1885 * Note that only one branch of the document tree can have its documents in
1886 * fullscreen state at one time. We're in inconsistent state if a
1887 * fullscreen document has a parent and that parent isn't fullscreen. We
1888 * preserve this property across process boundaries.
1890 void RemoteFrameFullscreenReverted();
1893 * Restores the previous fullscreen element to fullscreen status. If there
1894 * is no former fullscreen element, this exits fullscreen, moving the
1895 * top-level browser window out of fullscreen mode.
1897 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1900 * Returns true if this document is a fullscreen leaf document, i.e. it
1901 * is in fullscreen mode and has no fullscreen children.
1903 bool IsFullscreenLeaf();
1906 * Returns the document which is at the root of this document's branch
1907 * in the in-process document tree. Returns nullptr if the document isn't
1908 * fullscreen.
1910 Document* GetFullscreenRoot() const { return mFullscreenRoot; }
1912 size_t CountFullscreenElements() const;
1915 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1916 * in this document.
1918 void SetFullscreenRoot(Document* aRoot) { mFullscreenRoot = aRoot; }
1921 * Synchronously cleans up the fullscreen state on the given document.
1923 * Calling this without performing fullscreen transition could lead
1924 * to undesired effect (the transition happens after document state
1925 * flips), hence it should only be called either by nsGlobalWindow
1926 * when we have performed the transition, or when it is necessary to
1927 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1928 * should be called instead.
1930 * aDocument must not be null.
1932 static void ExitFullscreenInDocTree(Document* aDocument);
1935 * Ask the document to exit fullscreen state asynchronously.
1937 * Different from ExitFullscreenInDocTree(), this allows the window
1938 * to perform fullscreen transition first if any.
1940 * If aDocument is null, it will exit fullscreen from all documents
1941 * in all windows.
1943 static void AsyncExitFullscreen(Document* aDocument);
1946 * Handles any pending fullscreen in aDocument or its subdocuments.
1948 * Returns whether there is any fullscreen request handled.
1950 static bool HandlePendingFullscreenRequests(Document* aDocument);
1953 * Clear pending fullscreen in aDocument.
1955 static void ClearPendingFullscreenRequests(Document* aDocument);
1957 // ScreenOrientation related APIs
1959 void ClearOrientationPendingPromise();
1960 bool SetOrientationPendingPromise(Promise* aPromise);
1961 Promise* GetOrientationPendingPromise() const {
1962 return mOrientationPendingPromise;
1965 //----------------------------------------------------------------------
1967 // Document notification API's
1970 * Add a new observer of document change notifications. Whenever
1971 * content is changed, appended, inserted or removed the observers are
1972 * informed. An observer that is already observing the document must
1973 * not be added without being removed first.
1975 void AddObserver(nsIDocumentObserver* aObserver);
1978 * Remove an observer of document change notifications. This will
1979 * return false if the observer cannot be found.
1981 bool RemoveObserver(nsIDocumentObserver* aObserver);
1983 // Observation hooks used to propagate notifications to document observers.
1984 // BeginUpdate must be called before any batch of modifications of the
1985 // content model or of style data, EndUpdate must be called afterward.
1986 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1987 void BeginUpdate();
1988 void EndUpdate();
1989 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
1991 void BeginLoad();
1992 virtual void EndLoad();
1994 enum ReadyState {
1995 READYSTATE_UNINITIALIZED = 0,
1996 READYSTATE_LOADING = 1,
1997 READYSTATE_INTERACTIVE = 3,
1998 READYSTATE_COMPLETE = 4
2000 // Set the readystate of the document. If aUpdateTimingInformation is true,
2001 // this will record relevant timestamps in the document's performance timing.
2002 // Some consumers (document.open is the only one right now, actually) don't
2003 // want to do that, though.
2004 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2005 ReadyState GetReadyStateEnum() { return mReadyState; }
2007 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2008 ReadyState aNewState);
2010 void NotifyAbortedLoad();
2012 // Notify that an element changed state. This must happen under a
2013 // scriptblocker but NOT within a begin/end update.
2014 void ElementStateChanged(Element*, ElementState);
2016 // Update a set of document states that may have changed.
2017 // This should only be called by callers whose state is also reflected in the
2018 // implementation of Document::State.
2020 // aNotify controls whether we notify our DocumentStatesChanged observers.
2021 void UpdateDocumentStates(DocumentState aMaybeChangedStates, bool aNotify);
2023 void ResetDocumentDirection();
2025 // Observation hooks for style data to propagate notifications
2026 // to document observers
2027 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2028 void RuleAdded(StyleSheet&, css::Rule&);
2029 void RuleRemoved(StyleSheet&, css::Rule&);
2030 void SheetCloned(StyleSheet&) {}
2031 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2034 * Flush notifications for this document and its parent documents
2035 * (since those may affect the layout of this one).
2037 void FlushPendingNotifications(FlushType aType);
2040 * Another variant of the above FlushPendingNotifications. This function
2041 * takes a ChangesToFlush to specify whether throttled animations are flushed
2042 * or not.
2043 * If in doubt, use the above FlushPendingNotifications.
2045 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2046 void FlushPendingNotifications(ChangesToFlush aFlush);
2049 * Calls FlushPendingNotifications on any external resources this document
2050 * has. If this document has no external resources or is an external resource
2051 * itself this does nothing. This should only be called with
2052 * aType >= FlushType::Style.
2054 void FlushExternalResources(FlushType aType);
2056 void AddWorkerDocumentListener(WorkerDocumentListener* aListener);
2057 void RemoveWorkerDocumentListener(WorkerDocumentListener* aListener);
2059 // Triggers an update of <svg:use> element shadow trees.
2060 void UpdateSVGUseElementShadowTrees() {
2061 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2062 return;
2064 DoUpdateSVGUseElementShadowTrees();
2068 * Only to be used inside Gecko, you can't really do anything with the
2069 * pointer outside Gecko anyway.
2071 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2074 * Reset the document using the given channel and loadgroup. This works
2075 * like ResetToURI, but also sets the document's channel to aChannel.
2076 * The principal of the document will be set from the channel.
2078 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2081 * Reset this document to aURI, aLoadGroup, aPrincipal and
2082 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2083 * content principal based on aURI will be used.
2085 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2086 nsIPrincipal* aPrincipal,
2087 nsIPrincipal* aPartitionedPrincipal);
2090 * Set the container (docshell) for this document. Virtual so that
2091 * docshell can call it.
2093 virtual void SetContainer(nsDocShell* aContainer);
2096 * Get the container (docshell) for this document.
2098 nsISupports* GetContainer() const;
2101 * Get the container's load context for this document.
2103 nsILoadContext* GetLoadContext() const;
2106 * Get docshell the for this document.
2108 nsIDocShell* GetDocShell() const;
2111 * Set and get XML declaration. If aVersion is null there is no declaration.
2112 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2113 * was no standalone parameter in the declaration, that it was given as no,
2114 * or that it was given as yes.
2116 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2117 const int32_t aStandalone);
2118 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2119 nsAString& Standalone);
2122 * Returns the bits for the color-scheme specified by the
2123 * <meta name="color-scheme">.
2125 uint8_t GetColorSchemeBits() const { return mColorSchemeBits; }
2128 * Traverses the DOM and computes the supported color schemes as per
2129 * https://html.spec.whatwg.org/#meta-color-scheme
2131 void RecomputeColorScheme();
2132 void AddColorSchemeMeta(HTMLMetaElement&);
2133 void RemoveColorSchemeMeta(HTMLMetaElement&);
2136 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2137 * regular HTML document with Content-Type "text/html", image documents and
2138 * media documents). Returns false for XHTML and any other documents parsed
2139 * by the XML parser.
2141 bool IsHTMLDocument() const { return mType == eHTML; }
2142 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2143 bool IsImageDocument() const {
2144 return MediaDocumentKind() == MediaDocumentKind::Image;
2146 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2147 bool IsSVGDocument() const { return mType == eSVG; }
2148 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2149 bool LoadsFullXULStyleSheetUpFront() {
2150 if (IsSVGDocument()) {
2151 return false;
2153 return AllowXULXBL();
2156 bool IsScriptEnabled() const;
2159 * Returns true if this document was created from a nsXULPrototypeDocument.
2161 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2163 * Returns the prototype the document was created from, or null if it was not
2164 * created from a prototype.
2166 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2168 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2169 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2170 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2173 bool IsContentDocument() const { return mIsContentDocument; }
2174 void SetIsContentDocument(bool aIsContentDocument) {
2175 mIsContentDocument = aIsContentDocument;
2178 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2180 * Create an element with the specified name, prefix and namespace ID.
2181 * Returns null if element name parsing failed.
2183 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2184 int32_t aNamespaceID,
2185 const nsAString* aIs = nullptr);
2188 * Get the security info (i.e. SSL state etc) that the document got
2189 * from the channel/document that created the content of the
2190 * document.
2192 * @see nsIChannel
2194 nsITransportSecurityInfo* GetSecurityInfo() { return mSecurityInfo; }
2197 * Get the channel that failed to load and resulted in an error page, if it
2198 * exists. This is only relevant to error pages.
2200 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2203 * This function checks if the document that is trying to access
2204 * GetNetErrorInfo is a trusted about net error page or not.
2206 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2209 * This function checks if the document that is trying to access
2210 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2212 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext* aCx,
2213 JSObject* aObject);
2216 * Get security info like error code for a failed channel. This
2217 * property is only exposed to about:neterror documents.
2219 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2222 * This function checks if the document that is trying to access
2223 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2225 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2228 * This function checks if the privilege storage access api is available for
2229 * the caller. We only allow privilege SSA to be called by system principal
2230 * and webcompat extension.
2232 static bool CallerCanAccessPrivilegeSSA(JSContext* aCx, JSObject* aObject);
2235 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2236 * failed Channel. This property is only exposed for about:certerror
2237 * documents.
2239 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2240 ErrorResult& aRv);
2243 * Set the channel that failed to load and resulted in an error page.
2244 * This is only relevant to error pages.
2246 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2249 * Returns the default namespace ID used for elements created in this
2250 * document.
2252 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2254 void RemoveAllProperties();
2255 void RemoveAllPropertiesFor(nsINode* aNode);
2257 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2260 * Sets the ID used to identify this part of the multipart document
2262 void SetPartID(uint32_t aID) { mPartID = aID; }
2265 * Return the ID used to identify this part of the multipart document
2267 uint32_t GetPartID() const { return mPartID; }
2270 * Sanitize the document by resetting all input elements and forms that have
2271 * autocomplete=off to their default values.
2272 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2274 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Sanitize();
2277 * Enumerate all subdocuments.
2278 * The enumerator callback should return CallState::Continue to continue
2279 * enumerating, or CallState::Stop to stop. This will never get passed a null
2280 * aDocument.
2282 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2283 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2286 * Collect all the descendant documents for which |aCalback| returns true.
2287 * The callback function must not mutate any state for the given document.
2289 using nsDocTestFunc = bool (*)(const Document* aDocument);
2290 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2291 nsDocTestFunc aCallback) const;
2294 * Check whether it is safe to cache the presentation of this document
2295 * and all of its subdocuments (depending on the 3rd param). This method
2296 * checks the following conditions recursively:
2297 * - Some document types, such as plugin documents, cannot be safely cached.
2298 * - If there are any pending requests, we don't allow the presentation
2299 * to be cached. Ideally these requests would be suspended and resumed,
2300 * but that is difficult in some cases, such as XMLHttpRequest.
2301 * - If there are any beforeunload or unload listeners, we must fire them
2302 * for correctness, but this likely puts the document into a state where
2303 * it would not function correctly if restored.
2305 * |aNewRequest| should be the request for a new document which will
2306 * replace this document in the docshell. The new document's request
2307 * will be ignored when checking for active requests. If there is no
2308 * request associated with the new document, this parameter may be null.
2310 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2311 * combination is when we try to BFCache aNewRequest
2313 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2314 uint32_t& aBFCacheCombo,
2315 bool aIncludeSubdocuments,
2316 bool aAllowUnloadListeners = true);
2319 * Pass principals if the correct ones are known when calling Init. That way
2320 * NodeInfoManager doesn't need to create a temporary null principal.
2322 virtual nsresult Init(nsIPrincipal* aPrincipal,
2323 nsIPrincipal* aPartitionedPrincipal);
2326 * Notify the document that its associated ContentViewer is being destroyed.
2327 * This releases circular references so that the document can go away.
2328 * Destroy() is only called on documents that have a content viewer.
2330 virtual void Destroy();
2333 * Notify the document that its associated ContentViewer is no longer
2334 * the current viewer for the docshell. The document might still
2335 * be rendered in "zombie state" until the next document is ready.
2336 * The document should save form control state.
2338 void RemovedFromDocShell();
2341 * Get the layout history state that should be used to save and restore state
2342 * for nodes in this document. This may return null; if that happens state
2343 * saving and restoration is not possible.
2345 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2348 * Methods that can be used to prevent onload firing while an event that
2349 * should block onload is posted. onload is guaranteed to not fire until
2350 * either all calls to BlockOnload() have been matched by calls to
2351 * UnblockOnload() or the load has been stopped altogether (by the user
2352 * pressing the Stop button, say).
2354 void BlockOnload();
2356 * @param aFireSync whether to fire onload synchronously. If false,
2357 * onload will fire asynchronously after all onload blocks have been
2358 * removed. It will NOT fire from inside UnblockOnload. If true,
2359 * onload may fire from inside UnblockOnload.
2361 void UnblockOnload(bool aFireSync);
2363 // Only BlockOnload should call this!
2364 void AsyncBlockOnload();
2366 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2368 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnblockDOMContentLoaded();
2371 * Notification that the page has been shown, for documents which are loaded
2372 * into a DOM window. This corresponds to the completion of document load,
2373 * or to the page's presentation being restored into an existing DOM window.
2374 * This notification fires applicable DOM events to the content window. See
2375 * PageTransitionEvent.webidl for a description of the |aPersisted|
2376 * parameter. If aDispatchStartTarget is null, the pageshow event is
2377 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2378 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2379 * event is only dispatched to listeners in the system group.
2380 * Note: if aDispatchStartTarget isn't null, the showing state of the
2381 * document won't be altered.
2383 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2384 bool aOnlySystemGroup = false);
2387 * Notification that the page has been hidden, for documents which are loaded
2388 * into a DOM window. This corresponds to the unloading of the document, or
2389 * to the document's presentation being saved but removed from an existing
2390 * DOM window. This notification fires applicable DOM events to the content
2391 * window. See PageTransitionEvent.webidl for a description of the
2392 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2393 * event is dispatched on the ScriptGlobalObject for this document,
2394 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2395 * true, the event is only dispatched to listeners in the system group.
2396 * Note: if aDispatchStartTarget isn't null, the showing state of the
2397 * document won't be altered.
2399 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2400 bool aOnlySystemGroup = false);
2403 * We record the set of links in the document that are relevant to
2404 * style.
2407 * Notification that an element is a link that is relevant to style.
2409 void AddStyleRelevantLink(Link* aLink) {
2410 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2411 #ifdef DEBUG
2412 NS_ASSERTION(!mStyledLinks.Contains(aLink),
2413 "Document already knows about this Link!");
2414 mStyledLinksCleared = false;
2415 #endif
2416 mStyledLinks.Insert(aLink);
2420 * Notification that an element is a link and its URI might have been
2421 * changed or the element removed. If the element is still a link relevant
2422 * to style, then someone must ensure that AddStyleRelevantLink is
2423 * (eventually) called on it again.
2425 void ForgetLink(Link* aLink) {
2426 MOZ_ASSERT(aLink, "Passing in a null link. Expect crashes RSN!");
2427 MOZ_ASSERT(mStyledLinks.Contains(aLink) || mStyledLinksCleared,
2428 "Document knows nothing about this Link!");
2429 mStyledLinks.Remove(aLink);
2432 // Refreshes the hrefs of all the links in the document.
2433 void RefreshLinkHrefs();
2436 * Support for window.matchMedia()
2439 already_AddRefed<MediaQueryList> MatchMedia(const nsACString& aMediaQueryList,
2440 CallerType aCallerType);
2442 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2444 nsTHashtable<LCPEntryHashEntry>& ContentIdentifiersForLCP() {
2445 return mContentIdentifiersForLCP;
2449 * Get the compatibility mode for this document
2451 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2454 * Check whether we've ever fired a DOMTitleChanged event for this
2455 * document.
2457 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2460 * To batch DOMSubtreeModified, document needs to be informed when
2461 * a mutation event might be dispatched, even if the event isn't actually
2462 * created because there are no listeners for it.
2464 * @param aTarget is the target for the mutation event.
2466 void MayDispatchMutationEvent(nsINode* aTarget) {
2467 if (mSubtreeModifiedDepth > 0) {
2468 mSubtreeModifiedTargets.AppendObject(aTarget);
2473 * Marks as not-going-to-be-collected for the given generation of
2474 * cycle collection.
2476 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2477 mMarkedCCGeneration = aGeneration;
2481 * Gets the cycle collector generation this document is marked for.
2483 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2486 * Returns whether this document is cookie averse. See
2487 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2489 bool IsCookieAverse() const {
2490 // If we are a document that "has no browsing context."
2491 if (!GetInnerWindow()) {
2492 return true;
2495 // If we are a document "whose URL's scheme is not a network scheme."
2496 // NB: Explicitly allow file: URIs to store cookies.
2498 return !NodePrincipal()->SchemeIs("http") &&
2499 !NodePrincipal()->SchemeIs("https") &&
2500 !NodePrincipal()->SchemeIs("file");
2503 bool IsLoadedAsData() { return mLoadedAsData; }
2505 void SetAddedToMemoryReportAsDataDocument() {
2506 mAddedToMemoryReportingAsDataDocument = true;
2509 void UnregisterFromMemoryReportingForDataDocument();
2511 bool MayStartLayout() { return mMayStartLayout; }
2513 void SetMayStartLayout(bool aMayStartLayout);
2515 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2517 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2519 // In case of failure, the document really can't initialize the frame loader.
2520 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2521 // In case of failure, the caller must handle the error, for example by
2522 // finalizing frame loader asynchronously.
2523 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2524 // Removes the frame loader of aShell from the initialization list.
2525 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2528 * Check whether this document is a root document that is not an
2529 * external resource.
2531 bool IsRootDisplayDocument() const {
2532 return !mParentDocument && !mDisplayDocument;
2535 bool ChromeRulesEnabled() const { return mChromeRulesEnabled; }
2537 bool IsInChromeDocShell() const {
2538 const Document* root = this;
2539 while (const Document* displayDoc = root->GetDisplayDocument()) {
2540 root = displayDoc;
2542 return root->mInChromeDocShell;
2545 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2547 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2549 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2551 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2553 bool IsResourceDoc() const {
2554 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2555 mHasDisplayDocument; // Are we an external resource doc?
2559 * Get the document for which this document is an external resource. This
2560 * will be null if this document is not an external resource. Otherwise,
2561 * GetDisplayDocument() will return a non-null document, and
2562 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2564 Document* GetDisplayDocument() const { return mDisplayDocument; }
2567 * Set the display document for this document. aDisplayDocument must not be
2568 * null.
2570 void SetDisplayDocument(Document* aDisplayDocument) {
2571 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2572 "Shouldn't set mDisplayDocument on documents that already "
2573 "have a presentation or a docshell or a window");
2574 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2575 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2576 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2577 "Display documents should not nest");
2578 mDisplayDocument = aDisplayDocument;
2579 mHasDisplayDocument = !!aDisplayDocument;
2583 * Request an external resource document for aURI. This will return the
2584 * resource document if available. If one is not available yet, it will
2585 * start loading as needed, and the pending load object will be returned in
2586 * aPendingLoad so that the caller can register an observer to wait for the
2587 * load. If this function returns null and doesn't return a pending load,
2588 * that means that there is no resource document for this URI and won't be
2589 * one in the future.
2591 * @param aURI the URI to get
2592 * @param aReferrerInfo the referrerInfo of the request
2593 * @param aRequestingNode the node making the request
2594 * @param aPendingLoad the pending load for this request, if any
2596 Document* RequestExternalResource(nsIURI* aURI,
2597 nsIReferrerInfo* aReferrerInfo,
2598 nsINode* aRequestingNode,
2599 ExternalResourceLoad** aPendingLoad);
2602 * Enumerate the external resource documents associated with this document.
2603 * The enumerator callback should return CallState::Continue to continue
2604 * enumerating, or CallState::Stop to stop. This callback will never get
2605 * passed a null aDocument.
2607 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2609 dom::ExternalResourceMap& ExternalResourceMap() {
2610 return mExternalResourceMap;
2614 * Return whether the document is currently showing (in the sense of
2615 * OnPageShow() having been called already and OnPageHide() not having been
2616 * called yet.
2618 bool IsShowing() const { return mIsShowing; }
2620 * Return whether the document is currently visible (in the sense of
2621 * OnPageHide having been called and OnPageShow not yet having been called)
2623 bool IsVisible() const { return mVisible; }
2625 void SetSuppressedEventListener(EventListener* aListener);
2627 EventListener* GetSuppressedEventListener() {
2628 return mSuppressedEventListener;
2632 * Return true when this document is active, i.e., an active document
2633 * in a content viewer and not in the bfcache.
2634 * This does NOT match the "active document" concept in the WHATWG spec -
2635 * see IsCurrentActiveDocument.
2637 bool IsActive() const;
2640 * Return true if this is the current active document for its
2641 * docshell. Note that a docshell may have multiple active documents
2642 * due to the bfcache -- this should be used when you need to
2643 * differentiate the *current* active document from any active
2644 * documents.
2646 bool IsCurrentActiveDocument() const {
2647 nsPIDOMWindowInner* inner = GetInnerWindow();
2648 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2652 * Returns whether this document should perform image loads.
2654 bool ShouldLoadImages() const {
2655 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2656 // images can themselves have data: URL image references.
2657 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2658 IsStaticDocument();
2661 void SetHasPrintCallbacks() {
2662 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2663 mHasPrintCallbacks = true;
2666 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2669 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2670 * the document's activity changes such as OnPageHide, visibility, activity.
2671 * The ActivityObserver objects can be nsIObjectLoadingContent or
2672 * nsIDocumentActivity or HTMLMEdiaElement.
2674 void RegisterActivityObserver(nsISupports* aSupports);
2675 bool UnregisterActivityObserver(nsISupports* aSupports);
2676 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2677 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2678 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2680 void NotifyActivityChanged();
2682 // Indicates whether mAnimationController has been (lazily) initialized.
2683 // If this returns true, we're promising that GetAnimationController()
2684 // will have a non-null return value.
2685 bool HasAnimationController() { return !!mAnimationController; }
2687 // Getter for this document's SMIL Animation Controller. Performs lazy
2688 // initialization, if this document supports animation and if
2689 // mAnimationController isn't yet initialized.
2691 // If HasAnimationController is true, this is guaranteed to return non-null.
2692 SMILAnimationController* GetAnimationController();
2694 // Gets the tracker for scroll-driven animations that are waiting to start.
2695 // Returns nullptr if there is no scroll-driven animation tracker for this
2696 // document which will be the case if there have never been any scroll-driven
2697 // animations in the document.
2698 ScrollTimelineAnimationTracker* GetScrollTimelineAnimationTracker() {
2699 return mScrollTimelineAnimationTracker;
2702 // Gets the tracker for scroll-driven animations that are waiting to start and
2703 // creates it if it doesn't already exist. As a result, the return value
2704 // will never be nullptr.
2705 ScrollTimelineAnimationTracker* GetOrCreateScrollTimelineAnimationTracker();
2708 * Prevents user initiated events from being dispatched to the document and
2709 * subdocuments.
2711 void SuppressEventHandling(uint32_t aIncrease = 1);
2714 * Unsuppress event handling.
2715 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2716 * asynchronously.
2718 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnsuppressEventHandlingAndFireEvents(
2719 bool aFireEvents);
2721 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2723 bool IsEventHandlingEnabled() const {
2724 return !EventHandlingSuppressed() && mScriptGlobalObject;
2727 bool WouldScheduleFrameRequestCallbacks() const {
2728 // If this function changes to depend on some other variable, make sure to
2729 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2730 // where that variable can change.
2731 return mPresShell && IsEventHandlingEnabled();
2734 void DecreaseEventSuppression() {
2735 MOZ_ASSERT(mEventsSuppressed);
2736 --mEventsSuppressed;
2737 UpdateFrameRequestCallbackSchedulingState();
2741 * Some clipboard commands are unconditionally enabled on some documents, so
2742 * as to always dispatch copy / paste events even though you'd normally not be
2743 * able to copy.
2745 bool AreClipboardCommandsUnconditionallyEnabled() const;
2748 * Note a ChannelEventQueue which has been suspended on the document's behalf
2749 * to prevent XHRs from running content scripts while event handling is
2750 * suppressed. The document is responsible for resuming the queue after
2751 * event handling is unsuppressed.
2753 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2756 * Returns true if a postMessage event should be suspended instead of running.
2757 * The document is responsible for running the event later, in the order they
2758 * were received.
2760 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2763 * Run any suspended postMessage events, or clear them.
2765 void FireOrClearPostMessageEvents(bool aFireEvents);
2767 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2770 * Flag whether we're about to fire the window's load event for this document.
2772 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2775 * Test whether we should be firing a load event for this document after a
2776 * document.close(). This is public and on Document, instead of being private
2777 * to Document, because we need to go through the normal docloader logic
2778 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2779 * semantics of firing the load event; we just don't want to fire the load
2780 * event if this tests true. So we need the docloader to be able to access
2781 * this state.
2783 * This method should only be called at the point when the load event is about
2784 * to be fired. It resets the "skip" flag, so it is not idempotent.
2786 bool SkipLoadEventAfterClose() {
2787 bool skip = mSkipLoadEventAfterClose;
2788 mSkipLoadEventAfterClose = false;
2789 return skip;
2793 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2795 void IncrementIgnoreDestructiveWritesCounter() {
2796 ++mIgnoreDestructiveWritesCounter;
2800 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2802 void DecrementIgnoreDestructiveWritesCounter() {
2803 --mIgnoreDestructiveWritesCounter;
2806 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2809 * Returns true if this document is allowed to contain XUL element and
2810 * use non-builtin XBL bindings.
2812 bool AllowXULXBL() {
2813 return mAllowXULXBL == eTriTrue ? true
2814 : mAllowXULXBL == eTriFalse ? false
2815 : InternalAllowXULXBL();
2819 * Returns true if this document is allowed to load DTDs from UI resources
2820 * no matter what.
2822 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2824 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2826 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2829 * Returns the template content owner document that owns the content of
2830 * HTMLTemplateElement.
2832 Document* GetTemplateContentsOwner();
2834 Document* GetTemplateContentsOwnerIfExists() const {
2835 return mTemplateContentsOwner.get();
2838 bool IsTemplateContentsOwner() const {
2839 // Template contents owner documents are the template contents owner of
2840 // themselves.
2841 return mTemplateContentsOwner == this;
2845 * Returns true if this document is a static clone of a normal document.
2847 * We create static clones for print preview and printing (possibly other
2848 * things in future).
2850 * Note that static documents are also "loaded as data" (if this method
2851 * returns true, IsLoadedAsData() will also return true).
2853 bool IsStaticDocument() const { return mIsStaticDocument; }
2856 * Clones the document along with any subdocuments, stylesheet, etc.
2858 * The resulting document and everything it contains (including any
2859 * sub-documents) are created purely via cloning. The returned documents and
2860 * any sub-documents are "loaded as data" documents to preserve the state as
2861 * it was during the clone process (we don't want external resources to load
2862 * and replace the cloned resources).
2864 * @param aCloneContainer The container for the clone document.
2865 * @param aDocumentViewer The viewer for the clone document. Must be the
2866 * viewer of aCloneContainer, but callers must have a
2867 * reference to it already and ensure it's not null.
2868 * @param aPrintSettings The print settings for this clone.
2869 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2871 already_AddRefed<Document> CreateStaticClone(
2872 nsIDocShell* aCloneContainer, nsIDocumentViewer* aDocumentViewer,
2873 nsIPrintSettings* aPrintSettings, bool* aOutHasInProcessPrintCallbacks);
2876 * If this document is a static clone, this returns the original
2877 * document.
2879 Document* GetOriginalDocument() const {
2880 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2881 return mOriginalDocument;
2885 * If this document is a static clone, let the original document know that
2886 * we're going away and then release our reference to it.
2888 void UnlinkOriginalDocumentIfStatic();
2891 * These are called by the parser as it encounters <picture> tags, the end of
2892 * said tags, and possible picture <source srcset> sources respectively. These
2893 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2894 * expected to be marked void.
2896 * NOTE that the parser does not attempt to track the current picture nesting
2897 * level or whether the given <source> tag is within a picture -- it is only
2898 * guaranteed to order these calls properly with respect to
2899 * ResolvePreLoadImage.
2902 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2904 void PreloadPictureClosed();
2906 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2907 const nsAString& aSizesAttr,
2908 const nsAString& aTypeAttr,
2909 const nsAString& aMediaAttr);
2912 * Called by the parser to resolve an image for preloading. The parser will
2913 * call the PreloadPicture* functions to inform us of possible <picture>
2914 * nesting and possible sources, which are used to inform URL selection
2915 * responsive <picture> or <img srcset> images. Unset attributes are expected
2916 * to be marked void.
2917 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2918 * true, false otherwise.
2920 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2921 const nsAString& aSrcAttr,
2922 const nsAString& aSrcsetAttr,
2923 const nsAString& aSizesAttr,
2924 bool* aIsImgSet);
2926 * Called by nsParser to preload images. Can be removed and code moved
2927 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2928 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2929 * be a void string if the attr is not present.
2930 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2931 * when this image is for loading <picture> or <img srcset> images.
2933 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2934 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2935 bool aLinkPreload, const nsAString& aFetchPriority);
2936 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2937 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2938 bool aLinkPreload, uint64_t aEarlyHintPreloaderId,
2939 const nsAString& aFetchPriority);
2942 * Called by images to forget an image preload when they start doing
2943 * the real load.
2945 void ForgetImagePreload(nsIURI* aURI);
2948 * Called by the parser or the preload service to preload style sheets.
2949 * aCrossOriginAttr should be a void string if the attr is not present.
2951 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2952 const nsAString& aCrossOriginAttr,
2953 ReferrerPolicyEnum aReferrerPolicy,
2954 const nsAString& aNonce,
2955 const nsAString& aIntegrity,
2956 css::StylePreloadKind,
2957 uint64_t aEarlyHintPreloaderId,
2958 const nsAString& aFetchPriority);
2961 * Called by the chrome registry to load style sheets.
2963 * This always does a synchronous load, and parses as a normal document sheet.
2965 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2968 * Returns true if the locale used for the document specifies a direction of
2969 * right to left. For chrome documents, this comes from the chrome registry.
2970 * This is used to determine the current state for the :-moz-locale-dir
2971 * pseudoclass so once can know whether a document is expected to be rendered
2972 * left-to-right or right-to-left.
2974 bool IsDocumentRightToLeft();
2977 * Called by Parser for link rel=preconnect
2979 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2982 * Set the document's pending state object (as serialized using structured
2983 * clone).
2985 void SetStateObject(nsIStructuredCloneContainer* scContainer);
2988 * Set the document's pending state object to the same state object as
2989 * aDocument.
2991 void SetStateObjectFrom(Document* aDocument) {
2992 SetStateObject(aDocument->mStateObjectContainer);
2995 // Whether we're a media document or not.
2996 enum class MediaDocumentKind {
2997 NotMedia,
2998 Video,
2999 Image,
3000 Plugin,
3003 virtual enum MediaDocumentKind MediaDocumentKind() const {
3004 return MediaDocumentKind::NotMedia;
3007 DocumentState State() const { return mState; }
3009 nsISupports* GetCurrentContentSink();
3011 void ElementWithAutoFocusInserted(Element* aAutoFocusCandidate);
3012 MOZ_CAN_RUN_SCRIPT void FlushAutoFocusCandidates();
3013 void ScheduleFlushAutoFocusCandidates();
3014 bool HasAutoFocusCandidates() const {
3015 return !mAutoFocusCandidates.IsEmpty();
3018 void SetAutoFocusFired();
3020 void SetScrollToRef(nsIURI* aDocumentURI);
3021 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3022 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3024 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3025 mChangeScrollPosWhenScrollingToRef = aValue;
3028 using DocumentOrShadowRoot::GetElementById;
3029 using DocumentOrShadowRoot::GetElementsByClassName;
3030 using DocumentOrShadowRoot::GetElementsByTagName;
3031 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3033 DocumentTimeline* Timeline();
3034 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3035 void UpdateHiddenByContentVisibilityForAnimations();
3037 SVGSVGElement* GetSVGRootElement() const;
3039 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3040 int32_t* aHandle);
3041 void CancelFrameRequestCallback(int32_t aHandle);
3044 * Returns true if the handle refers to a callback that was canceled that
3045 * we did not find in our list of callbacks (e.g. because it is one of those
3046 * in the set of callbacks currently queued to be run).
3048 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3051 * Put this document's frame request callbacks into the provided
3052 * list, and forget about them.
3054 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3057 * @return true if this document's frame request callbacks should be
3058 * throttled. We throttle requestAnimationFrame for documents which aren't
3059 * visible (e.g. scrolled out of the viewport).
3061 bool ShouldThrottleFrameRequests() const;
3063 // This returns true when the document tree is being teared down.
3064 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3066 dom::ImageTracker* ImageTracker();
3068 // Adds an element to mResponsiveContent when the element is
3069 // added to the tree.
3070 void AddResponsiveContent(HTMLImageElement* aContent) {
3071 MOZ_ASSERT(aContent);
3072 mResponsiveContent.Insert(aContent);
3075 // Removes an element from mResponsiveContent when the element is
3076 // removed from the tree.
3077 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3078 MOZ_ASSERT(aContent);
3079 mResponsiveContent.Remove(aContent);
3082 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3083 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3084 mSVGUseElementsNeedingShadowTreeUpdate.Remove(&aElement);
3087 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3088 return mSVGUseElementsNeedingShadowTreeUpdate.Contains(&aElement);
3091 using ShadowRootSet = nsTHashSet<ShadowRoot*>;
3093 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3094 mComposedShadowRoots.Insert(&aShadowRoot);
3097 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3098 mComposedShadowRoots.Remove(&aShadowRoot);
3101 // If you're considering using this, you probably want to use
3102 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3103 // sanity-checking.
3104 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3105 return mComposedShadowRoots.Contains(&aShadowRoot);
3108 const ShadowRootSet& ComposedShadowRoots() const {
3109 return mComposedShadowRoots;
3112 // WebIDL method for chrome code.
3113 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3115 // Notifies any responsive content added by AddResponsiveContent upon media
3116 // features values changing.
3117 void NotifyMediaFeatureValuesChanged();
3119 nsresult GetStateObject(JS::MutableHandle<JS::Value> aState);
3121 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3123 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3125 nsContentList* ImageMapList();
3127 // Add aLink to the set of links that need their status resolved.
3128 void RegisterPendingLinkUpdate(Link* aLink);
3130 // Update state on links in mLinksToUpdate.
3131 void FlushPendingLinkUpdates();
3133 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3134 void WarnOnceAbout(
3135 DeprecatedOperations aOperation, bool asError = false,
3136 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3138 #define DOCUMENT_WARNING(_op) e##_op,
3139 enum DocumentWarnings {
3140 #include "nsDocumentWarningList.h"
3141 eDocumentWarningCount
3143 #undef DOCUMENT_WARNING
3144 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3145 void WarnOnceAbout(
3146 DocumentWarnings aWarning, bool asError = false,
3147 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3149 // This method may fire a DOM event; if it does so it will happen
3150 // synchronously.
3152 // Whether the event fires is controlled by the argument.
3153 enum class DispatchVisibilityChange { No, Yes };
3154 void UpdateVisibilityState(
3155 DispatchVisibilityChange = DispatchVisibilityChange::Yes);
3157 // Posts an event to call UpdateVisibilityState.
3158 void PostVisibilityUpdateEvent();
3160 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3162 // Adds the size of a given node, which must not be a document node, to the
3163 // window sizes passed-in.
3164 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3166 // Note: Document is a sub-class of nsINode, which has a
3167 // SizeOfExcludingThis function. However, because Document objects can
3168 // only appear at the top of the DOM tree, we have a specialized measurement
3169 // function which returns multiple sizes.
3170 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3171 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3172 // because Document inherits from nsINode; see the comment above the
3173 // declaration of nsINode::SizeOfIncludingThis.
3174 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3176 void ConstructUbiNode(void* storage) override;
3178 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3180 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3182 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3184 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3186 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3188 void SetIsInSyncOperation(bool aSync);
3190 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3193 * Creates a new element in the HTML namespace with a local name given by
3194 * aTag.
3196 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3198 // WebIDL API
3199 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3200 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3201 ErrorResult& rv);
3202 DOMImplementation* GetImplementation(ErrorResult& rv);
3203 [[nodiscard]] nsresult GetURL(nsString& retval) const;
3204 [[nodiscard]] nsresult GetDocumentURI(nsString& retval) const;
3205 // Return the URI for the document.
3206 // The returned value may differ if the document is loaded via XHR, and
3207 // when accessed from chrome privileged script and
3208 // from content privileged script for compatibility.
3209 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3210 ErrorResult& aRv) const;
3211 void GetCompatMode(nsString& retval) const;
3212 void GetCharacterSet(nsAString& retval) const;
3213 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3214 // GetDoctype defined above
3215 Element* GetDocumentElement() const { return GetRootElement(); }
3217 WindowContext* GetTopLevelWindowContext() const;
3219 // If the top-level ancestor content document for this document is in the same
3220 // process, returns it. Otherwise, returns null. This function is not
3221 // Fission-compatible, and should not be used in new code.
3222 Document* GetTopLevelContentDocumentIfSameProcess();
3223 const Document* GetTopLevelContentDocumentIfSameProcess() const;
3225 // Returns the associated app window if this is a top-level chrome document,
3226 // null otherwise.
3227 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3229 already_AddRefed<Element> CreateElement(
3230 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3231 ErrorResult& rv);
3232 already_AddRefed<Element> CreateElementNS(
3233 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3234 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3235 already_AddRefed<Element> CreateXULElement(
3236 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3237 ErrorResult& aRv);
3238 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3239 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3240 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3241 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3242 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3243 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3244 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3245 ErrorResult& rv) const;
3246 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3247 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* AdoptNode(
3248 nsINode& aAdoptedNode, ErrorResult& rv, bool aAcceptShadowRoot = false);
3249 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3250 CallerType aCallerType,
3251 ErrorResult& rv) const;
3252 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3253 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3254 uint32_t aWhatToShow,
3255 NodeFilter* aFilter,
3256 ErrorResult& rv) const;
3257 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3258 uint32_t aWhatToShow,
3259 NodeFilter* aFilter,
3260 ErrorResult& rv) const;
3261 // Deprecated WebIDL bits
3262 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3263 ErrorResult& rv);
3264 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3265 ErrorResult& rv);
3266 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3267 const nsAString& aQualifiedName,
3268 ErrorResult& rv);
3269 void GetInputEncoding(nsAString& aInputEncoding) const;
3270 already_AddRefed<Location> GetLocation() const;
3271 void GetDomain(nsAString& aDomain);
3272 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3273 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3274 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3275 void GetReferrer(nsAString& aReferrer) const;
3276 void GetLastModified(nsAString& aLastModified) const;
3277 void GetReadyState(nsAString& aReadyState) const;
3279 void GetTitle(nsAString& aTitle);
3280 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3281 void GetDir(nsAString& aDirection) const;
3282 void SetDir(const nsAString& aDirection);
3283 nsIHTMLCollection* Images();
3284 nsIHTMLCollection* Embeds();
3285 nsIHTMLCollection* Plugins() { return Embeds(); }
3286 nsIHTMLCollection* Links();
3287 nsIHTMLCollection* Forms();
3288 nsIHTMLCollection* Scripts();
3289 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3290 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3291 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3293 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3294 const mozilla::dom::Optional<nsAString>& /* unused */,
3295 mozilla::ErrorResult& aError);
3296 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3297 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3298 mozilla::ErrorResult& rv);
3299 void Close(mozilla::ErrorResult& rv);
3300 void Write(const mozilla::dom::Sequence<nsString>& aText,
3301 mozilla::ErrorResult& rv);
3302 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3303 mozilla::ErrorResult& rv);
3304 Nullable<WindowProxyHolder> GetDefaultView() const;
3305 Element* GetActiveElement();
3306 enum class IncludeChromeOnly : bool { No, Yes };
3307 // TODO(emilio): Audit callers and remove the default argument, some seem like
3308 // they could want the IncludeChromeOnly::Yes version.
3309 nsIContent* GetUnretargetedFocusedContent(
3310 IncludeChromeOnly = IncludeChromeOnly::No) const;
3312 * Return true if this document or a subdocument has focus.
3314 bool HasFocus(ErrorResult& rv) const;
3317 * Return true if this document itself has focus.
3319 bool ThisDocumentHasFocus() const;
3321 void GetDesignMode(nsAString& aDesignMode);
3322 void SetDesignMode(const nsAString& aDesignMode,
3323 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3324 void SetDesignMode(const nsAString& aDesignMode,
3325 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3326 mozilla::ErrorResult& rv);
3327 MOZ_CAN_RUN_SCRIPT
3328 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3329 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3330 mozilla::ErrorResult& aRv);
3331 MOZ_CAN_RUN_SCRIPT bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3332 nsIPrincipal& aSubjectPrincipal,
3333 mozilla::ErrorResult& aRv);
3334 MOZ_CAN_RUN_SCRIPT bool QueryCommandIndeterm(
3335 const nsAString& aHTMLCommandName, mozilla::ErrorResult& aRv);
3336 MOZ_CAN_RUN_SCRIPT bool QueryCommandState(const nsAString& aHTMLCommandName,
3337 mozilla::ErrorResult& aRv);
3338 MOZ_CAN_RUN_SCRIPT bool QueryCommandSupported(
3339 const nsAString& aHTMLCommandName, mozilla::dom::CallerType aCallerType,
3340 mozilla::ErrorResult& aRv);
3341 MOZ_CAN_RUN_SCRIPT void QueryCommandValue(const nsAString& aHTMLCommandName,
3342 nsAString& aValue,
3343 mozilla::ErrorResult& aRv);
3344 nsIHTMLCollection* Applets();
3345 nsIHTMLCollection* Anchors();
3346 TimeStamp LastFocusTime() const;
3347 void SetLastFocusTime(const TimeStamp& aFocusTime);
3348 // Event handlers are all on nsINode already
3349 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3350 Element* GetCurrentScript();
3351 void ReleaseCapture() const;
3352 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3353 nsIURI* GetDocumentURIObject() const;
3354 // Not const because all the fullscreen goop is not const
3355 const char* GetFullscreenError(CallerType);
3356 bool FullscreenEnabled(CallerType aCallerType) {
3357 return !GetFullscreenError(aCallerType);
3360 void GetWireframeWithoutFlushing(bool aIncludeNodes, Nullable<Wireframe>&);
3362 MOZ_CAN_RUN_SCRIPT void GetWireframe(bool aIncludeNodes,
3363 Nullable<Wireframe>&);
3365 // Hides all popovers until the given end point, see
3366 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3367 MOZ_CAN_RUN_SCRIPT void HideAllPopoversUntil(nsINode& aEndpoint,
3368 bool aFocusPreviousElement,
3369 bool aFireEvents);
3371 MOZ_CAN_RUN_SCRIPT_BOUNDARY void HideAllPopoversWithoutRunningScript();
3372 // Hides the given popover element, see
3373 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3374 MOZ_CAN_RUN_SCRIPT void HidePopover(Element& popover,
3375 bool aFocusPreviousElement,
3376 bool aFireEvents, ErrorResult& aRv);
3378 // Returns a list of all the elements in the Document's top layer whose
3379 // popover attribute is in the auto state.
3380 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3381 nsTArray<Element*> AutoPopoverList() const;
3383 // Return document's auto popover list's last element.
3384 // See
3385 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3386 Element* GetTopmostAutoPopover() const;
3388 // Adds/removes an element to/from the auto popover list.
3389 void AddToAutoPopoverList(Element&);
3390 void RemoveFromAutoPopoverList(Element&);
3392 void AddPopoverToTopLayer(Element&);
3393 void RemovePopoverFromTopLayer(Element&);
3395 Element* GetTopLayerTop();
3396 // Return the fullscreen element in the top layer
3397 Element* GetUnretargetedFullscreenElement() const;
3398 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3399 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3400 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3401 void GetFgColor(nsAString& aFgColor);
3402 void SetFgColor(const nsAString& aFgColor);
3403 void GetLinkColor(nsAString& aLinkColor);
3404 void SetLinkColor(const nsAString& aLinkColor);
3405 void GetVlinkColor(nsAString& aAvlinkColor);
3406 void SetVlinkColor(const nsAString& aVlinkColor);
3407 void GetAlinkColor(nsAString& aAlinkColor);
3408 void SetAlinkColor(const nsAString& aAlinkColor);
3409 void GetBgColor(nsAString& aBgColor);
3410 void SetBgColor(const nsAString& aBgColor);
3411 void Clear() const {
3412 // Deprecated
3414 void CaptureEvents();
3415 void ReleaseEvents();
3417 mozilla::dom::HTMLAllCollection* All();
3419 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3420 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3421 JSObject* aObject);
3422 // Checks that the caller is either chrome or some addon.
3423 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3425 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3426 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3428 public:
3429 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3430 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3431 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3432 aSheetSet = mLastStyleSheetSet;
3434 const nsString& GetCurrentStyleSheetSet() const {
3435 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3436 : mLastStyleSheetSet;
3438 void SetPreferredStyleSheetSet(const nsAString&);
3439 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3440 aSheetSet = mPreferredStyleSheetSet;
3442 DOMStringList* StyleSheetSets();
3443 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3446 * Retrieve the location of the caret position (DOM node and character
3447 * offset within that node), given a point.
3449 * @param aX Horizontal point at which to determine the caret position, in
3450 * page coordinates.
3451 * @param aY Vertical point at which to determine the caret position, in
3452 * page coordinates.
3454 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3455 float aY);
3457 Element* GetScrollingElement();
3458 // A way to check whether a given element is what would get returned from
3459 // GetScrollingElement. It can be faster than comparing to the return value
3460 // of GetScrollingElement() due to being able to avoid flushes in various
3461 // cases. This method assumes that null is NOT passed.
3462 bool IsScrollingElement(Element* aElement);
3464 // QuerySelector and QuerySelectorAll already defined on nsINode
3466 UniquePtr<XPathExpression> CreateExpression(const nsAString& aExpression,
3467 XPathNSResolver* aResolver,
3468 ErrorResult& rv);
3469 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3470 already_AddRefed<XPathResult> Evaluate(
3471 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3472 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3473 ErrorResult& rv);
3474 // Touch event handlers already on nsINode
3475 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3476 EventTarget* aTarget, int32_t aIdentifier,
3477 int32_t aPageX, int32_t aPageY,
3478 int32_t aScreenX, int32_t aScreenY,
3479 int32_t aClientX, int32_t aClientY,
3480 int32_t aRadiusX, int32_t aRadiusY,
3481 float aRotationAngle, float aForce);
3482 already_AddRefed<TouchList> CreateTouchList();
3483 already_AddRefed<TouchList> CreateTouchList(
3484 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3485 already_AddRefed<TouchList> CreateTouchList(
3486 const Sequence<OwningNonNull<Touch>>& aTouches);
3488 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3489 mStyleSheetChangeEventsEnabled = aValue;
3492 bool StyleSheetChangeEventsEnabled() const {
3493 return mStyleSheetChangeEventsEnabled;
3496 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue) {
3497 mDevToolsAnonymousAndShadowEventsEnabled = aValue;
3499 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3500 return mDevToolsAnonymousAndShadowEventsEnabled;
3503 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3504 const BlockParsingOptions& aOptions,
3505 ErrorResult& aRv);
3507 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3509 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3511 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock) {
3512 if (aBlock) {
3513 BlockOnload();
3514 } else {
3515 UnblockOnload(/* aFireSync = */ false);
3519 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3520 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3521 void InitializeXULBroadcastManager();
3522 XULBroadcastManager* GetXULBroadcastManager() const {
3523 return mXULBroadcastManager;
3525 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3526 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3528 bool DevToolsWatchingDOMMutations() const {
3529 return mDevToolsWatchingDOMMutations;
3531 void SetDevToolsWatchingDOMMutations(bool aValue);
3533 void MaybeWarnAboutZoom();
3535 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3536 void EvaluateMediaQueriesAndReportChanges(bool aRecurse);
3538 nsTHashSet<RefPtr<WakeLockSentinel>>& ActiveWakeLocks(WakeLockType aType);
3540 void UnlockAllWakeLocks(WakeLockType aType);
3542 // ParentNode
3543 nsIHTMLCollection* Children();
3544 uint32_t ChildElementCount();
3547 * Asserts IsHTMLOrXHTML, and can't return null.
3548 * Defined inline in nsHTMLDocument.h
3550 inline nsHTMLDocument* AsHTMLDocument();
3551 inline const nsHTMLDocument* AsHTMLDocument() const;
3554 * Asserts IsSVGDocument, and can't return null.
3555 * Defined inline in SVGDocument.h
3557 inline SVGDocument* AsSVGDocument();
3558 inline const SVGDocument* AsSVGDocument() const;
3561 * Asserts IsImageDocument, and can't return null.
3562 * Defined inline in ImageDocument.h
3564 inline ImageDocument* AsImageDocument();
3565 inline const ImageDocument* AsImageDocument() const;
3567 gfxUserFontSet* GetUserFontSet();
3568 void FlushUserFontSet();
3569 void MarkUserFontSetDirty();
3570 FontFaceSet* GetFonts() { return mFontFaceSet; }
3572 // FontFaceSource
3573 FontFaceSet* GetFonts(ErrorResult&) { return Fonts(); }
3574 FontFaceSet* Fonts();
3576 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3578 bool IsSynthesized();
3580 // Records whether we will track use counters for this document, and if so,
3581 // which top-level document that page counters will be accumulated to.
3583 // Informs the parent process that page use counters will be sent once the
3584 // document goes away.
3585 void InitUseCounters();
3587 // Reports document use counters via telemetry. This method only has an
3588 // effect once per document, and so is called during document destruction.
3589 void ReportDocumentUseCounters();
3591 // Reports largest contentful paint via telemetry. We want the most up to
3592 // date value for LCP and so this is called during document destruction.
3593 void ReportLCP();
3595 // Report how lazyload performs for this document.
3596 void ReportDocumentLazyLoadCounters();
3598 // Sends page use counters to the parent process to accumulate against the
3599 // top-level document. Must be called while we still have access to our
3600 // WindowContext. This method has an effect each time it is called, and we
3601 // call it just before the document loses its window.
3602 void SendPageUseCounters();
3604 void SetUseCounter(UseCounter aUseCounter) {
3605 mUseCounters[aUseCounter] = true;
3608 const StyleUseCounters* GetStyleUseCounters() {
3609 return mStyleUseCounters.get();
3612 // Propagate our use counters explicitly into the specified referencing
3613 // document.
3615 // This is used for SVG image documents, which cannot be enumerated in the
3616 // referencing document's ReportUseCounters() like external resource documents
3617 // can.
3618 void PropagateImageUseCounters(Document* aReferencingDocument);
3620 // Called to track whether this document has had any interaction.
3621 // This is used to track whether we should permit "beforeunload".
3622 void SetUserHasInteracted();
3623 bool UserHasInteracted() { return mUserHasInteracted; }
3624 void ResetUserInteractionTimer();
3626 // Whether we're cloning the contents of an SVG use element.
3627 bool CloningForSVGUse() const { return mCloningForSVGUse; }
3629 // This should be called when this document receives events which are likely
3630 // to be user interaction with the document, rather than the byproduct of
3631 // interaction with the browser (i.e. a keypress to scroll the view port,
3632 // keyboard shortcuts, etc). This is used to decide whether we should
3633 // permit autoplay audible media. This also gesture activates all other
3634 // content documents in this tab.
3635 void NotifyUserGestureActivation(
3636 UserActivation::Modifiers aModifiers = UserActivation::Modifiers::None());
3638 // This function is used for mochitest only.
3639 void ClearUserGestureActivation();
3641 // Return true if NotifyUserGestureActivation() has been called on any
3642 // document in the document tree.
3643 bool HasBeenUserGestureActivated();
3645 // Reture timestamp of last user gesture in milliseconds relative to
3646 // navigation start timestamp.
3647 DOMHighResTimeStamp LastUserGestureTimeStamp();
3649 // Return true if there is transient user gesture activation and it hasn't yet
3650 // timed out or hasn't been consumed.
3651 bool HasValidTransientUserGestureActivation() const;
3653 // Return true if HasValidTransientUserGestureActivation() would return true,
3654 // and consume the activation.
3655 bool ConsumeTransientUserGestureActivation();
3657 bool GetTransientUserGestureActivationModifiers(
3658 UserActivation::Modifiers* aModifiers);
3660 BrowsingContext* GetBrowsingContext() const;
3662 // This document is a WebExtension page, it might be a background page, a
3663 // popup, a visible tab, a visible iframe ...e.t.c.
3664 bool IsExtensionPage() const;
3666 bool HasScriptsBlockedBySandbox() const;
3668 void ReportHasScrollLinkedEffect(const TimeStamp& aTimeStamp);
3669 bool HasScrollLinkedEffect() const;
3671 #ifdef DEBUG
3672 void AssertDocGroupMatchesKey() const;
3673 #endif
3675 DocGroup* GetDocGroup() const {
3676 #ifdef DEBUG
3677 AssertDocGroupMatchesKey();
3678 #endif
3679 return mDocGroup;
3682 DocGroup* GetDocGroupOrCreate();
3685 * If we're a sub-document, the parent document's layout can affect our style
3686 * and layout (due to the viewport size, viewport units, media queries...).
3688 * This function returns true if our parent document and our child document
3689 * can observe each other. If they cannot, then we don't need to synchronously
3690 * update the parent document layout every time the child document may need
3691 * up-to-date layout information.
3693 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3694 return GetInProcessParentDocument() &&
3695 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3698 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3699 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3700 "Intersection observer already in the list");
3701 mIntersectionObservers.Insert(aObserver);
3704 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3705 mIntersectionObservers.Remove(aObserver);
3708 bool HasIntersectionObservers() const {
3709 return !mIntersectionObservers.IsEmpty();
3712 void UpdateIntersectionObservations(TimeStamp aNowTime);
3713 void ScheduleIntersectionObserverNotification();
3714 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3716 DOMIntersectionObserver* GetLazyLoadObserver() { return mLazyLoadObserver; }
3717 DOMIntersectionObserver& EnsureLazyLoadObserver();
3719 bool HasElementsWithLastRememberedSize() const {
3720 return !mElementsObservedForLastRememberedSize.IsEmpty();
3722 void ObserveForLastRememberedSize(Element&);
3723 void UnobserveForLastRememberedSize(Element&);
3724 void UpdateLastRememberedSizes();
3726 // Dispatch a runnable related to the document.
3727 nsresult Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) const;
3729 // The URLs passed to this function should match what
3730 // JS::DescribeScriptedCaller() returns, since this API is used to
3731 // determine whether some code is being called from a tracking script.
3732 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3733 // The JSContext passed to this method represents the context that we want to
3734 // determine if it belongs to a tracker.
3735 bool IsScriptTracking(JSContext* aCx) const;
3737 // ResizeObserver usage.
3738 void AddResizeObserver(ResizeObserver&);
3739 void RemoveResizeObserver(ResizeObserver&);
3740 void ScheduleResizeObserversNotification() const;
3741 bool HasResizeObservers() const { return !mResizeObservers.IsEmpty(); }
3743 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3744 * All observations in each ResizeObserver with element's depth more than
3745 * aDepth will be gathered.
3747 void GatherAllActiveResizeObservations(uint32_t aDepth);
3749 * Calls BroadcastActiveObservations() for all ResizeObservers.
3750 * It also returns the shallowest depth of observed target elements with
3751 * active observations from all ResizeObservers or
3752 * numeric_limits<uint32_t>::max() if there aren't any active observations
3753 * at all.
3755 MOZ_CAN_RUN_SCRIPT uint32_t BroadcastAllActiveResizeObservations();
3757 * Returns whether there is any ResizeObserver that has active
3758 * observations.
3760 bool HasAnyActiveResizeObservations() const;
3762 * Returns whether there is any ResizeObserver that has skipped observations.
3764 bool HasAnySkippedResizeObservations() const;
3766 * Determine proximity to viewport for content-visibility: auto elements and
3767 * notify resize observers.
3769 MOZ_CAN_RUN_SCRIPT void
3770 DetermineProximityToViewportAndNotifyResizeObservers();
3772 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3773 PermissionDelegateHandler* GetPermissionDelegateHandler();
3775 // Notify the document that a fetch or a XHR request has completed
3776 // succesfully in this document. This is used by the password manager to infer
3777 // whether a form is submitted.
3778 void NotifyFetchOrXHRSuccess();
3780 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3781 void SetNotifyFetchSuccess(bool aShouldNotify);
3783 // When this is set, removing a form or a password field from DOM
3784 // sends a Chrome-only event. This is now only used by the password manager
3785 // and formautofill.
3786 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify);
3788 // This function is used by HTMLFormElement and HTMLInputElement to determin
3789 // whether to send an event when it is removed from DOM.
3790 bool ShouldNotifyFormOrPasswordRemoved() const {
3791 return mShouldNotifyFormOrPasswordRemoved;
3794 HTMLEditor* GetHTMLEditor() const;
3797 * Localization
3799 * For more information on DocumentL10n see
3800 * intl/l10n/docs/fluent/tutorial.rst
3803 public:
3805 * This is a public method exposed on Document WebIDL
3806 * to chrome only documents.
3808 DocumentL10n* GetL10n() const { return mDocumentL10n.get(); }
3811 * Whether there's any async l10n mutation work pending.
3813 * When this turns false, we fire the L10nMutationsFinished event.
3815 bool HasPendingL10nMutations() const;
3818 * This method should be called when the container
3819 * of l10n resources parsing is completed.
3821 * It triggers initial async fetch of the resources
3822 * as early as possible.
3824 * In HTML case this is </head>.
3825 * In XUL case this is </linkset>.
3827 void OnL10nResourceContainerParsed();
3830 * This method should be called when a link element
3831 * with rel="localization" is being added to the
3832 * l10n resource container element.
3834 void LocalizationLinkAdded(Element* aLinkElement);
3837 * This method should be called when a link element
3838 * with rel="localization" is being removed.
3840 void LocalizationLinkRemoved(Element* aLinkElement);
3843 * This method should be called as soon as the
3844 * parsing of the document is completed.
3846 * In HTML/XHTML this happens when we finish parsing
3847 * the document element.
3848 * In XUL it happens at `DoneWalking`, during
3849 * `MozBeforeInitialXULLayout`.
3851 void OnParsingCompleted();
3854 * This method is called when the initial translation
3855 * of the document is completed.
3857 * It unblocks the load event if translation was blocking it.
3859 * If the `aL10nCached` is set to `true`, and the document has
3860 * a prototype, it will set the `isL10nCached` flag on it.
3862 void InitialTranslationCompleted(bool aL10nCached);
3865 * Returns whether the document allows localization.
3867 bool AllowsL10n() const;
3869 void SetAllowDeclarativeShadowRoots(bool aAllowDeclarativeShadowRoots);
3870 bool AllowsDeclarativeShadowRoots() const;
3872 void SuspendDOMNotifications() {
3873 MOZ_ASSERT(IsHTMLDocument(),
3874 "Currently suspending DOM notifications is supported only on "
3875 "HTML documents.");
3876 mSuspendDOMNotifications = true;
3879 void ResumeDOMNotifications() { mSuspendDOMNotifications = false; }
3881 bool DOMNotificationsSuspended() const { return mSuspendDOMNotifications; }
3883 protected:
3884 RefPtr<DocumentL10n> mDocumentL10n;
3887 * Return true when you want a document without explicitly specified viewport
3888 * dimensions/scale to be treated as if "width=device-width" had in fact been
3889 * specified.
3891 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3893 private:
3894 bool IsErrorPage() const;
3896 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3897 // mUseCounters.
3898 void SetCssUseCounterBits();
3900 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3901 const nsAString& aHeightString,
3902 bool aIsAutoScale);
3904 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3905 // represents the scale property and returns the scale value if it's valid.
3906 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
3908 // Parse scale values in |aViewportMetaData| and set the values in
3909 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3910 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
3912 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3913 // stored in parent iframe or container's browsingContext (cross process)
3914 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
3916 public:
3917 const OriginTrials& Trials() const { return mTrials; }
3919 private:
3920 void DoCacheAllKnownLangPrefs();
3921 void RecomputeLanguageFromCharset();
3922 bool GetSHEntryHasUserInteraction();
3924 void AppendAutoFocusCandidateToTopDocument(Element* aAutoFocusCandidate);
3926 public:
3927 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
3929 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
3931 void SetSHEntryHasUserInteraction(bool aHasInteraction);
3933 nsAtom* GetContentLanguageAsAtomForStyle() const;
3934 nsAtom* GetLanguageForStyle() const;
3937 * Fetch the user's font preferences for the given aLanguage's
3938 * language group.
3940 const LangGroupFontPrefs* GetFontPrefsForLang(
3941 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
3943 void ForceCacheLang(nsAtom* aLanguage) {
3944 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
3945 return;
3947 GetFontPrefsForLang(aLanguage);
3950 void CacheAllKnownLangPrefs() {
3951 if (!mMayNeedFontPrefsUpdate) {
3952 return;
3954 DoCacheAllKnownLangPrefs();
3957 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
3959 uint32_t GetServoRestyleRootDirtyBits() const {
3960 MOZ_ASSERT(mServoRestyleRoot);
3961 MOZ_ASSERT(mServoRestyleRootDirtyBits);
3962 return mServoRestyleRootDirtyBits;
3965 void ClearServoRestyleRoot() {
3966 mServoRestyleRoot = nullptr;
3967 mServoRestyleRootDirtyBits = 0;
3970 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3971 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3973 bool ShouldThrowOnDynamicMarkupInsertion() {
3974 return mThrowOnDynamicMarkupInsertionCounter;
3977 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3978 ++mThrowOnDynamicMarkupInsertionCounter;
3981 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3982 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3983 --mThrowOnDynamicMarkupInsertionCounter;
3986 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
3988 void IncrementIgnoreOpensDuringUnloadCounter() {
3989 ++mIgnoreOpensDuringUnloadCounter;
3992 void DecrementIgnoreOpensDuringUnloadCounter() {
3993 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3994 --mIgnoreOpensDuringUnloadCounter;
3997 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
4000 * Find the (non-anonymous) content in this document for aFrame. It will
4001 * be aFrame's content node if that content is in this document and not
4002 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4003 * element containing the subdocument containing aFrame, and/or find the
4004 * nearest non-anonymous ancestor in this document.
4005 * Returns null if there is no such element.
4007 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
4009 void ReportShadowDOMUsage();
4011 // Sets flags for media telemetry.
4012 void SetDocTreeHadMedia();
4014 dom::XPathEvaluator* XPathEvaluator();
4016 void MaybeInitializeFinalizeFrameLoaders();
4018 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
4019 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
4022 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
4024 nsIPermissionDelegateHandler* PermDelegateHandler();
4026 // Returns whether this is a top-level about:blank page without an opener (and
4027 // thus likely not accessible by content). Likely because it shouldn't be used
4028 // for security checks for example, see bug 1860098.
4029 bool IsLikelyContentInaccessibleTopLevelAboutBlank() const;
4031 // CSS prefers-color-scheme media feature for this document.
4032 enum class IgnoreRFP { No, Yes };
4033 ColorScheme PreferredColorScheme(IgnoreRFP = IgnoreRFP::No) const;
4034 // Returns the initial color-scheme used for this document based on the
4035 // color-scheme meta tag.
4036 ColorScheme DefaultColorScheme() const;
4038 static bool HasRecentlyStartedForegroundLoads();
4040 static bool AutomaticStorageAccessPermissionCanBeGranted(
4041 nsIPrincipal* aPrincipal);
4043 already_AddRefed<Promise> AddCertException(bool aIsTemporary,
4044 ErrorResult& aError);
4046 void ReloadWithHttpsOnlyException();
4048 // Subframes need to be static cloned after the main document has been
4049 // embedded within a script global. A `PendingFrameStaticClone` is a static
4050 // clone which has not yet been performed.
4052 // The getter returns a direct reference to an internal array which is
4053 // manipulated from within printing code.
4054 struct PendingFrameStaticClone {
4055 PendingFrameStaticClone() = default;
4056 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
4057 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
4058 ~PendingFrameStaticClone();
4060 RefPtr<nsFrameLoaderOwner> mElement;
4061 RefPtr<nsFrameLoader> mStaticCloneOf;
4063 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
4064 nsFrameLoader* aStaticCloneOf);
4066 bool ShouldAvoidNativeTheme() const;
4068 static bool IsValidDomain(nsIURI* aOrigHost, nsIURI* aNewURI);
4070 // Inform a parent document that a BrowserBridgeChild has been created for
4071 // an OOP sub-document.
4072 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4073 void OOPChildLoadStarted(BrowserBridgeChild* aChild);
4075 // Inform a parent document that the BrowserBridgeChild for one of its
4076 // OOP sub-documents is done calling its onload handler.
4077 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4078 void OOPChildLoadDone(BrowserBridgeChild* aChild);
4080 void ClearOOPChildrenLoading();
4082 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading.IsEmpty(); }
4084 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache = true; }
4086 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache; }
4089 * Get the `HighlightRegistry` which contains all highlights associated
4090 * with this document.
4092 class HighlightRegistry& HighlightRegistry();
4094 bool ShouldResistFingerprinting(RFPTarget aTarget) const;
4095 bool IsInPrivateBrowsing() const;
4097 const Maybe<RFPTarget>& GetOverriddenFingerprintingSettings() const {
4098 return mOverriddenFingerprintingSettings;
4101 // Recompute the current resist fingerprinting state. Returns true when
4102 // the state was changed.
4103 bool RecomputeResistFingerprinting();
4105 void RecordCanvasUsage(CanvasUsage& aUsage);
4106 void RecordFontFingerprinting();
4108 bool MayHaveDOMActivateListeners() const;
4110 void DropStyleSet();
4112 protected:
4113 // Returns the WindowContext for the document that we will contribute
4114 // page use counters to.
4115 WindowContext* GetWindowContextForPageUseCounters() const;
4117 void DoUpdateSVGUseElementShadowTrees();
4119 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
4120 nsIPrincipal* aPrincipal);
4122 void EnsureOnloadBlocker();
4124 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
4126 // Returns true if the scheme for the url for this document is "about".
4127 bool IsAboutPage() const;
4129 bool ContainsEMEContent();
4130 bool ContainsMSEContent();
4133 * Returns the title element of the document as defined by the HTML
4134 * specification, or null if there isn't one. For documents whose root
4135 * element is an <svg:svg>, this is the first <svg:title> element that's a
4136 * child of the root. For other documents, it's the first HTML title element
4137 * in the document.
4139 Element* GetTitleElement();
4141 void RecordNavigationTiming(ReadyState aReadyState);
4143 // Recomputes the visibility state but doesn't set the new value.
4144 dom::VisibilityState ComputeVisibilityState() const;
4146 // Since we wouldn't automatically play media from non-visited page, we need
4147 // to notify window when the page was first visited.
4148 void MaybeActiveMediaComponents();
4150 // Apply the fullscreen state to the document, and trigger related
4151 // events. It returns false if the fullscreen element ready check
4152 // fails and nothing gets changed.
4153 bool ApplyFullscreen(UniquePtr<FullscreenRequest>);
4155 void RemoveDocStyleSheetsFromStyleSets();
4156 void ResetStylesheetsToURI(nsIURI* aURI);
4157 void FillStyleSet();
4158 void FillStyleSetUserAndUASheets();
4159 void FillStyleSetDocumentSheets();
4160 void CompatibilityModeChanged();
4161 bool NeedsQuirksSheet() const {
4162 // SVG documents never load quirk.css.
4163 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4164 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
4166 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
4167 void RemoveContentEditableStyleSheets();
4168 void AddStyleSheetToStyleSets(StyleSheet&);
4169 void RemoveStyleSheetFromStyleSets(StyleSheet&);
4170 void NotifyStyleSheetApplicableStateChanged();
4171 // Just like EnableStyleSheetsForSet, but doesn't check whether
4172 // aSheetSet is null and allows the caller to control whether to set
4173 // aSheetSet as the preferred set in the CSSLoader.
4174 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
4175 bool aUpdateCSSLoader);
4177 already_AddRefed<nsIURI> GetDomainURI();
4178 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4179 const nsACString& aHostString);
4180 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4181 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4183 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4184 mozilla::ErrorResult& aRv);
4185 // A version of WriteCommon used by WebIDL bindings
4186 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4187 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4189 void* GenerateParserKey(void);
4191 private:
4192 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4193 // parameter.
4194 enum class ExecCommandParam : uint8_t {
4195 // Always ignore it.
4196 Ignore,
4197 // Treat the given parameter as-is. If the command requires it, use it.
4198 // Otherwise, ignore it.
4199 String,
4200 // Always treat it as boolean parameter.
4201 Boolean,
4202 // Always treat it as boolean, but inverted.
4203 InvertedBoolean,
4206 using GetEditorCommandFunc = mozilla::EditorCommand*();
4208 struct InternalCommandData {
4209 const char* mXULCommandName;
4210 mozilla::Command mCommand; // uint8_t
4211 // How ConvertToInternalCommand() to treats aValue.
4212 // Its callers don't need to check this.
4213 ExecCommandParam mExecCommandParam; // uint8_t
4214 GetEditorCommandFunc* mGetEditorCommandFunc;
4215 enum class CommandOnTextEditor : uint8_t {
4216 Disabled,
4217 Enabled,
4218 FallThrough, // Not disabled, but handled by HTMLEditor if there is one
4220 CommandOnTextEditor mCommandOnTextEditor;
4222 InternalCommandData()
4223 : mXULCommandName(nullptr),
4224 mCommand(mozilla::Command::DoNothing),
4225 mExecCommandParam(ExecCommandParam::Ignore),
4226 mGetEditorCommandFunc(nullptr),
4227 mCommandOnTextEditor(CommandOnTextEditor::Disabled) {}
4228 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4229 ExecCommandParam aExecCommandParam,
4230 GetEditorCommandFunc aGetEditorCommandFunc,
4231 CommandOnTextEditor aCommandOnTextEditor)
4232 : mXULCommandName(aXULCommandName),
4233 mCommand(aCommand),
4234 mExecCommandParam(aExecCommandParam),
4235 mGetEditorCommandFunc(aGetEditorCommandFunc),
4236 mCommandOnTextEditor(aCommandOnTextEditor) {}
4238 bool IsAvailableOnlyWhenEditable() const {
4239 return mCommand != mozilla::Command::Cut &&
4240 mCommand != mozilla::Command::Copy &&
4241 mCommand != mozilla::Command::Paste &&
4242 mCommand != mozilla::Command::SetDocumentReadOnly &&
4243 mCommand != mozilla::Command::SelectAll;
4245 bool IsCutOrCopyCommand() const {
4246 return mCommand == mozilla::Command::Cut ||
4247 mCommand == mozilla::Command::Copy;
4249 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4253 * AutoEditorCommandTarget considers which editor or global command manager
4254 * handles given command.
4256 class MOZ_RAII AutoEditorCommandTarget {
4257 public:
4258 MOZ_CAN_RUN_SCRIPT AutoEditorCommandTarget(
4259 Document& aDocument, const InternalCommandData& aCommandData);
4260 AutoEditorCommandTarget() = delete;
4261 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget& aOther) =
4262 delete;
4264 bool DoNothing() const { return mDoNothing; }
4265 MOZ_CAN_RUN_SCRIPT bool IsEditable(Document* aDocument) const;
4266 bool IsEditor() const {
4267 MOZ_ASSERT_IF(mEditorCommand, mActiveEditor || mHTMLEditor);
4268 return !!mEditorCommand;
4271 MOZ_CAN_RUN_SCRIPT bool IsCommandEnabled() const;
4272 MOZ_CAN_RUN_SCRIPT nsresult DoCommand(nsIPrincipal* aPrincipal) const;
4273 template <typename ParamType>
4274 MOZ_CAN_RUN_SCRIPT nsresult DoCommandParam(const ParamType& aParam,
4275 nsIPrincipal* aPrincipal) const;
4276 MOZ_CAN_RUN_SCRIPT nsresult
4277 GetCommandStateParams(nsCommandParams& aParams) const;
4279 private:
4280 // The returned editor's life is guaranteed while this instance is alive.
4281 EditorBase* GetTargetEditor() const;
4283 RefPtr<EditorBase> mActiveEditor;
4284 RefPtr<HTMLEditor> mHTMLEditor;
4285 RefPtr<EditorCommand> mEditorCommand;
4286 const InternalCommandData& mCommandData;
4287 bool mDoNothing = false;
4291 * Helper method to initialize sInternalCommandDataHashtable.
4293 static void EnsureInitializeInternalCommandDataHashtable();
4296 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4297 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4298 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4299 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4300 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4301 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4302 * returns a copy of instance created with default constructor. I.e., its
4303 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4304 * is unsupported in such case.
4306 * @param aHTMLCommandName Command name in HTML, e.g., used by
4307 * execCommand().
4308 * @param aValue The value which is set to the 3rd parameter
4309 * of execCommand().
4310 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4311 * Will be set to adjusted value for executing
4312 * the internal command.
4313 * @return Returns a copy of instance created with the
4314 * default constructor if there is no
4315 * corresponding internal command for
4316 * aHTMLCommandName or aValue is invalid for
4317 * found internal command when aAdjustedValue
4318 * is not nullptr. Otherwise, returns a copy of
4319 * instance registered in
4320 * sInternalCommandDataHashtable.
4322 static InternalCommandData ConvertToInternalCommand(
4323 const nsAString& aHTMLCommandName, const nsAString& aValue = u""_ns,
4324 nsAString* aAdjustedValue = nullptr);
4327 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4328 * Since it's a bit field, not a bool member, therefore, we cannot use
4329 * AutoRestorer for it.
4331 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4332 public:
4333 AutoRunningExecCommandMarker() = delete;
4334 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4335 delete;
4336 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4337 MOZ_CAN_RUN_SCRIPT AutoRunningExecCommandMarker(Document& aDocument,
4338 nsIPrincipal* aPrincipal);
4339 ~AutoRunningExecCommandMarker() {
4340 if (mTreatAsUserInput) {
4341 mDocument.mIsRunningExecCommandByChromeOrAddon =
4342 mHasBeenRunningByChromeOrAddon;
4343 } else {
4344 mDocument.mIsRunningExecCommandByContent = mHasBeenRunningByContent;
4348 [[nodiscard]] bool IsSafeToRun() const {
4349 // We don't allow nested calls of execCommand even if the caller is chrome
4350 // script.
4351 if (mTreatAsUserInput) {
4352 return !mHasBeenRunningByChromeOrAddon && !mHasBeenRunningByContent;
4354 // If current call is by content, we should ignore whether nested with a
4355 // call by addon (or chrome script) because the caller wants to emulate
4356 // user input for making it undoable. So, we should treat the first
4357 // call as user input.
4358 return !mHasBeenRunningByContent;
4361 private:
4362 Document& mDocument;
4363 bool mTreatAsUserInput;
4364 bool mHasBeenRunningByContent;
4365 bool mHasBeenRunningByChromeOrAddon;
4368 // Mapping table from HTML command name to internal command.
4369 using InternalCommandDataHashtable =
4370 nsTHashMap<nsStringCaseInsensitiveHashKey, InternalCommandData>;
4371 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4373 mutable std::bitset<static_cast<size_t>(
4374 DeprecatedOperations::eDeprecatedOperationCount)>
4375 mDeprecationWarnedAbout;
4376 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4378 // Lazy-initialization to have mDocGroup initialized in prior to the
4379 UniquePtr<ServoStyleSet> mStyleSet;
4381 protected:
4382 // Never ever call this. Only call GetWindow!
4383 nsPIDOMWindowOuter* GetWindowInternal() const;
4385 // Never ever call this. Only call GetScriptHandlingObject!
4386 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4388 // Never ever call this. Only call AllowXULXBL!
4389 bool InternalAllowXULXBL();
4392 * These methods should be called before and after dispatching
4393 * a mutation event.
4394 * To make this easy and painless, use the mozAutoSubtreeModified helper
4395 * class.
4397 void WillDispatchMutationEvent(nsINode* aTarget);
4398 void MutationEventDispatched(nsINode* aTarget);
4399 friend class mozAutoSubtreeModified;
4401 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4403 nsCString GetContentTypeInternal() const { return mContentType; }
4405 // Update our frame request callback scheduling state, if needed. This will
4406 // schedule or unschedule them, if necessary, and update
4407 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4408 // mPresShell is becoming null; in that case it will be used to get hold of
4409 // the relevant refresh driver.
4410 void UpdateFrameRequestCallbackSchedulingState(
4411 PresShell* aOldPresShell = nullptr);
4413 // Helper for GetScrollingElement/IsScrollingElement.
4414 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4416 void MaybeAllowStorageForOpenerAfterUserInteraction();
4418 void MaybeStoreUserInteractionAsPermission();
4420 // Helpers for GetElementsByName.
4421 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4422 nsAtom* aAtom, void* aData);
4423 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4425 void MaybeResolveReadyForIdle();
4427 using AutomaticStorageAccessPermissionGrantPromise =
4428 MozPromise<bool, bool, true>;
4429 [[nodiscard]] RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4430 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation);
4432 static void AddToplevelLoadingDocument(Document* aDoc);
4433 static void RemoveToplevelLoadingDocument(Document* aDoc);
4434 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4435 friend class cycleCollection;
4437 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4438 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4440 nsString mLastModified;
4442 nsCOMPtr<nsIURI> mDocumentURI;
4443 nsCOMPtr<nsIURI> mOriginalURI;
4444 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4445 nsCOMPtr<nsIURI> mDocumentBaseURI;
4446 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4448 // The base domain of the document for third-party checks.
4449 nsCString mBaseDomain;
4451 // A lazily-constructed URL data for style system to resolve URL values.
4452 RefPtr<URLExtraData> mCachedURLData;
4453 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfoForInternalCSSAndSVGResources;
4455 nsWeakPtr mDocumentLoadGroup;
4457 WeakPtr<nsDocShell> mDocumentContainer;
4459 NotNull<const Encoding*> mCharacterSet;
4460 int32_t mCharacterSetSource;
4462 OriginTrials mTrials;
4464 // This is just a weak pointer; the parent document owns its children.
4465 Document* mParentDocument;
4467 // A reference to the element last returned from GetRootElement().
4468 Element* mCachedRootElement;
4470 // This is maintained by AutoSetRestoreSVGContextPaint.
4471 const SVGContextPaint* mCurrentContextPaint = nullptr;
4473 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4474 // which in turn holds a strong reference to this mNodeInfoManager.
4475 nsNodeInfoManager* mNodeInfoManager;
4476 RefPtr<css::Loader> mCSSLoader;
4477 RefPtr<css::ImageLoader> mStyleImageLoader;
4479 // The object that contains link color declarations (from the <body> mapped
4480 // attributes), mapped attribute caches, and inline style attribute caches.
4481 RefPtr<AttributeStyles> mAttributeStyles;
4483 // Tracking for images in the document.
4484 RefPtr<dom::ImageTracker> mImageTracker;
4486 // A hashtable of ShadowRoots belonging to the composed doc.
4488 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4489 ShadowRootSet mComposedShadowRoots;
4491 using SVGUseElementSet = nsTHashSet<SVGUseElement*>;
4493 // The set of <svg:use> elements that need a shadow tree reclone because the
4494 // tree they map to has changed.
4495 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4497 // The set of all object, embed, video/audio elements or
4498 // nsIObjectLoadingContent or DocumentActivity for which this is
4499 // the owner document. (They might not be in the document.)
4501 // These are non-owning pointers, the elements are responsible for removing
4502 // themselves when they go away.
4503 UniquePtr<nsTHashSet<nsISupports*>> mActivityObservers;
4505 // A hashtable of styled links keyed by address pointer.
4506 nsTHashSet<Link*> mStyledLinks;
4507 #ifdef DEBUG
4508 // Indicates whether mStyledLinks was cleared or not. This is used to track
4509 // state so we can provide useful assertions to consumers of ForgetLink and
4510 // AddStyleRelevantLink.
4511 bool mStyledLinksCleared;
4512 #endif
4514 // The array of all links that need their status resolved. Links must add
4515 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4516 // document.
4517 static const size_t kSegmentSize = 128;
4519 using LinksToUpdateList =
4520 SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>;
4522 LinksToUpdateList mLinksToUpdate;
4524 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4525 RefPtr<SMILAnimationController> mAnimationController;
4527 // Table of element properties for this document.
4528 nsPropertyTable mPropertyTable;
4530 // Our cached .children collection
4531 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4533 // Various DOM lists
4534 RefPtr<nsContentList> mImages;
4535 RefPtr<nsContentList> mEmbeds;
4536 RefPtr<nsContentList> mLinks;
4537 RefPtr<nsContentList> mForms;
4538 RefPtr<nsContentList> mScripts;
4539 nsCOMPtr<nsIHTMLCollection> mApplets;
4540 RefPtr<nsContentList> mAnchors;
4542 // container for per-context fonts (downloadable, SVG, etc.)
4543 RefPtr<FontFaceSet> mFontFaceSet;
4545 // Last time this document or a one of its sub-documents was focused. If
4546 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4547 TimeStamp mLastFocusTime;
4549 // Last time we found any scroll linked effect in this document.
4550 TimeStamp mLastScrollLinkedEffectDetectionTime;
4552 DocumentState mState{DocumentState::LTR_LOCALE};
4554 RefPtr<Promise> mReadyForIdle;
4556 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4558 // Permission Delegate Handler, lazily-initialized in
4559 // GetPermissionDelegateHandler
4560 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4562 bool mCachedStateObjectValid : 1;
4563 bool mBlockAllMixedContent : 1;
4564 bool mBlockAllMixedContentPreloads : 1;
4565 bool mUpgradeInsecureRequests : 1;
4566 bool mUpgradeInsecurePreloads : 1;
4567 bool mDevToolsWatchingDOMMutations : 1;
4569 // True if BIDI is enabled.
4570 bool mBidiEnabled : 1;
4571 // True if we may need to recompute the language prefs for this document.
4572 bool mMayNeedFontPrefsUpdate : 1;
4573 // True if a MathML element has ever been owned by this document.
4574 bool mMathMLEnabled : 1;
4576 // True if this document is the initial document for a window. This should
4577 // basically be true only for documents that exist in newly-opened windows or
4578 // documents created to satisfy a GetDocument() on a window when there's no
4579 // document in it.
4580 bool mIsInitialDocumentInWindow : 1;
4582 // True if this document has ever been the initial document for a window. This
4583 // is useful to determine if a document that was the initial document at one
4584 // point, and became non-initial later.
4585 bool mIsEverInitialDocumentInWindow : 1;
4587 bool mIgnoreDocGroupMismatches : 1;
4589 // True if we're loaded as data and therefor has any dangerous stuff, such
4590 // as scripts and plugins, disabled.
4591 bool mLoadedAsData : 1;
4593 // True if the document is considered for memory reporting as a
4594 // data document
4595 bool mAddedToMemoryReportingAsDataDocument : 1;
4597 // If true, whoever is creating the document has gotten it to the
4598 // point where it's safe to start layout on it.
4599 bool mMayStartLayout : 1;
4601 // True iff we've ever fired a DOMTitleChanged event for this document
4602 bool mHaveFiredTitleChange : 1;
4604 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4605 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4606 // before the initial load completes and when we're in bfcache or unloaded,
4607 // true otherwise.
4608 bool mIsShowing : 1;
4610 // State for IsVisible(). mVisible starts off true. It becomes false when
4611 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4612 // it's false only when we're in bfcache or unloaded.
4613 bool mVisible : 1;
4615 // True if our content viewer has been removed from the docshell
4616 // (it may still be displayed, but in zombie state). Form control data
4617 // has been saved.
4618 bool mRemovedFromDocShell : 1;
4620 // True iff DNS prefetch is allowed for this document. Note that if the
4621 // document has no window, DNS prefetch won't be performed no matter what.
4622 bool mAllowDNSPrefetch : 1;
4624 // True when this document is a static clone of a normal document
4625 bool mIsStaticDocument : 1;
4627 // True while this document is being cloned to a static document.
4628 bool mCreatingStaticClone : 1;
4630 // True if this static document has any <canvas> element with a
4631 // mozPrintCallback property at the time of the clone.
4632 bool mHasPrintCallbacks : 1;
4634 // True iff the document is being unlinked or deleted.
4635 bool mInUnlinkOrDeletion : 1;
4637 // True if document has ever had script handling object.
4638 bool mHasHadScriptHandlingObject : 1;
4640 // True if we're an SVG document being used as an image.
4641 bool mIsBeingUsedAsImage : 1;
4643 // True if our current document URI's scheme enables privileged CSS rules.
4644 bool mChromeRulesEnabled : 1;
4646 // True if we're loaded in a chrome docshell.
4647 bool mInChromeDocShell : 1;
4649 // True is this document is synthetic : stand alone image, video, audio
4650 // file, etc.
4651 bool mIsSyntheticDocument : 1;
4653 // True is there is a pending runnable which will call
4654 // FlushPendingLinkUpdates().
4655 bool mHasLinksToUpdateRunnable : 1;
4657 // True if we're flushing pending link updates.
4658 bool mFlushingPendingLinkUpdates : 1;
4660 // True if a DOMMutationObserver is perhaps attached to a node in the
4661 // document.
4662 bool mMayHaveDOMMutationObservers : 1;
4664 // True if an nsIAnimationObserver is perhaps attached to a node in the
4665 // document.
4666 bool mMayHaveAnimationObservers : 1;
4668 // True if the document has a CSP delivered throuh a header
4669 bool mHasCSPDeliveredThroughHeader : 1;
4671 // True if DisallowBFCaching has been called on this document.
4672 bool mBFCacheDisallowed : 1;
4674 bool mHasHadDefaultView : 1;
4676 // Whether style sheet change events will be dispatched for this document
4677 bool mStyleSheetChangeEventsEnabled : 1;
4679 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4680 // will be dispatched for this document.
4681 bool mDevToolsAnonymousAndShadowEventsEnabled : 1;
4683 // Whether the document was created by a srcdoc iframe.
4684 bool mIsSrcdocDocument : 1;
4686 // Whether this document has a display document and thus is considered to
4687 // be a resource document. Normally this is the same as !!mDisplayDocument,
4688 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4689 // valid in the document's destructor.
4690 bool mHasDisplayDocument : 1;
4692 // Is the current mFontFaceSet valid?
4693 bool mFontFaceSetDirty : 1;
4695 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4696 // (e.g. we're not being parsed at all).
4697 bool mDidFireDOMContentLoaded : 1;
4699 // True if we have frame request callbacks scheduled with the refresh driver.
4700 // This should generally be updated only via
4701 // UpdateFrameRequestCallbackSchedulingState.
4702 bool mFrameRequestCallbacksScheduled : 1;
4704 bool mIsTopLevelContentDocument : 1;
4706 bool mIsContentDocument : 1;
4708 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4709 bool mDidCallBeginLoad : 1;
4711 // True if the encoding menu should be disabled.
4712 bool mEncodingMenuDisabled : 1;
4714 // False if we've disabled link handling for elements inside this document,
4715 // true otherwise.
4716 bool mLinksEnabled : 1;
4718 // True if this document is for an SVG-in-OpenType font.
4719 bool mIsSVGGlyphsDocument : 1;
4721 // True if the document is being destroyed.
4722 bool mInDestructor : 1;
4724 // True if the document has been detached from its content viewer.
4725 bool mIsGoingAway : 1;
4727 // Whether we have filled our style set with all the stylesheets.
4728 bool mStyleSetFilled : 1;
4730 // Whether we have a quirks mode stylesheet in the style set.
4731 bool mQuirkSheetAdded : 1;
4733 // Whether we have a contenteditable.css stylesheet in the style set.
4734 bool mContentEditableSheetAdded : 1;
4736 // Whether we have a designmode.css stylesheet in the style set.
4737 bool mDesignModeSheetAdded : 1;
4739 // True if this document has ever had an HTML or SVG <title> element
4740 // bound to it
4741 bool mMayHaveTitleElement : 1;
4743 bool mDOMLoadingSet : 1;
4744 bool mDOMInteractiveSet : 1;
4745 bool mDOMCompleteSet : 1;
4746 bool mAutoFocusFired : 1;
4748 bool mScrolledToRefAlready : 1;
4749 bool mChangeScrollPosWhenScrollingToRef : 1;
4751 bool mDelayFrameLoaderInitialization : 1;
4753 bool mSynchronousDOMContentLoaded : 1;
4755 // Set to true when the document is possibly controlled by the ServiceWorker.
4756 // Used to prevent multiple requests to ServiceWorkerManager.
4757 bool mMaybeServiceWorkerControlled : 1;
4759 // These member variables cache information about the viewport so we don't
4760 // have to recalculate it each time.
4761 bool mAllowZoom : 1;
4762 bool mValidScaleFloat : 1;
4763 bool mValidMinScale : 1;
4764 bool mValidMaxScale : 1;
4765 bool mWidthStrEmpty : 1;
4767 // Parser aborted. True if the parser of this document was forcibly
4768 // terminated instead of letting it finish at its own pace.
4769 bool mParserAborted : 1;
4771 // Whether we have reported document use counters for this document with
4772 // Telemetry yet. Normally this is only done at document destruction time,
4773 // but for image documents (SVG documents) that are not guaranteed to be
4774 // destroyed, we report use counters when the image cache no longer has any
4775 // imgRequestProxys pointing to them. We track whether we ever reported use
4776 // counters so that we only report them once for the document.
4777 bool mReportedDocumentUseCounters : 1;
4779 bool mHasReportedShadowDOMUsage : 1;
4781 // Whether an event triggered by the refresh driver was delayed because this
4782 // document has suppressed events.
4783 bool mHasDelayedRefreshEvent : 1;
4785 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4786 // to have the right semantics. See
4787 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4788 // flag that is set while the window's 'load' event is firing if this document
4789 // is the window's document.
4790 bool mLoadEventFiring : 1;
4792 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4793 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4794 // What we have instead is a flag that is set if completion of our document
4795 // via document.close() should skip firing the load event. Note that this
4796 // flag is only relevant for HTML documents, but lives here for reasons that
4797 // are documented above on SkipLoadEventAfterClose().
4798 bool mSkipLoadEventAfterClose : 1;
4800 // When false, the .cookies property is completely disabled
4801 bool mDisableCookieAccess : 1;
4803 // When false, the document.write() API is disabled.
4804 bool mDisableDocWrite : 1;
4806 // Has document.write() been called with a recursion depth higher than
4807 // allowed?
4808 bool mTooDeepWriteRecursion : 1;
4811 * Temporary flag that is set in EndUpdate() to ignore
4812 * MaybeEditingStateChanged() script runners from a nested scope.
4814 bool mPendingMaybeEditingStateChanged : 1;
4816 // mHasBeenEditable is set to true when mEditingState is firstly set to
4817 // eDesignMode or eContentEditable.
4818 bool mHasBeenEditable : 1;
4820 // Whether we've warned about the CSS zoom property.
4822 // We don't use the general deprecated operation mechanism for this because we
4823 // also record this as a `CountedUnknownProperty`.
4824 bool mHasWarnedAboutZoom : 1;
4826 // While we're handling an execCommand call by web app, set
4827 // to true.
4828 bool mIsRunningExecCommandByContent : 1;
4829 // While we're handling an execCommand call by an addon (or chrome script),
4830 // set to true.
4831 bool mIsRunningExecCommandByChromeOrAddon : 1;
4833 // True if we should change the readystate to complete after we fire
4834 // DOMContentLoaded. This happens when we abort a load and
4835 // nsDocumentViewer::EndLoad runs while we still have things blocking
4836 // DOMContentLoaded. We wait for those to complete, and then update the
4837 // readystate when they finish.
4838 bool mSetCompleteAfterDOMContentLoaded : 1;
4840 // Set the true if a completed cached stylesheet was created for the document.
4841 bool mDidHitCompleteSheetCache : 1;
4843 // Whether we have initialized mShouldReportUseCounters and
4844 // mShouldSendPageUseCounters, and sent any needed message to the parent
4845 // process to indicate that use counter data will be sent at some later point.
4846 bool mUseCountersInitialized : 1;
4848 // Whether this document should report use counters.
4849 bool mShouldReportUseCounters : 1;
4851 // Whether this document should send page use counters. Set to true after
4852 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4853 bool mShouldSendPageUseCounters : 1;
4855 // Whether the user has interacted with the document or not:
4856 bool mUserHasInteracted : 1;
4858 // We constantly update the user-interaction anti-tracking permission at any
4859 // user-interaction using a timer. This boolean value is set to true when this
4860 // timer is scheduled.
4861 bool mHasUserInteractionTimerScheduled : 1;
4863 // Whether we should resist fingerprinting.
4864 bool mShouldResistFingerprinting : 1;
4866 // Whether we are in private browsing mode.
4867 bool mIsInPrivateBrowsing : 1;
4869 // Whether we're cloning the contents of an SVG use element.
4870 bool mCloningForSVGUse : 1;
4872 bool mAllowDeclarativeShadowRoots : 1;
4874 bool mSuspendDOMNotifications : 1;
4876 // The fingerprinting protections overrides for this document. The value will
4877 // override the default enabled fingerprinting protections for this document.
4878 // This will only get populated if these is one that comes from the local
4879 // fingerprinting protection override pref or WebCompat. Otherwise, a value of
4880 // Nothing() indicates no overrides are present for this document.
4881 Maybe<RFPTarget> mOverriddenFingerprintingSettings;
4883 uint8_t mXMLDeclarationBits;
4885 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4886 // use uint8_t to avoid having to include a bunch of style system headers
4887 // everywhere.
4888 uint8_t mColorSchemeBits = 0;
4890 // Currently active onload blockers.
4891 uint32_t mOnloadBlockCount;
4893 // Tracks if we are currently processing any document.write calls (either
4894 // implicit or explicit). Note that if a write call writes out something which
4895 // would block the parser, then mWriteLevel will be incorrect until the parser
4896 // finishes processing that script.
4897 uint32_t mWriteLevel;
4899 uint32_t mContentEditableCount;
4900 EditingState mEditingState;
4902 // Compatibility mode
4903 nsCompatibility mCompatMode;
4905 // Our readyState
4906 ReadyState mReadyState;
4908 // Ancestor's loading state
4909 bool mAncestorIsLoading;
4911 // Our visibility state
4912 dom::VisibilityState mVisibilityState;
4914 enum Type {
4915 eUnknown, // should never be used
4916 eHTML,
4917 eXHTML,
4918 eGenericXML,
4919 eSVG
4922 Type mType;
4924 uint8_t mDefaultElementType;
4926 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4928 Tri mAllowXULXBL;
4930 bool mSkipDTDSecurityChecks;
4932 // The document's script global object, the object from which the
4933 // document can get its script context and scope. This is the
4934 // *inner* window object.
4935 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4937 // If mIsStaticDocument is true, mOriginalDocument points to the original
4938 // document.
4939 RefPtr<Document> mOriginalDocument;
4941 // The bidi options for this document. What this bitfield means is
4942 // defined in nsBidiUtils.h
4943 uint32_t mBidiOptions;
4945 // The sandbox flags on the document. These reflect the value of the sandbox
4946 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4947 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4948 // possible flags.
4949 uint32_t mSandboxFlags;
4951 // The embedder policy obtained from parsing the HTTP response header or from
4952 // our opener if this is the initial about:blank document.
4953 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4955 RefPtr<nsAtom> mContentLanguage;
4957 // The channel that got passed to Document::StartDocumentLoad(), if any.
4958 nsCOMPtr<nsIChannel> mChannel;
4960 // The CSP for every load lives in the Client within the LoadInfo. For all
4961 // document-initiated subresource loads we can use that cached version of the
4962 // CSP so we do not have to deserialize the CSP from the Client all the time.
4963 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4964 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4966 private:
4967 nsCString mContentType;
4969 protected:
4970 // The document's security info
4971 nsCOMPtr<nsITransportSecurityInfo> mSecurityInfo;
4973 // The channel that failed to load and resulted in an error page.
4974 // This only applies to error pages. Might be null.
4975 nsCOMPtr<nsIChannel> mFailedChannel;
4977 // if this document is part of a multipart document,
4978 // the ID can be used to distinguish it from the other parts.
4979 uint32_t mPartID;
4981 // Cycle collector generation in which we're certain that this document
4982 // won't be collected
4983 uint32_t mMarkedCCGeneration;
4985 PresShell* mPresShell;
4987 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4988 uint32_t mSubtreeModifiedDepth;
4990 // All images in process of being preloaded. This is a hashtable so
4991 // we can remove them as the real image loads start; that way we
4992 // make sure to not keep the image load going when no one cares
4993 // about it anymore.
4994 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4996 // A list of preconnects initiated by the preloader. This prevents
4997 // the same uri from being used more than once, and allows the dom
4998 // builder to not repeat the work of the preloader.
4999 nsTHashMap<nsURIHashKey, bool> mPreloadedPreconnects;
5001 // Current depth of picture elements from parser
5002 uint32_t mPreloadPictureDepth;
5004 // Set if we've found a URL for the current picture
5005 nsString mPreloadPictureFoundSource;
5007 // If we're an external resource document, this will be non-null and will
5008 // point to our "display document": the one that all resource lookups should
5009 // go to.
5010 RefPtr<Document> mDisplayDocument;
5012 uint32_t mEventsSuppressed;
5014 // Any XHR ChannelEventQueues that were suspended on this document while
5015 // events were suppressed.
5016 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
5018 // Any postMessage events that were suspended on this document while events
5019 // were suppressed.
5020 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
5022 RefPtr<EventListener> mSuppressedEventListener;
5025 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5027 uint32_t mIgnoreDestructiveWritesCounter;
5029 // Count of live static clones of this document.
5030 uint32_t mStaticCloneCount;
5032 // If the document is currently printing (or in print preview) this will point
5033 // to the current static clone of this document. This is weak since the clone
5034 // also has a reference to this document.
5035 WeakPtr<Document> mLatestStaticClone;
5037 // Array of nodes that have been blocked to prevent user tracking.
5038 // They most likely have had their nsIChannel canceled by the URL
5039 // classifier. (Safebrowsing)
5041 // Weak nsINode pointers are used to allow nodes to disappear.
5042 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
5044 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5045 // updated on every set of mScriptGlobalObject.
5046 nsPIDOMWindowInner* mWindow;
5048 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
5050 FrameRequestManager mFrameRequestManager;
5052 // This object allows us to evict ourself from the back/forward cache. The
5053 // pointer is non-null iff we're currently in the bfcache.
5054 nsIBFCacheEntry* mBFCacheEntry;
5056 // Our base target.
5057 nsString mBaseTarget;
5059 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
5060 JS::Heap<JS::Value> mCachedStateObject;
5062 uint32_t mInSyncOperationCount;
5064 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
5066 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
5068 uint32_t mBlockDOMContentLoaded;
5070 // Our live MediaQueryLists
5071 LinkedList<MediaQueryList> mDOMMediaQueryLists;
5073 // A hashset to keep track of which {element, imgRequestProxy}
5074 // combination has been processed to avoid considering the same
5075 // element twice for LargestContentfulPaint.
5076 nsTHashtable<LCPEntryHashEntry> mContentIdentifiersForLCP;
5078 // Array of observers
5079 nsTObserverArray<nsIDocumentObserver*> mObservers;
5081 // Flags for use counters used directly by this document.
5082 UseCounters mUseCounters;
5083 // Flags for use counters from resource documents, static clones,
5084 // and SVG images referenced by this document. Those documents propagate
5085 // their use counters up to here, which then count towards the top-level
5086 // document's page use counters.
5087 UseCounters mChildDocumentUseCounters;
5089 // The CSS property use counters.
5090 UniquePtr<StyleUseCounters> mStyleUseCounters;
5092 TimeStamp mPageUnloadingEventTimeStamp;
5094 RefPtr<DocGroup> mDocGroup;
5096 RefPtr<nsCommandManager> mMidasCommandManager;
5098 // The set of all the tracking script URLs. URLs are added to this set by
5099 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5100 // existing in the set means the corresponding script isn't a tracking script.
5101 nsTHashSet<nsCString> mTrackingScripts;
5103 // Pointer to our parser if we're currently in the process of being
5104 // parsed into.
5105 nsCOMPtr<nsIParser> mParser;
5107 // If the document was created from the the prototype cache there will be a
5108 // reference to the prototype document to allow tracing.
5109 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
5111 // Weak reference to our sink for in case we no longer have a parser. This
5112 // will allow us to flush out any pending stuff from the sink even if
5113 // EndLoad() has already happened.
5114 nsWeakPtr mWeakSink;
5116 // Our update nesting level
5117 uint32_t mUpdateNestLevel;
5119 // HTTPS-Only Mode Status
5120 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5121 uint32_t mHttpsOnlyStatus;
5123 enum ViewportType : uint8_t {
5124 DisplayWidthHeight,
5125 Specified,
5126 Unknown,
5129 ViewportType mViewportType;
5131 // viewport-fit described by
5132 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5133 ViewportFitType mViewportFit;
5135 // XXXdholbert This should really be modernized to a nsTHashMap or similar,
5136 // though note that the modernization will need to take care to also convert
5137 // the special hash_table_ops logic (e.g. how SubDocClearEntry clears the
5138 // parent document as part of cleaning up an entry in this table).
5139 UniquePtr<PLDHashTable> mSubDocuments;
5141 class HeaderData;
5142 UniquePtr<HeaderData> mHeaderData;
5144 nsTArray<net::EarlyHintConnectArgs> mEarlyHints;
5146 class TitleChangeEvent;
5147 nsRevocableEventPtr<TitleChangeEvent> mPendingTitleChangeEvent;
5149 RefPtr<nsDOMNavigationTiming> mTiming;
5151 // Recorded time of change to 'loading' state
5152 // or time of the page gets restored from BFCache.
5153 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp;
5155 // Decided to use nsTObserverArray because it allows us to
5156 // remove candidates while iterating them and this is what
5157 // the spec defines. We could implement the spec without
5158 // using nsTObserverArray, however using nsTObserverArray is more clear.
5159 nsTObserverArray<nsWeakPtr> mAutoFocusCandidates;
5161 nsCString mScrollToRef;
5163 // Weak reference to the scope object (aka the script global object)
5164 // that, unlike mScriptGlobalObject, is never unset once set. This
5165 // is a weak reference to avoid leaks due to circular references.
5166 nsWeakPtr mScopeObject;
5168 // Array of intersection observers
5169 nsTHashSet<DOMIntersectionObserver*> mIntersectionObservers;
5171 // Array of resize observers
5172 nsTArray<ResizeObserver*> mResizeObservers;
5174 RefPtr<DOMIntersectionObserver> mLazyLoadObserver;
5176 // Elements observed for a last remembered size.
5177 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5178 nsTHashSet<RefPtr<Element>> mElementsObservedForLastRememberedSize;
5180 // Stack of top layer elements.
5181 nsTArray<nsWeakPtr> mTopLayer;
5183 // The root of the doc tree in which this document is in. This is only
5184 // non-null when this document is in fullscreen mode.
5185 WeakPtr<Document> mFullscreenRoot;
5187 RefPtr<DOMImplementation> mDOMImplementation;
5189 RefPtr<nsContentList> mImageMaps;
5191 // A set of responsive images keyed by address pointer.
5192 nsTHashSet<HTMLImageElement*> mResponsiveContent;
5194 RefPtr<DocumentTimeline> mDocumentTimeline;
5195 LinkedList<DocumentTimeline> mTimelines;
5197 RefPtr<dom::ScriptLoader> mScriptLoader;
5199 // Tracker for scroll-driven animations that are waiting to start.
5200 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5201 RefPtr<ScrollTimelineAnimationTracker> mScrollTimelineAnimationTracker;
5203 // A document "without a browsing context" that owns the content of
5204 // HTMLTemplateElement.
5205 RefPtr<Document> mTemplateContentsOwner;
5207 dom::ExternalResourceMap mExternalResourceMap;
5209 // ScreenOrientation "pending promise" as described by
5210 // http://www.w3.org/TR/screen-orientation/
5211 RefPtr<Promise> mOrientationPendingPromise;
5213 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
5214 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
5215 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
5217 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
5219 // The layout history state that should be used by nodes in this
5220 // document. We only actually store a pointer to it when:
5221 // 1) We have no script global object.
5222 // 2) We haven't had Destroy() called on us yet.
5223 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
5225 // Mapping of wake lock types to sets of wake locks sentinels
5226 // https://w3c.github.io/screen-wake-lock/#internal-slots
5227 nsTHashMap<WakeLockType, nsTHashSet<RefPtr<WakeLockSentinel>>> mActiveLocks;
5229 // The parsed viewport metadata of the last modified <meta name=viewport>
5230 // element.
5231 UniquePtr<ViewportMetaData> mLastModifiedViewportMetaData;
5233 // A tree ordered list of all color-scheme meta tags in this document.
5235 // TODO(emilio): There are other meta tags in the spec that have a similar
5236 // processing model to color-scheme. We could store all in-document meta tags
5237 // here to get sane and fast <meta> element processing.
5238 TreeOrderedArray<HTMLMetaElement*> mColorSchemeMetaTags;
5240 // These member variables cache information about the viewport so we don't
5241 // have to recalculate it each time.
5242 LayoutDeviceToScreenScale mScaleMinFloat;
5243 LayoutDeviceToScreenScale mScaleMaxFloat;
5244 LayoutDeviceToScreenScale mScaleFloat;
5245 CSSToLayoutDeviceScale mPixelRatio;
5247 CSSCoord mMinWidth;
5248 CSSCoord mMaxWidth;
5249 CSSCoord mMinHeight;
5250 CSSCoord mMaxHeight;
5252 RefPtr<EventListenerManager> mListenerManager;
5254 nsCOMPtr<nsIRequest> mOnloadBlocker;
5256 // Gecko-internal sheets used for extensions and such.
5257 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5258 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5260 // Member to store out last-selected stylesheet set.
5261 nsString mLastStyleSheetSet;
5262 nsString mPreferredStyleSheetSet;
5264 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5266 // We lazily calculate declaration blocks for elements with mapped
5267 // attributes. This set contains all elements which need lazy resolution.
5268 nsTHashSet<Element*> mLazyPresElements;
5270 nsTHashSet<RefPtr<nsAtom>> mLanguagesUsed;
5272 // TODO(emilio): Is this hot enough to warrant to be cached?
5273 RefPtr<nsAtom> mLanguageFromCharset;
5275 // Restyle root for servo's style system.
5277 // We store this as an nsINode, rather than as an Element, so that we can
5278 // store the Document node as the restyle root if the entire document (along
5279 // with all document-level native-anonymous content) needs to be restyled.
5281 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5282 // root corresponds to.
5283 nsCOMPtr<nsINode> mServoRestyleRoot;
5284 uint32_t mServoRestyleRootDirtyBits;
5286 // Used in conjunction with the create-an-element-for-the-token algorithm to
5287 // prevent custom element constructors from being able to use document.open(),
5288 // document.close(), and document.write() when they are invoked by the parser.
5289 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5291 // Count of unload/beforeunload/pagehide operations in progress.
5292 uint32_t mIgnoreOpensDuringUnloadCounter;
5294 nsCOMPtr<nsIDOMXULCommandDispatcher>
5295 mCommandDispatcher; // [OWNER] of the focus tracker
5297 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5298 RefPtr<XULPersist> mXULPersist;
5299 RefPtr<ChromeObserver> mChromeObserver;
5301 RefPtr<HTMLAllCollection> mAll;
5303 nsTHashSet<RefPtr<WorkerDocumentListener>> mWorkerListeners;
5305 // Pres shell resolution saved before entering fullscreen mode.
5306 float mSavedResolution;
5308 // Pres shell resolution saved before creating a MobileViewportManager.
5309 float mSavedResolutionBeforeMVM;
5311 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5313 bool mHasStoragePermission;
5315 // Document generation. Gets incremented everytime it changes.
5316 int32_t mGeneration;
5318 // Cached TabSizes values for the document.
5319 int32_t mCachedTabSizeGeneration;
5320 nsTabSizes mCachedTabSizes;
5322 // This is equal to document's principal but with an isolation key. See
5323 // StoragePrincipalHelper.h to know more.
5324 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5326 // The cached storage principal for this document.
5327 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5328 // which is required due to its CloneDocHelper() call site. :-(
5329 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5331 // The cached cookie principal for this document.
5332 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5333 // which is required due to its CloneDocHelper() call site. :-(
5334 mutable nsCOMPtr<nsIPrincipal> mActiveCookiePrincipal;
5336 // See GetNextFormNumber and GetNextControlNumber.
5337 int32_t mNextFormNumber;
5338 int32_t mNextControlNumber;
5340 uint32_t mMediaElementWithMSECount = 0;
5342 // Scope preloads per document. This is used by speculative loading as well.
5343 PreloadService mPreloadService;
5345 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5346 bool mShouldNotifyFetchSuccess;
5348 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5349 bool mShouldNotifyFormOrPasswordRemoved;
5351 // Record page load telemetry
5352 void RecordPageLoadEventTelemetry(
5353 glean::perf::PageLoadExtra& aEventTelemetryData);
5355 // Accumulate JS telemetry collected
5356 void AccumulateJSTelemetry(
5357 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5359 // Accumulate page load metrics
5360 void AccumulatePageLoadTelemetry(
5361 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5363 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5364 // Not holding strong refs here since we don't actually use the BBCs.
5365 nsTArray<const BrowserBridgeChild*> mOOPChildrenLoading;
5367 // Registry of custom highlight definitions associated with this document.
5368 RefPtr<class HighlightRegistry> mHighlightRegistry;
5370 // Used for tracking a number of recent canvas extractions (e.g. toDataURL),
5371 // this is used for a canvas fingerprinter detection heuristic.
5372 nsTArray<CanvasUsage> mCanvasUsage;
5373 uint64_t mLastCanvasUsage = 0;
5375 UniquePtr<RadioGroupContainer> mRadioGroupContainer;
5377 public:
5378 // Needs to be public because the bindings code pokes at it.
5379 JS::ExpandoAndGeneration mExpandoAndGeneration;
5381 bool HasPendingInitialTranslation();
5383 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5384 mL10nProtoElements;
5386 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5387 void SetSavedResolutionBeforeMVM(float aResolution) {
5388 mSavedResolutionBeforeMVM = aResolution;
5391 void LoadEventFired();
5393 RadioGroupContainer& OwnedRadioGroupContainer();
5395 static already_AddRefed<Document> ParseHTMLUnsafe(GlobalObject& aGlobal,
5396 const nsAString& aHTML);
5399 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5402 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5403 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5404 * object is deleted.
5406 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5407 public:
5409 * @param aSubTreeOwner The document in which a subtree will be modified.
5410 * @param aTarget The target of the possible DOMSubtreeModified event.
5411 * Can be nullptr, in which case mozAutoSubtreeModified
5412 * is just used to batch DOM mutations.
5414 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5415 UpdateTarget(aSubtreeOwner, aTarget);
5418 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5420 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5421 if (mSubtreeOwner) {
5422 mSubtreeOwner->MutationEventDispatched(mTarget);
5425 mTarget = aTarget;
5426 mSubtreeOwner = aSubtreeOwner;
5427 if (mSubtreeOwner) {
5428 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5432 private:
5433 nsCOMPtr<nsINode> mTarget;
5434 RefPtr<Document> mSubtreeOwner;
5437 enum class SyncOperationBehavior { eSuspendInput, eAllowInput };
5439 class AutoWalkBrowsingContextGroup {
5440 public:
5441 virtual ~AutoWalkBrowsingContextGroup() = default;
5443 protected:
5444 void SuppressBrowsingContext(BrowsingContext* aContext);
5445 void SuppressBrowsingContextGroup(BrowsingContextGroup* aGroup);
5446 void UnsuppressDocuments() {
5447 for (const auto& doc : mDocuments) {
5448 UnsuppressDocument(doc);
5451 virtual void SuppressDocument(Document* aDocument) = 0;
5452 virtual void UnsuppressDocument(Document* aDocument) = 0;
5453 AutoTArray<RefPtr<Document>, 16> mDocuments;
5456 class MOZ_RAII nsAutoSyncOperation : private AutoWalkBrowsingContextGroup {
5457 public:
5458 explicit nsAutoSyncOperation(Document* aDocument,
5459 SyncOperationBehavior aSyncBehavior);
5460 ~nsAutoSyncOperation();
5462 protected:
5463 void SuppressDocument(Document* aDocument) override;
5464 void UnsuppressDocument(Document* aDocument) override;
5466 private:
5467 uint32_t mMicroTaskLevel;
5468 const SyncOperationBehavior mSyncBehavior;
5469 RefPtr<BrowsingContext> mBrowsingContext;
5472 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5473 public:
5474 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5475 : mDocument(aDocument) {
5476 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5479 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5480 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5483 private:
5484 Document* mDocument;
5487 class MOZ_RAII IgnoreOpensDuringUnload final {
5488 public:
5489 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5490 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5493 ~IgnoreOpensDuringUnload() {
5494 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5497 private:
5498 Document* mDoc;
5501 bool IsInFocusedTab(Document* aDoc);
5503 // This covers all cases covered by IsInFocusedTab, but also ensures that
5504 // focused tab is "active" meaning not occluded.
5505 bool IsInActiveTab(Document* aDoc);
5507 } // namespace mozilla::dom
5509 NON_VIRTUAL_ADDREF_RELEASE(mozilla::dom::Document)
5511 // XXX These belong somewhere else
5512 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5513 nsIPrincipal* aPrincipal,
5514 nsIPrincipal* aPartitionedPrincipal,
5515 bool aLoadedAsData = false);
5517 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5518 nsIPrincipal* aPrincipal,
5519 nsIPrincipal* aPartitionedPrincipal,
5520 bool aLoadedAsData = false,
5521 bool aIsPlainDocument = false);
5523 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult,
5524 nsIPrincipal* aPrincipal,
5525 nsIPrincipal* aPartitionedPrincipal);
5527 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult,
5528 nsIPrincipal* aPrincipal,
5529 nsIPrincipal* aPartitionedPrincipal);
5531 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult,
5532 nsIPrincipal* aPrincipal,
5533 nsIPrincipal* aPartitionedPrincipal);
5535 // Enum for requesting a particular type of document when creating a doc
5536 enum DocumentFlavor {
5537 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5538 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5539 DocumentFlavorSVG, // SVGDocument
5540 DocumentFlavorXML, // XMLDocument
5541 DocumentFlavorPlain, // Just a Document
5544 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5545 // -- this method will not attempt to get a principal based on aDocumentURI.
5546 // Also, both aDocumentURI and aBaseURI must not be null.
5547 nsresult NS_NewDOMDocument(
5548 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5549 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5550 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5551 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5553 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5554 mozilla::dom::Document* ownerDoc = OwnerDoc();
5556 return ownerDoc != this ? ownerDoc : nullptr;
5559 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5561 inline mozilla::dom::Document* nsINode::AsDocument() {
5562 MOZ_ASSERT(IsDocument());
5563 return static_cast<mozilla::dom::Document*>(this);
5566 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5567 MOZ_ASSERT(IsDocument());
5568 return static_cast<const mozilla::dom::Document*>(this);
5571 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5572 return static_cast<nsINode*>(aDoc);
5575 #endif /* mozilla_dom_Document_h___ */