Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / dom / base / Document.h
blobe919f19be08dcf688481b1b7b71cf16097f596cf
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 FragmentDirective;
248 class FrameRequestCallback;
249 class ImageTracker;
250 class HighlightRegistry;
251 class HTMLAllCollection;
252 class HTMLBodyElement;
253 class HTMLInputElement;
254 class HTMLMetaElement;
255 class HTMLDialogElement;
256 class HTMLSharedElement;
257 class HTMLImageElement;
258 struct LifecycleCallbackArgs;
259 class Link;
260 class Location;
261 class MediaQueryList;
262 struct NetErrorInfo;
263 class NodeFilter;
264 class NodeInfo;
265 class NodeIterator;
266 enum class OrientationType : uint8_t;
267 class ProcessingInstruction;
268 class Promise;
269 class ScriptLoader;
270 class Selection;
271 class ServiceWorkerDescriptor;
272 class ShadowRoot;
273 class SVGDocument;
274 class SVGElement;
275 class SVGSVGElement;
276 class SVGUseElement;
277 class ImageDocument;
278 class Touch;
279 class TouchList;
280 class TreeWalker;
281 enum class ViewportFitType : uint8_t;
282 class WakeLockSentinel;
283 class WindowContext;
284 class WindowGlobalChild;
285 class WindowProxyHolder;
286 struct Wireframe;
287 class WorkerDocumentListener;
288 class XPathEvaluator;
289 class XPathExpression;
290 class XPathNSResolver;
291 class XPathResult;
292 class BrowsingContext;
294 class nsUnblockOnloadEvent;
296 template <typename, typename>
297 class CallbackObjectHolder;
299 enum class CallerType : uint32_t;
301 enum BFCacheStatus {
302 NOT_ALLOWED = 1 << 0, // Status 0
303 EVENT_HANDLING_SUPPRESSED = 1 << 1, // Status 1
304 SUSPENDED = 1 << 2, // Status 2
305 UNLOAD_LISTENER = 1 << 3, // Status 3
306 REQUEST = 1 << 4, // Status 4
307 ACTIVE_GET_USER_MEDIA = 1 << 5, // Status 5
308 ACTIVE_PEER_CONNECTION = 1 << 6, // Status 6
309 CONTAINS_EME_CONTENT = 1 << 7, // Status 7
310 CONTAINS_MSE_CONTENT = 1 << 8, // Status 8
311 HAS_ACTIVE_SPEECH_SYNTHESIS = 1 << 9, // Status 9
312 HAS_USED_VR = 1 << 10, // Status 10
313 CONTAINS_REMOTE_SUBFRAMES = 1 << 11, // Status 11
314 NOT_ONLY_TOPLEVEL_IN_BCG = 1 << 12, // Status 12
315 ABOUT_PAGE = 1 << 13, // Status 13
316 RESTORING = 1 << 14, // Status 14
317 BEFOREUNLOAD_LISTENER = 1 << 15, // Status 15
318 ACTIVE_LOCK = 1 << 16, // Status 16
319 ACTIVE_WEBTRANSPORT = 1 << 17, // Status 17
322 } // namespace dom
323 namespace glean::perf {
324 struct PageLoadExtra;
326 } // namespace mozilla
328 namespace mozilla::net {
329 class ChannelEventQueue;
330 class EarlyHintConnectArgs;
331 } // namespace mozilla::net
333 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
334 #define NS_IDOCUMENT_IID \
336 0xce1f7627, 0x7109, 0x4977, { \
337 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
341 namespace mozilla::dom {
343 class Document;
344 class DOMStyleSheetSetList;
345 class ResizeObserver;
346 class ResizeObserverController;
347 class PostMessageEvent;
349 #define DEPRECATED_OPERATION(_op) e##_op,
350 enum class DeprecatedOperations : uint16_t {
351 #include "nsDeprecatedOperationList.h"
352 eDeprecatedOperationCount
354 #undef DEPRECATED_OPERATION
356 class ExternalResourceMap {
357 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
359 public:
361 * A class that represents an external resource load that has begun but
362 * doesn't have a document yet. Observers can be registered on this object,
363 * and will be notified after the document is created. Observers registered
364 * after the document has been created will NOT be notified. When observers
365 * are notified, the subject will be the newly-created document, the topic
366 * will be "external-resource-document-created", and the data will be null.
367 * If document creation fails for some reason, observers will still be
368 * notified, with a null document pointer.
370 class ExternalResourceLoad : public nsISupports {
371 public:
372 virtual ~ExternalResourceLoad() = default;
374 void AddObserver(nsIObserver* aObserver) {
375 MOZ_ASSERT(aObserver, "Must have observer");
376 mObservers.AppendElement(aObserver);
379 const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
381 protected:
382 AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
385 ExternalResourceMap();
388 * Request an external resource document. This does exactly what
389 * Document::RequestExternalResource is documented to do.
391 Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
392 nsINode* aRequestingNode,
393 Document* aDisplayDocument,
394 ExternalResourceLoad** aPendingLoad);
397 * Enumerate the resource documents. See
398 * Document::EnumerateExternalResources.
400 void EnumerateResources(SubDocEnumFunc aCallback);
403 * Traverse ourselves for cycle-collection
405 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
408 * Shut ourselves down (used for cycle-collection unlink), as well
409 * as for document destruction.
411 void Shutdown() {
412 mPendingLoads.Clear();
413 mMap.Clear();
414 mHaveShutDown = true;
417 bool HaveShutDown() const { return mHaveShutDown; }
419 // Needs to be public so we can traverse them sanely
420 struct ExternalResource {
421 ~ExternalResource();
422 RefPtr<Document> mDocument;
423 nsCOMPtr<nsIDocumentViewer> mViewer;
424 nsCOMPtr<nsILoadGroup> mLoadGroup;
427 // Hide all our viewers
428 void HideViewers();
430 // Show all our viewers
431 void ShowViewers();
433 protected:
434 class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
435 ~PendingLoad() = default;
437 public:
438 explicit PendingLoad(Document* aDisplayDocument)
439 : mDisplayDocument(aDisplayDocument) {}
441 NS_DECL_ISUPPORTS
442 NS_DECL_NSISTREAMLISTENER
443 NS_DECL_NSIREQUESTOBSERVER
446 * Start aURI loading. This will perform the necessary security checks and
447 * so forth.
449 nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
450 nsINode* aRequestingNode);
452 * Set up an nsIDocumentViewer based on aRequest. This is guaranteed to
453 * put null in *aViewer and *aLoadGroup on all failures.
455 nsresult SetupViewer(nsIRequest* aRequest, nsIDocumentViewer** aViewer,
456 nsILoadGroup** aLoadGroup);
458 private:
459 RefPtr<Document> mDisplayDocument;
460 nsCOMPtr<nsIStreamListener> mTargetListener;
461 nsCOMPtr<nsIURI> mURI;
463 friend class PendingLoad;
465 class LoadgroupCallbacks final : public nsIInterfaceRequestor {
466 ~LoadgroupCallbacks() = default;
468 public:
469 explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
470 : mCallbacks(aOtherCallbacks) {}
471 NS_DECL_ISUPPORTS
472 NS_DECL_NSIINTERFACEREQUESTOR
473 private:
474 // The only reason it's safe to hold a strong ref here without leaking is
475 // that the notificationCallbacks on a loadgroup aren't the docshell itself
476 // but a shim that holds a weak reference to the docshell.
477 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
479 // Use shims for interfaces that docshell implements directly so that we
480 // don't hand out references to the docshell. The shims should all allow
481 // getInterface back on us, but other than that each one should only
482 // implement one interface.
484 // XXXbz I wish we could just derive the _allcaps thing from _i
485 #define DECL_SHIM(_i, _allcaps) \
486 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
487 ~_i##Shim() {} \
489 public: \
490 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
491 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
492 NS_ASSERTION(mIfReq, "Expected non-null here"); \
493 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
495 NS_DECL_ISUPPORTS \
496 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
497 NS_FORWARD_##_allcaps(mRealPtr->) private \
498 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
499 nsCOMPtr<_i> mRealPtr; \
502 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
503 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
504 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
505 #undef DECL_SHIM
509 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
510 * when this is called if the URI didn't result in an XML document. This
511 * function makes sure to remove the pending load for aURI, if any, from our
512 * hashtable, and to notify its observers, if any.
514 nsresult AddExternalResource(nsIURI* aURI, nsIDocumentViewer* aViewer,
515 nsILoadGroup* aLoadGroup,
516 Document* aDisplayDocument);
518 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
519 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
520 bool mHaveShutDown;
523 // The current status for a preload.
524 enum class SheetPreloadStatus : uint8_t {
525 // There's no need to preload anything, the sheet is already in-memory.
526 AlreadyComplete,
527 // The load is in-progress. There's no guarantee that a load was started, it
528 // could be coalesced with other redundant loads.
529 InProgress,
530 // Something went wrong, and we errored out.
531 Errored,
534 //----------------------------------------------------------------------
536 // Document interface. This is implemented by all document objects in
537 // Gecko.
538 class Document : public nsINode,
539 public DocumentOrShadowRoot,
540 public nsSupportsWeakReference,
541 public nsIScriptObjectPrincipal,
542 public SupportsWeakPtr {
543 friend class DocumentOrShadowRoot;
545 protected:
546 explicit Document(const char* aContentType);
547 virtual ~Document();
549 Document(const Document&) = delete;
550 Document& operator=(const Document&) = delete;
552 public:
553 using ExternalResourceLoad = dom::ExternalResourceMap::ExternalResourceLoad;
554 using ReferrerPolicyEnum = dom::ReferrerPolicy;
555 using AdoptedStyleSheetCloneCache =
556 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
558 // nsINode overrides the new operator for DOM Arena allocation.
559 // to use the default one, we need to bring it back again
560 void* operator new(size_t aSize) { return ::operator new(aSize); }
563 * Called when XPCOM shutdown.
565 static void Shutdown();
567 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
569 NS_DECL_ISUPPORTS_INHERITED
570 NS_IMETHOD_(void) DeleteCycleCollectable() override;
572 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
574 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
575 nsINode)
577 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
578 do { \
579 for (RefPtr obs : mObservers.ForwardRange()) { \
580 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
581 obs->func_ params_; \
584 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
585 looks bogus. */ \
586 if (PresShell* presShell = GetObservingPresShell()) { \
587 presShell->func_ params_; \
589 } while (0)
591 nsIPrincipal* EffectiveCookiePrincipal() const;
593 nsIPrincipal* EffectiveStoragePrincipal() const;
595 // nsIScriptObjectPrincipal
596 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
598 nsIPrincipal* GetEffectiveCookiePrincipal() final {
599 return EffectiveCookiePrincipal();
602 nsIPrincipal* GetEffectiveStoragePrincipal() final {
603 return EffectiveStoragePrincipal();
606 // You should probably not be using this function, since it performs no checks
607 // to ensure that the partitioned principal should really be used here. It is
608 // only designed to be used in very specific circumstances, such as when
609 // inheriting the document/storage principal.
610 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
612 // Gets the appropriate principal to check the URI against a blocklist /
613 // allowlist.
614 nsIPrincipal* GetPrincipalForPrefBasedHacks() const;
616 void ClearActiveCookieAndStoragePrincipals() {
617 mActiveStoragePrincipal = nullptr;
618 mActiveCookiePrincipal = nullptr;
621 // EventTarget
622 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
623 EventListenerManager* GetOrCreateListenerManager() override;
624 EventListenerManager* GetExistingListenerManager() const override;
626 // This helper class must be set when we dispatch beforeunload and unload
627 // events in order to avoid unterminate sync XHRs.
628 class MOZ_RAII PageUnloadingEventTimeStamp {
629 RefPtr<Document> mDocument;
630 bool mSet;
632 public:
633 explicit PageUnloadingEventTimeStamp(Document* aDocument)
634 : mDocument(aDocument), mSet(false) {
635 MOZ_ASSERT(aDocument);
636 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
637 mDocument->SetPageUnloadingEventTimeStamp();
638 mSet = true;
642 ~PageUnloadingEventTimeStamp() {
643 if (mSet) {
644 mDocument->CleanUnloadEventsTimeStamp();
650 * Let the document know that we're starting to load data into it.
651 * @param aCommand The parser command. Must not be null.
652 * XXXbz It's odd to have that here.
653 * @param aChannel The channel the data will come from. The channel must be
654 * able to report its Content-Type.
655 * @param aLoadGroup The loadgroup this document should use from now on.
656 * Note that the document might not be the only thing using
657 * this loadgroup.
658 * @param aContainer The container this document is in. This may be null.
659 * XXXbz maybe we should make it more explicit (eg make the
660 * container an nsIWebNavigation or nsIDocShell or
661 * something)?
662 * @param [out] aDocListener the listener to pump data from the channel into.
663 * Generally this will be the parser this document
664 * sets up, or some sort of data-handler for media
665 * documents.
666 * @param aReset whether the document should call Reset() on itself. If this
667 * is false, the document will NOT set its principal to the
668 * channel's owner, will not clear any event listeners that are
669 * already set on it, etc.
671 * Once this has been called, the document will return false for
672 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
673 * sure this happens is the responsibility of the caller of
674 * StartDocumentLoad().
676 * This function has an implementation, and does some setup, but does NOT set
677 * *aDocListener; this is the job of subclasses.
679 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
680 nsILoadGroup* aLoadGroup,
681 nsISupports* aContainer,
682 nsIStreamListener** aDocListener,
683 bool aReset) = 0;
684 void StopDocumentLoad();
686 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
687 virtual bool SuppressParserErrorElement() { return false; }
689 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
690 virtual bool SuppressParserErrorConsoleMessages() { return false; }
692 // nsINode
693 void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
694 bool aNotify, ErrorResult& aRv) override;
695 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
696 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
697 return NS_ERROR_NOT_IMPLEMENTED;
699 nsresult CloneDocHelper(Document* clone) const;
701 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
704 * Signal that the document title may have changed
705 * (see Document::GetTitle).
706 * @param aBoundTitleElement true if an HTML or SVG <title> element
707 * has just been bound to the document.
709 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
712 * Return the URI for the document. May return null. If it ever stops being
713 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
714 * also never return null.
716 * The value returned corresponds to the "document's address" in
717 * HTML5. As such, it may change over the lifetime of the document, for
718 * instance as a result of the user navigating to a fragment identifier on
719 * the page, or as a result to a call to pushState() or replaceState().
721 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
723 nsIURI* GetDocumentURI() const { return mDocumentURI; }
726 * Return the original URI of the document. This is the same as the
727 * document's URI unless that has changed from its original value (for
728 * example, due to history.pushState() or replaceState() being invoked on the
729 * document).
731 * This method corresponds to the "creation URL" in HTML5 and, once set,
732 * doesn't change over the lifetime of the document.
734 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
736 nsIURI* GetOriginalURI() const { return mOriginalURI; }
739 * Return the base domain of the document. This has been computed using
740 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
741 * checks. When the URI of the document changes, this value is recomputed.
743 nsCString GetBaseDomain() const { return mBaseDomain; }
746 * Set the URI for the document. This also sets the document's original URI,
747 * if it's null.
749 void SetDocumentURI(nsIURI* aURI);
752 * Set the URI for the document loaded via XHR, when accessed from
753 * chrome privileged script.
755 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
758 * Set the base URI for the document loaded via XHR, when accessed from
759 * chrome privileged script.
761 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
764 * The CSP in general is stored in the ClientInfo, but we also cache
765 * the CSP on the document so subresources loaded within a document
766 * can query that cached CSP instead of having to deserialize the CSP
767 * from the Client.
769 * Please note that at the time of CSP parsing the Client is not
770 * available yet, hence we sync CSP of document and Client when the
771 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
773 nsIContentSecurityPolicy* GetCsp() const;
774 void SetCsp(nsIContentSecurityPolicy* aCSP);
776 nsIContentSecurityPolicy* GetPreloadCsp() const;
777 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
779 void GetCspJSON(nsString& aJSON);
782 * Set referrer policy and upgrade-insecure-requests flags
784 void ApplySettingsFromCSP(bool aSpeculative);
786 already_AddRefed<nsIParser> CreatorParserOrNull() {
787 nsCOMPtr<nsIParser> parser = mParser;
788 return parser.forget();
792 * ReferrerInfo getter for Document.webidl.
794 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
796 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
798 nsIReferrerInfo* GetPreloadReferrerInfo() const {
799 return mPreloadReferrerInfo;
802 * Return the referrer policy of the document. Return "default" if there's no
803 * valid meta referrer tag found in the document.
804 * Referrer policy should be inherited from parent if the iframe is srcdoc
806 ReferrerPolicyEnum GetReferrerPolicy() const;
809 * GetReferrerPolicy() for Document.webidl.
811 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
814 * If true, this flag indicates that all mixed content subresource
815 * loads for this document (and also embeded browsing contexts) will
816 * be blocked.
818 bool GetBlockAllMixedContent(bool aPreload) const {
819 if (aPreload) {
820 return mBlockAllMixedContentPreloads;
822 return mBlockAllMixedContent;
826 * If true, this flag indicates that all subresource loads for this
827 * document need to be upgraded from http to https.
828 * This flag becomes true if the CSP of the document itself, or any
829 * of the document's ancestors up to the toplevel document makes use
830 * of the CSP directive 'upgrade-insecure-requests'.
832 bool GetUpgradeInsecureRequests(bool aPreload) const {
833 if (aPreload) {
834 return mUpgradeInsecurePreloads;
836 return mUpgradeInsecureRequests;
839 void SetReferrerInfo(nsIReferrerInfo*);
842 * Referrer policy from <meta name="referrer" content=`policy`>
843 * will have higher priority than referrer policy from Referrer-Policy
844 * header. So override the old ReferrerInfo if we get one from meta
846 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
847 bool aPreload);
850 * Set the principals responsible for this document. Chances are, you do not
851 * want to be using this.
853 void SetPrincipals(nsIPrincipal* aPrincipal,
854 nsIPrincipal* aPartitionedPrincipal);
857 * Returns true if exempt from HTTPS-Only Mode upgrade.
859 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
862 * Return the LoadGroup for the document. May return null.
864 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
865 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
866 return group.forget();
870 * Return the fallback base URL for this document, as defined in the HTML
871 * specification. Note that this can return null if there is no document URI.
873 * XXXbz: This doesn't implement the bits for about:blank yet.
875 nsIURI* GetFallbackBaseURI() const {
876 if (mIsSrcdocDocument && mParentDocument) {
877 return mParentDocument->GetDocBaseURI();
879 return mDocumentURI;
883 * Return the referrer from document URI as defined in the Referrer Policy
884 * specification.
885 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
886 * While document is an iframe srcdoc document, let document be document's
887 * browsing context's browsing context container's node document.
888 * Then referrer should be document's URL
891 nsIURI* GetDocumentURIAsReferrer() const {
892 if (mIsSrcdocDocument && mParentDocument) {
893 return mParentDocument->GetDocumentURIAsReferrer();
895 return mDocumentURI;
899 * Return the base URI for relative URIs in the document (the document uri
900 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
901 * returned URI could be null if there is no document URI. If the document is
902 * a srcdoc document and has no explicit base URL, return the parent
903 * document's base URL.
905 nsIURI* GetDocBaseURI() const {
906 if (mDocumentBaseURI) {
907 return mDocumentBaseURI;
909 return GetFallbackBaseURI();
912 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
914 void SetBaseURI(nsIURI* aURI);
917 * Resolves a URI based on the document's base URI.
919 Result<OwningNonNull<nsIURI>, nsresult> ResolveWithBaseURI(
920 const nsAString& aURI);
923 * Return the URL data which style system needs for resolving url value.
924 * This method attempts to use the cached object in mCachedURLData, but
925 * if the base URI, document URI, or principal has changed since last
926 * call to this function, or the function is called the first time for
927 * the document, a new one is created.
929 URLExtraData* DefaultStyleAttrURLData();
930 nsIReferrerInfo* ReferrerInfoForInternalCSSAndSVGResources();
933 * Get/Set the base target of a link in a document.
935 void GetBaseTarget(nsAString& aBaseTarget) const {
936 aBaseTarget = mBaseTarget;
939 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
942 * Return a standard name for the document's character set.
944 NotNull<const Encoding*> GetDocumentCharacterSet() const {
945 return mCharacterSet;
949 * Set the document's character encoding.
951 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
953 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
955 // This method MUST be called before SetDocumentCharacterSet if
956 // you're planning to call both.
957 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
958 mCharacterSetSource = aCharsetSource;
962 * Get the Content-Type of this document.
964 void GetContentType(nsAString& aContentType);
967 * Set the Content-Type of this document.
969 void SetContentType(const nsACString& aContentType);
972 * Return the language of this document, or null if not set.
974 nsAtom* GetContentLanguage() const { return mContentLanguage.get(); }
976 void GetContentLanguageForBindings(DOMString&) const;
978 // The states BidiEnabled and MathMLEnabled should persist across multiple
979 // views (screen, print) of the same document.
982 * Check if the document contains bidi data.
983 * If so, we have to apply the Unicode Bidi Algorithm.
985 bool GetBidiEnabled() const { return mBidiEnabled; }
988 * Indicate the document contains bidi data.
989 * Currently, we cannot disable bidi, because once bidi is enabled,
990 * it affects a frame model irreversibly, and plays even though
991 * the document no longer contains bidi data.
993 void SetBidiEnabled() { mBidiEnabled = true; }
995 void SetMathMLEnabled() { mMathMLEnabled = true; }
998 * Ask this document whether it's the initial document in its window.
1000 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
1003 * Ask this document whether it has ever been a initial document in its
1004 * window.
1006 bool IsEverInitialDocument() const { return mIsEverInitialDocumentInWindow; }
1009 * Tell this document that it's the initial document in its window. See
1010 * comments on mIsInitialDocumentInWindow for when this should be called.
1012 void SetIsInitialDocument(bool aIsInitialDocument);
1014 void SetLoadedAsData(bool aLoadedAsData, bool aConsiderForMemoryReporting);
1016 TimeStamp GetLoadingOrRestoredFromBFCacheTimeStamp() const {
1017 return mLoadingOrRestoredFromBFCacheTimeStamp;
1019 void SetLoadingOrRestoredFromBFCacheTimeStampToNow() {
1020 mLoadingOrRestoredFromBFCacheTimeStamp = TimeStamp::Now();
1024 * Normally we assert if a runnable labeled with one DocGroup touches data
1025 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1026 * means that we can touch that document from any DocGroup without asserting.
1028 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1031 * Get the bidi options for this document.
1032 * @see nsBidiUtils.h
1034 uint32_t GetBidiOptions() const { return mBidiOptions; }
1037 * Set the bidi options for this document. This just sets the bits;
1038 * callers are expected to take action as needed if they want this
1039 * change to actually change anything immediately.
1040 * @see nsBidiUtils.h
1042 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1045 * Returns true if the document holds a CSP
1046 * delivered through an HTTP Header.
1048 bool GetHasCSPDeliveredThroughHeader() {
1049 return mHasCSPDeliveredThroughHeader;
1053 * Return a promise which resolves to the content blocking events.
1055 using GetContentBlockingEventsPromise = MozPromise<uint32_t, bool, true>;
1056 [[nodiscard]] RefPtr<GetContentBlockingEventsPromise>
1057 GetContentBlockingEvents();
1060 * Get the sandbox flags for this document.
1061 * @see nsSandboxFlags.h for the possible flags
1063 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1065 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1066 return mEmbedderPolicy;
1069 void SetEmbedderPolicy(
1070 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1071 mEmbedderPolicy = aCOEP;
1075 * Get string representation of sandbox flags (null if no flags are set)
1077 void GetSandboxFlagsAsString(nsAString& aFlags);
1080 * Set the sandbox flags for this document.
1081 * @see nsSandboxFlags.h for the possible flags
1083 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1086 * Called when the document was decoded as UTF-8 and decoder encountered no
1087 * errors.
1089 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1092 * Called to disable client access to cookies through the document.cookie API
1093 * from user JavaScript code.
1095 void DisableCookieAccess() { mDisableCookieAccess = true; }
1097 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1098 bool LinkHandlingEnabled() { return mLinksEnabled; }
1101 * Set compatibility mode for this document
1103 void SetCompatibilityMode(nsCompatibility aMode);
1106 * Called to disable client access to document.write() API from user
1107 * JavaScript code.
1109 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1112 * Whether a document.write() call is in progress.
1114 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1117 * Access HTTP header data (this may also get set from other
1118 * sources, like HTML META tags).
1120 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1121 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1124 * Set Early Hint data, moves the arrays into the function, leaving the
1125 * passed variables empty
1127 void SetEarlyHints(nsTArray<net::EarlyHintConnectArgs>&& aEarlyHints);
1128 const nsTArray<net::EarlyHintConnectArgs>& GetEarlyHints() const {
1129 return mEarlyHints;
1133 * Create a new presentation shell that will use aContext for its
1134 * presentation context (presentation contexts <b>must not</b> be
1135 * shared among multiple presentation shells). The caller of this
1136 * method is responsible for calling BeginObservingDocument() on the
1137 * presshell if the presshell should observe document mutations.
1139 MOZ_CAN_RUN_SCRIPT already_AddRefed<PresShell> CreatePresShell(
1140 nsPresContext* aContext, nsViewManager* aViewManager);
1141 void DeletePresShell();
1143 PresShell* GetPresShell() const {
1144 return GetBFCacheEntry() ? nullptr : mPresShell;
1147 inline PresShell* GetObservingPresShell() const;
1149 // Return whether the presshell for this document is safe to flush.
1150 bool IsSafeToFlush() const;
1152 inline nsPresContext* GetPresContext() const;
1154 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1156 // Instead using this method, what you probably want is
1157 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1158 void DisallowBFCaching(uint32_t aStatus = BFCacheStatus::NOT_ALLOWED);
1160 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1162 // Accepts null to clear the BFCache entry too.
1163 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1165 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1167 // Removes this document from the BFCache, if it is cached, and returns
1168 // true if it was.
1169 bool RemoveFromBFCacheSync();
1172 * Return the parent document of this document. Will return null
1173 * unless this document is within a compound document and has a
1174 * parent. Note that this parent chain may cross chrome boundaries.
1176 Document* GetInProcessParentDocument() const { return mParentDocument; }
1179 * Set the parent document of this document.
1181 void SetParentDocument(Document* aParent) {
1182 mParentDocument = aParent;
1183 if (aParent) {
1184 RecomputeResistFingerprinting();
1185 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1189 void SetCurrentContextPaint(const SVGContextPaint* aContextPaint) {
1190 mCurrentContextPaint = aContextPaint;
1193 const SVGContextPaint* GetCurrentContextPaint() const {
1194 return mCurrentContextPaint;
1198 * Set the sub document for aContent to aSubDoc.
1200 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1203 * Get the sub document for aContent
1205 Document* GetSubDocumentFor(nsIContent* aContent) const;
1208 * Get the content node for which this document is a sub document.
1210 Element* GetEmbedderElement() const;
1213 * Return the doctype for this document.
1215 DocumentType* GetDoctype() const;
1218 * Return the root element for this document.
1220 Element* GetRootElement() const;
1222 Selection* GetSelection(ErrorResult& aRv);
1224 void MakeBrowsingContextNonSynthetic();
1225 nsresult HasStorageAccessSync(bool& aHasStorageAccess);
1226 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1228 StorageAccessAPIHelper::PerformPermissionGrant CreatePermissionGrantPromise(
1229 nsPIDOMWindowInner* aInnerWindow, nsIPrincipal* aPrincipal,
1230 bool aHasUserInteraction, bool aRequireUserInteraction,
1231 const Maybe<nsCString>& aTopLevelBaseDomain, bool aFrameOnly);
1233 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1235 already_AddRefed<Promise> RequestStorageAccessForOrigin(
1236 const nsAString& aThirdPartyOrigin, const bool aRequireUserInteraction,
1237 ErrorResult& aRv);
1239 already_AddRefed<Promise> RequestStorageAccessUnderSite(
1240 const nsAString& aSerializedSite, ErrorResult& aRv);
1241 already_AddRefed<Promise> CompleteStorageAccessRequestFromSite(
1242 const nsAString& aSerializedOrigin, ErrorResult& aRv);
1244 bool UseRegularPrincipal() const;
1247 * Gets the event target to dispatch key events to if there is no focused
1248 * content in the document.
1250 virtual Element* GetUnfocusedKeyEventTarget();
1253 * Retrieve information about the viewport as a data structure.
1254 * This will return information in the viewport META data section
1255 * of the document. This can be used in lieu of ProcessViewportInfo(),
1256 * which places the viewport information in the document header instead
1257 * of returning it directly.
1259 * @param aDisplaySize size of the on-screen display area for this
1260 * document, in device pixels.
1262 * NOTE: If the site is optimized for mobile (via the doctype), this
1263 * will return viewport information that specifies default information.
1265 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1267 void SetMetaViewportData(UniquePtr<ViewportMetaData> aData);
1269 // Returns a ViewportMetaData for this document.
1270 ViewportMetaData GetViewportMetaData() const;
1273 * True iff this doc will ignore manual character encoding overrides.
1275 virtual bool WillIgnoreCharsetOverride() { return true; }
1278 * Return whether the document was created by a srcdoc iframe.
1280 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1283 * Sets whether the document was created by a srcdoc iframe.
1285 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1286 mIsSrcdocDocument = aIsSrcdocDocument;
1290 * Gets the srcdoc string from within the channel (assuming both exist).
1291 * Returns a void string if this isn't a srcdoc document or if
1292 * the channel has not been set.
1294 nsresult GetSrcdocData(nsAString& aSrcdocData);
1296 already_AddRefed<AnonymousContent> InsertAnonymousContent(bool aForce,
1297 ErrorResult&);
1298 void RemoveAnonymousContent(AnonymousContent&);
1300 * If aNode is a descendant of anonymous content inserted by
1301 * InsertAnonymousContent, this method returns the root element of the
1302 * inserted anonymous content (in other words, the clone of the aElement
1303 * that was passed to InsertAnonymousContent).
1305 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1306 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1307 return mAnonymousContents;
1310 TimeStamp GetPageUnloadingEventTimeStamp() const {
1311 if (!mParentDocument) {
1312 return mPageUnloadingEventTimeStamp;
1315 TimeStamp parentTimeStamp(
1316 mParentDocument->GetPageUnloadingEventTimeStamp());
1317 if (parentTimeStamp.IsNull()) {
1318 return mPageUnloadingEventTimeStamp;
1321 if (!mPageUnloadingEventTimeStamp ||
1322 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1323 return parentTimeStamp;
1326 return mPageUnloadingEventTimeStamp;
1329 void NotifyLayerManagerRecreated();
1331 // Add an element to the list of elements that need their mapped attributes
1332 // resolved to a declaration block.
1334 // These are weak pointers, manually unschedule them when an element is
1335 // removed from the tree.
1336 void ScheduleForPresAttrEvaluation(Element* aElement);
1338 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1339 // generally when it's unbound from the tree.
1340 void UnscheduleForPresAttrEvaluation(Element* aElement);
1342 // Resolve all presentational attributes scheduled in
1343 // ScheduleForPresAttrEvaluation
1344 void ResolveScheduledPresAttrs() {
1345 if (mLazyPresElements.IsEmpty()) {
1346 return;
1348 DoResolveScheduledPresAttrs();
1351 Maybe<ClientInfo> GetClientInfo() const;
1352 Maybe<ClientState> GetClientState() const;
1353 Maybe<ServiceWorkerDescriptor> GetController() const;
1355 // Given a node, get a weak reference to it and append that reference to
1356 // mBlockedNodesByClassifier. Can be used later on to look up a node in it.
1357 // (e.g., by the UI)
1358 // /
1359 void AddBlockedNodeByClassifier(nsINode* aNode) {
1360 if (aNode) {
1361 mBlockedNodesByClassifier.AppendElement(do_GetWeakReference(aNode));
1365 // Returns the size of the mBlockedNodesByClassifier array.
1367 // This array contains nodes that have been blocked to prevent user tracking,
1368 // fingerprinting, cryptomining, etc. They most likely have had their
1369 // nsIChannel canceled by the URL classifier (Safebrowsing).
1371 // A script can subsequently use GetBlockedNodesByClassifier()
1372 // to get a list of references to these nodes.
1374 // Note:
1375 // This expresses how many tracking nodes have been blocked for this document
1376 // since its beginning, not how many of them are still around in the DOM tree.
1377 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1378 // array but they are not removed when those nodes are removed from the tree
1379 // or even garbage collected.
1380 size_t BlockedNodeByClassifierCount() const {
1381 return mBlockedNodesByClassifier.Length();
1384 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1385 // This array contains nodes that have been blocked to prevent
1386 // user tracking. They most likely have had their nsIChannel
1387 // canceled by the URL classifier (Safebrowsing).
1388 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1390 // Helper method that returns true if the document has storage-access sandbox
1391 // flag.
1392 bool StorageAccessSandboxed() const;
1394 // Helper method that returns true if storage access API is enabled and
1395 // the passed flag has storage-access sandbox flag.
1396 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1398 // Returns the cookie jar settings for this and sub contexts.
1399 nsICookieJarSettings* CookieJarSettings();
1401 // Returns whether this document is using unpartitioned cookies
1402 bool UsingStorageAccess();
1404 // Returns whether the storage access permission of the document is granted by
1405 // the allow list.
1406 bool HasStorageAccessPermissionGrantedByAllowList();
1408 // Increments the document generation.
1409 inline void Changed() { ++mGeneration; }
1411 // Returns the current generation.
1412 inline int32_t GetGeneration() const { return mGeneration; }
1414 // Adds cached sizes values to aSizes if there's any
1415 // cached value and if the document generation hasn't
1416 // changed since the cache was created.
1417 // Returns true if sizes were added.
1418 bool GetCachedSizes(nsTabSizes* aSizes);
1420 // Sets the cache sizes for the current generation.
1421 void SetCachedSizes(nsTabSizes* aSizes);
1424 * Should be called when an element's editable changes as a result of
1425 * changing its contentEditable attribute/property.
1427 * The change should be +1 if the contentEditable attribute/property was
1428 * changed to true, -1 if it was changed to false.
1430 void ChangeContentEditableCount(Element*, int32_t aChange);
1431 MOZ_CAN_RUN_SCRIPT void DeferredContentEditableCountChange(Element*);
1433 enum class EditingState : int8_t {
1434 eTearingDown = -2,
1435 eSettingUp = -1,
1436 eOff = 0,
1437 eDesignMode,
1438 eContentEditable
1442 * Returns the editing state of the document (not editable, contentEditable or
1443 * designMode).
1445 EditingState GetEditingState() const { return mEditingState; }
1448 * Returns whether the document is editable.
1450 bool IsEditingOn() const {
1451 return GetEditingState() == EditingState::eDesignMode ||
1452 GetEditingState() == EditingState::eContentEditable;
1455 class MOZ_STACK_CLASS nsAutoEditingState {
1456 public:
1457 nsAutoEditingState(Document* aDoc, EditingState aState)
1458 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1459 aDoc->mEditingState = aState;
1461 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1463 private:
1464 RefPtr<Document> mDoc;
1465 EditingState mSavedState;
1467 friend class nsAutoEditingState;
1470 * Set the editing state of the document. Don't use this if you want
1471 * to enable/disable editing, call EditingStateChanged() or
1472 * SetDesignMode().
1474 void SetEditingState(EditingState aState) { mEditingState = aState; }
1477 * Called when this Document's editor is destroyed.
1479 void TearingDownEditor();
1481 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1483 // Gets the next form number.
1485 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1486 // parser inserted form element.
1487 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1489 // Gets the next form control number.
1491 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1492 // parser inserted form control element.
1493 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1495 PreloadService& Preloads() { return mPreloadService; }
1497 bool HasThirdPartyChannel();
1499 bool ShouldIncludeInTelemetry() const;
1501 void AddMediaElementWithMSE();
1502 void RemoveMediaElementWithMSE();
1504 void DoNotifyPossibleTitleChange();
1506 void InitFeaturePolicy();
1507 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1509 void EnsureNotEnteringAndExitFullscreen();
1511 protected:
1512 friend class nsUnblockOnloadEvent;
1514 nsresult InitCSP(nsIChannel* aChannel);
1515 nsresult InitCOEP(nsIChannel* aChannel);
1517 nsresult InitReferrerInfo(nsIChannel* aChannel);
1519 void PostUnblockOnloadEvent();
1521 void DoUnblockOnload();
1523 void DoResolveScheduledPresAttrs();
1525 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1527 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1528 NotNull<const Encoding*>& aEncoding,
1529 nsHtml5TreeOpExecutor* aExecutor);
1531 MOZ_CAN_RUN_SCRIPT void DispatchContentLoadedEvents();
1533 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1534 MOZ_CAN_RUN_SCRIPT_BOUNDARY void DispatchPageTransition(
1535 EventTarget* aDispatchTarget, const nsAString& aType, bool aInFrameSwap,
1536 bool aPersisted, bool aOnlySystemGroup);
1538 // Call this before the document does something that will unbind all content.
1539 // That will stop us from doing a lot of work as each element is removed.
1540 void DestroyElementMaps();
1542 Element* GetRootElementInternal() const;
1544 void SetPageUnloadingEventTimeStamp() {
1545 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1546 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1549 void CleanUnloadEventsTimeStamp() {
1550 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1551 mPageUnloadingEventTimeStamp = TimeStamp();
1555 * Clears any Servo element data stored on Elements in the document.
1557 void ClearStaleServoData();
1560 * Do the tree-disconnection that ResetToURI and document.open need to do.
1562 void DisconnectNodeTree();
1565 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1566 * "CheckKeyPressEventModel" event to check whether we should dispatch
1567 * keypress events in confluent model or split model. This should be
1568 * called only when mEditingState is changed to eDesignMode or
1569 * eConentEditable at first time.
1571 void MaybeDispatchCheckKeyPressEventModelEvent();
1573 /* Midas implementation */
1574 nsCommandManager* GetMidasCommandManager();
1576 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1578 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1579 // of places, and I'm pretty sure the exact ExecCommand call it
1580 // makes cannot actually run script.
1581 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1583 void MaybeEditingStateChanged();
1585 public:
1586 // Get the root <html> element, or return null if there isn't one (e.g.
1587 // if the root isn't <html>)
1588 Element* GetHtmlElement() const;
1589 // Returns the first child of GetHtmlContent which has the given tag,
1590 // or nullptr if that doesn't exist.
1591 Element* GetHtmlChildElement(nsAtom* aTag);
1592 // Get the canonical <body> element, or return null if there isn't one (e.g.
1593 // if the root isn't <html> or if the <body> isn't there)
1594 HTMLBodyElement* GetBodyElement();
1595 // Get the canonical <head> element, or return null if there isn't one (e.g.
1596 // if the root isn't <html> or if the <head> isn't there)
1597 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1598 // Get the "body" in the sense of document.body: The first <body> or
1599 // <frameset> that's a child of a root <html>
1600 nsGenericHTMLElement* GetBody();
1601 // Set the "body" in the sense of document.body.
1602 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1603 // Get the "head" element in the sense of document.head.
1604 HTMLSharedElement* GetHead();
1606 ServoStyleSet* StyleSetForPresShell() const {
1607 MOZ_ASSERT(!!mStyleSet.get());
1608 return mStyleSet.get();
1611 inline ServoStyleSet& EnsureStyleSet() const;
1613 // ShadowRoot has APIs that can change styles. This notifies the shell that
1614 // stlyes applicable in the shadow tree have potentially changed.
1615 void RecordShadowStyleChange(ShadowRoot&);
1617 // Needs to be called any time the applicable style can has changed, in order
1618 // to schedule a style flush and setup all the relevant state.
1620 // If we know the stylesheet change applies only to a shadow tree we can avoid
1621 // some work (like updating the font-face-set / counter-styles / etc, as those
1622 // are global).
1623 void ApplicableStylesChanged(bool aKnownInShadowTree = false);
1625 // Whether we filled the style set with any style sheet. Only meant to be used
1626 // from DocumentOrShadowRoot::Traverse.
1627 bool StyleSetFilled() const { return mStyleSetFilled; }
1630 * Accessors to the collection of stylesheets owned by this document.
1631 * Style sheets are ordered, most significant last.
1634 void InsertSheetAt(size_t aIndex, StyleSheet&);
1637 * Add a stylesheet to the document
1639 * TODO(emilio): This is only used by parts of editor that are no longer in
1640 * use by m-c or c-c, so remove.
1642 void AddStyleSheet(StyleSheet* aSheet) {
1643 MOZ_ASSERT(aSheet);
1644 InsertSheetAt(SheetCount(), *aSheet);
1648 * Notify the document that the applicable state of the sheet changed
1649 * and that observers should be notified and style sets updated
1651 void StyleSheetApplicableStateChanged(StyleSheet&);
1652 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1653 void PostStyleSheetRemovedEvent(StyleSheet&);
1654 void PostCustomPropertyRegistered(const dom::PropertyDefinition&);
1656 enum additionalSheetType {
1657 eAgentSheet,
1658 eUserSheet,
1659 eAuthorSheet,
1660 AdditionalSheetTypeCount
1663 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1664 nsIURI* aSheetURI);
1665 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1666 StyleSheet* aSheet);
1667 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1669 StyleSheet* GetFirstAdditionalAuthorSheet() {
1670 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1674 * Returns the index that aSheet should be inserted at to maintain document
1675 * ordering.
1677 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1680 * Get this document's CSSLoader. This is guaranteed to not return null.
1682 css::Loader* CSSLoader() const { return mCSSLoader; }
1685 * Get this document's StyleImageLoader. This is guaranteed to not return
1686 * null.
1688 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1691 * Get the channel that was passed to StartDocumentLoad or Reset for this
1692 * document. Note that this may be null in some cases (eg if
1693 * StartDocumentLoad or Reset were never called)
1695 nsIChannel* GetChannel() const { return mChannel; }
1698 * Get this document's attribute stylesheet. May return null if
1699 * there isn't one.
1701 AttributeStyles* GetAttributeStyles() const { return mAttributeStyles.get(); }
1703 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1706 * Get/set the object from which the context for the event/script handling can
1707 * be got. Normally GetScriptHandlingObject() returns the same object as
1708 * GetScriptGlobalObject(), but if the document is loaded as data,
1709 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1710 * aHasHadScriptHandlingObject is set true if document has had the object
1711 * for event/script handling. Do not process any events/script if the method
1712 * returns null, but aHasHadScriptHandlingObject is true.
1714 nsIScriptGlobalObject* GetScriptHandlingObject(
1715 bool& aHasHadScriptHandlingObject) const {
1716 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1717 return mScriptGlobalObject ? mScriptGlobalObject.get()
1718 : GetScriptHandlingObjectInternal();
1720 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1723 * Get the object that is used as the scope for all of the content
1724 * wrappers whose owner document is this document. Unlike the script global
1725 * object, this will only return null when the global object for this
1726 * document is truly gone. Use this object when you're trying to find a
1727 * content wrapper in XPConnect.
1729 nsIGlobalObject* GetScopeObject() const;
1730 void SetScopeObject(nsIGlobalObject* aGlobal);
1733 * Return the window containing the document (the outer window).
1735 nsPIDOMWindowOuter* GetWindow() const {
1736 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1739 bool IsInBackgroundWindow() const {
1740 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1741 return outer && outer->IsBackground();
1745 * Return the inner window used as the script compilation scope for
1746 * this document. If you're not absolutely sure you need this, use
1747 * GetWindow().
1749 nsPIDOMWindowInner* GetInnerWindow() const {
1750 return mRemovedFromDocShell ? nullptr : mWindow;
1754 * Return the outer window ID.
1756 uint64_t OuterWindowID() const {
1757 nsPIDOMWindowOuter* window = GetWindow();
1758 return window ? window->WindowID() : 0;
1762 * Return the inner window ID.
1764 uint64_t InnerWindowID() const {
1765 nsPIDOMWindowInner* window = GetInnerWindow();
1766 return window ? window->WindowID() : 0;
1770 * Return WindowGlobalChild that is associated with the inner window.
1772 WindowGlobalChild* GetWindowGlobalChild() {
1773 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1774 : nullptr;
1778 * Return WindowContext associated with the inner window.
1780 WindowContext* GetWindowContext() const {
1781 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1784 bool IsTopLevelWindowInactive() const {
1785 return mState.HasState(DocumentState::WINDOW_INACTIVE);
1789 * Get the script loader for this document
1791 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1794 * Add/Remove an element to the document's id and name hashes
1796 void AddToIdTable(Element* aElement, nsAtom* aId);
1797 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1798 void AddToNameTable(Element* aElement, nsAtom* aName);
1799 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1802 * Returns all elements in the top layer in the insertion order.
1804 nsTArray<Element*> GetTopLayer() const;
1806 bool TopLayerContains(Element&) const;
1808 // Do the "fullscreen element ready check" from the fullscreen spec.
1809 // It returns true if the given element is allowed to go into fullscreen.
1810 // It is responsive to dispatch "fullscreenerror" event when necessary.
1811 bool FullscreenElementReadyCheck(FullscreenRequest&);
1814 * When this is called on content process, this asynchronously requests that
1815 * the document make aElement the fullscreen element, and move into fullscreen
1816 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1817 * and it can be returned to fullscreen status by calling
1818 * RestorePreviousFullscreenState().
1819 * If on chrome process, this is synchronously.
1821 * Note that requesting fullscreen in a document also makes the element which
1822 * contains this document in this document's parent document fullscreen. i.e.
1823 * the <iframe> or <browser> that contains this document is also mode
1824 * fullscreen. This happens recursively in all ancestor documents.
1826 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1827 bool aApplyFullscreenDirectly = false);
1829 private:
1830 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1831 bool aApplyFullscreenDirectly);
1832 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1833 bool aApplyFullscreenDirectly);
1835 // Pushes aElement onto the top layer
1836 void TopLayerPush(Element&);
1838 // Removes the topmost element for which aPredicate returns true from the top
1839 // layer. The removed element, if any, is returned.
1840 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicate);
1842 // Removes the given element from the top layer. The removed element, if any,
1843 // is returned.
1844 Element* TopLayerPop(Element&);
1846 MOZ_CAN_RUN_SCRIPT bool TryAutoFocusCandidate(Element& aElement);
1848 public:
1849 // Removes all the elements with fullscreen flag set from the top layer, and
1850 // clears their fullscreen flag.
1851 void CleanupFullscreenState();
1853 // Pops the fullscreen element from the top layer and clears its
1854 // fullscreen flag. Returns whether there was any fullscreen element.
1855 enum class UpdateViewport : bool { No, Yes };
1856 bool PopFullscreenElement(UpdateViewport = UpdateViewport::Yes);
1858 // Pushes the given element into the top of top layer and set fullscreen
1859 // flag.
1860 void SetFullscreenElement(Element&);
1862 // Whether we has pending fullscreen request.
1863 bool HasPendingFullscreenRequests();
1866 * When Esc key is pressed, cancel the dialog element if the document is
1867 * blocked by the dialog or hide popover if popover is shown.
1869 MOZ_CAN_RUN_SCRIPT void HandleEscKey();
1871 void AddModalDialog(HTMLDialogElement&);
1872 void RemoveModalDialog(HTMLDialogElement&);
1875 * Called when a frame in a child process has entered fullscreen or when a
1876 * fullscreen frame in a child process changes to another origin.
1877 * aFrameElement is the frame element which contains the child-process
1878 * fullscreen document.
1880 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1883 * Called when a frame in a remote child document has rolled back fullscreen
1884 * so that all its top layer are empty; we must continue the
1885 * rollback in this parent process' doc tree branch which is fullscreen.
1886 * Note that only one branch of the document tree can have its documents in
1887 * fullscreen state at one time. We're in inconsistent state if a
1888 * fullscreen document has a parent and that parent isn't fullscreen. We
1889 * preserve this property across process boundaries.
1891 void RemoteFrameFullscreenReverted();
1894 * Restores the previous fullscreen element to fullscreen status. If there
1895 * is no former fullscreen element, this exits fullscreen, moving the
1896 * top-level browser window out of fullscreen mode.
1898 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1901 * Returns true if this document is a fullscreen leaf document, i.e. it
1902 * is in fullscreen mode and has no fullscreen children.
1904 bool IsFullscreenLeaf();
1907 * Returns the document which is at the root of this document's branch
1908 * in the in-process document tree. Returns nullptr if the document isn't
1909 * fullscreen.
1911 Document* GetFullscreenRoot() const { return mFullscreenRoot; }
1913 size_t CountFullscreenElements() const;
1916 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1917 * in this document.
1919 void SetFullscreenRoot(Document* aRoot) { mFullscreenRoot = aRoot; }
1922 * Synchronously cleans up the fullscreen state on the given document.
1924 * Calling this without performing fullscreen transition could lead
1925 * to undesired effect (the transition happens after document state
1926 * flips), hence it should only be called either by nsGlobalWindow
1927 * when we have performed the transition, or when it is necessary to
1928 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1929 * should be called instead.
1931 * aDocument must not be null.
1933 static void ExitFullscreenInDocTree(Document* aDocument);
1936 * Ask the document to exit fullscreen state asynchronously.
1938 * Different from ExitFullscreenInDocTree(), this allows the window
1939 * to perform fullscreen transition first if any.
1941 * If aDocument is null, it will exit fullscreen from all documents
1942 * in all windows.
1944 static void AsyncExitFullscreen(Document* aDocument);
1947 * Handles any pending fullscreen in aDocument or its subdocuments.
1949 * Returns whether there is any fullscreen request handled.
1951 static bool HandlePendingFullscreenRequests(Document* aDocument);
1954 * Clear pending fullscreen in aDocument.
1956 static void ClearPendingFullscreenRequests(Document* aDocument);
1958 // ScreenOrientation related APIs
1960 void ClearOrientationPendingPromise();
1961 bool SetOrientationPendingPromise(Promise* aPromise);
1962 Promise* GetOrientationPendingPromise() const {
1963 return mOrientationPendingPromise;
1966 //----------------------------------------------------------------------
1968 // Document notification API's
1971 * Add a new observer of document change notifications. Whenever
1972 * content is changed, appended, inserted or removed the observers are
1973 * informed. An observer that is already observing the document must
1974 * not be added without being removed first.
1976 void AddObserver(nsIDocumentObserver* aObserver);
1979 * Remove an observer of document change notifications. This will
1980 * return false if the observer cannot be found.
1982 bool RemoveObserver(nsIDocumentObserver* aObserver);
1984 // Observation hooks used to propagate notifications to document observers.
1985 // BeginUpdate must be called before any batch of modifications of the
1986 // content model or of style data, EndUpdate must be called afterward.
1987 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1988 void BeginUpdate();
1989 void EndUpdate();
1990 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
1992 void BeginLoad();
1993 virtual void EndLoad();
1995 enum ReadyState {
1996 READYSTATE_UNINITIALIZED = 0,
1997 READYSTATE_LOADING = 1,
1998 READYSTATE_INTERACTIVE = 3,
1999 READYSTATE_COMPLETE = 4
2001 // Set the readystate of the document. If aUpdateTimingInformation is true,
2002 // this will record relevant timestamps in the document's performance timing.
2003 // Some consumers (document.open is the only one right now, actually) don't
2004 // want to do that, though.
2005 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2006 ReadyState GetReadyStateEnum() { return mReadyState; }
2008 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2009 ReadyState aNewState);
2011 void NotifyAbortedLoad();
2013 // Notify that an element changed state. This must happen under a
2014 // scriptblocker but NOT within a begin/end update.
2015 void ElementStateChanged(Element*, ElementState);
2017 // Update a set of document states that may have changed.
2018 // This should only be called by callers whose state is also reflected in the
2019 // implementation of Document::State.
2021 // aNotify controls whether we notify our DocumentStatesChanged observers.
2022 void UpdateDocumentStates(DocumentState aMaybeChangedStates, bool aNotify);
2024 void ResetDocumentDirection();
2026 // Observation hooks for style data to propagate notifications
2027 // to document observers
2028 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2029 void RuleAdded(StyleSheet&, css::Rule&);
2030 void RuleRemoved(StyleSheet&, css::Rule&);
2031 void SheetCloned(StyleSheet&) {}
2032 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2035 * Flush notifications for this document and its parent documents
2036 * (since those may affect the layout of this one).
2038 void FlushPendingNotifications(FlushType aType);
2041 * Another variant of the above FlushPendingNotifications. This function
2042 * takes a ChangesToFlush to specify whether throttled animations are flushed
2043 * or not.
2044 * If in doubt, use the above FlushPendingNotifications.
2046 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2047 void FlushPendingNotifications(ChangesToFlush aFlush);
2050 * Calls FlushPendingNotifications on any external resources this document
2051 * has. If this document has no external resources or is an external resource
2052 * itself this does nothing. This should only be called with
2053 * aType >= FlushType::Style.
2055 void FlushExternalResources(FlushType aType);
2057 void AddWorkerDocumentListener(WorkerDocumentListener* aListener);
2058 void RemoveWorkerDocumentListener(WorkerDocumentListener* aListener);
2060 // Triggers an update of <svg:use> element shadow trees.
2061 void UpdateSVGUseElementShadowTrees() {
2062 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2063 return;
2065 DoUpdateSVGUseElementShadowTrees();
2069 * Only to be used inside Gecko, you can't really do anything with the
2070 * pointer outside Gecko anyway.
2072 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2075 * Reset the document using the given channel and loadgroup. This works
2076 * like ResetToURI, but also sets the document's channel to aChannel.
2077 * The principal of the document will be set from the channel.
2079 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2082 * Reset this document to aURI, aLoadGroup, aPrincipal and
2083 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2084 * content principal based on aURI will be used.
2086 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2087 nsIPrincipal* aPrincipal,
2088 nsIPrincipal* aPartitionedPrincipal);
2091 * Set the container (docshell) for this document. Virtual so that
2092 * docshell can call it.
2094 virtual void SetContainer(nsDocShell* aContainer);
2097 * Get the container (docshell) for this document.
2099 nsISupports* GetContainer() const;
2102 * Get the container's load context for this document.
2104 nsILoadContext* GetLoadContext() const;
2107 * Get docshell the for this document.
2109 nsIDocShell* GetDocShell() const;
2112 * Set and get XML declaration. If aVersion is null there is no declaration.
2113 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2114 * was no standalone parameter in the declaration, that it was given as no,
2115 * or that it was given as yes.
2117 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2118 const int32_t aStandalone);
2119 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2120 nsAString& Standalone);
2123 * Returns the bits for the color-scheme specified by the
2124 * <meta name="color-scheme">.
2126 uint8_t GetColorSchemeBits() const { return mColorSchemeBits; }
2129 * Traverses the DOM and computes the supported color schemes as per
2130 * https://html.spec.whatwg.org/#meta-color-scheme
2132 void RecomputeColorScheme();
2133 void AddColorSchemeMeta(HTMLMetaElement&);
2134 void RemoveColorSchemeMeta(HTMLMetaElement&);
2137 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2138 * regular HTML document with Content-Type "text/html", image documents and
2139 * media documents). Returns false for XHTML and any other documents parsed
2140 * by the XML parser.
2142 bool IsHTMLDocument() const { return mType == eHTML; }
2143 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2144 bool IsImageDocument() const {
2145 return MediaDocumentKind() == MediaDocumentKind::Image;
2147 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2148 bool IsSVGDocument() const { return mType == eSVG; }
2149 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2150 bool LoadsFullXULStyleSheetUpFront() {
2151 if (IsSVGDocument()) {
2152 return false;
2154 return AllowXULXBL();
2157 bool IsScriptEnabled() const;
2160 * Returns true if this document was created from a nsXULPrototypeDocument.
2162 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2164 * Returns the prototype the document was created from, or null if it was not
2165 * created from a prototype.
2167 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2169 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2170 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2171 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2174 bool IsContentDocument() const { return mIsContentDocument; }
2175 void SetIsContentDocument(bool aIsContentDocument) {
2176 mIsContentDocument = aIsContentDocument;
2179 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2181 * Create an element with the specified name, prefix and namespace ID.
2182 * Returns null if element name parsing failed.
2184 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2185 int32_t aNamespaceID,
2186 const nsAString* aIs = nullptr);
2189 * Get the security info (i.e. SSL state etc) that the document got
2190 * from the channel/document that created the content of the
2191 * document.
2193 * @see nsIChannel
2195 nsITransportSecurityInfo* GetSecurityInfo() { return mSecurityInfo; }
2198 * Get the channel that failed to load and resulted in an error page, if it
2199 * exists. This is only relevant to error pages.
2201 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2204 * This function checks if the document that is trying to access
2205 * GetNetErrorInfo is a trusted about net error page or not.
2207 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2210 * This function checks if the document that is trying to access
2211 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2213 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext* aCx,
2214 JSObject* aObject);
2217 * Get security info like error code for a failed channel. This
2218 * property is only exposed to about:neterror documents.
2220 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2223 * This function checks if the document that is trying to access
2224 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2226 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2229 * This function checks if the privilege storage access api is available for
2230 * the caller. We only allow privilege SSA to be called by system principal
2231 * and webcompat extension.
2233 static bool CallerCanAccessPrivilegeSSA(JSContext* aCx, JSObject* aObject);
2236 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2237 * failed Channel. This property is only exposed for about:certerror
2238 * documents.
2240 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2241 ErrorResult& aRv);
2244 * Set the channel that failed to load and resulted in an error page.
2245 * This is only relevant to error pages.
2247 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2250 * Returns the default namespace ID used for elements created in this
2251 * document.
2253 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2255 void RemoveAllProperties();
2256 void RemoveAllPropertiesFor(nsINode* aNode);
2258 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2261 * Sets the ID used to identify this part of the multipart document
2263 void SetPartID(uint32_t aID) { mPartID = aID; }
2266 * Return the ID used to identify this part of the multipart document
2268 uint32_t GetPartID() const { return mPartID; }
2271 * Sanitize the document by resetting all input elements and forms that have
2272 * autocomplete=off to their default values.
2273 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2275 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Sanitize();
2278 * Enumerate all subdocuments.
2279 * The enumerator callback should return CallState::Continue to continue
2280 * enumerating, or CallState::Stop to stop. This will never get passed a null
2281 * aDocument.
2283 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2284 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2287 * Collect all the descendant documents for which |aCalback| returns true.
2288 * The callback function must not mutate any state for the given document.
2290 using nsDocTestFunc = bool (*)(const Document* aDocument);
2291 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2292 nsDocTestFunc aCallback) const;
2295 * Check whether it is safe to cache the presentation of this document
2296 * and all of its subdocuments (depending on the 3rd param). This method
2297 * checks the following conditions recursively:
2298 * - Some document types, such as plugin documents, cannot be safely cached.
2299 * - If there are any pending requests, we don't allow the presentation
2300 * to be cached. Ideally these requests would be suspended and resumed,
2301 * but that is difficult in some cases, such as XMLHttpRequest.
2302 * - If there are any beforeunload or unload listeners, we must fire them
2303 * for correctness, but this likely puts the document into a state where
2304 * it would not function correctly if restored.
2306 * |aNewRequest| should be the request for a new document which will
2307 * replace this document in the docshell. The new document's request
2308 * will be ignored when checking for active requests. If there is no
2309 * request associated with the new document, this parameter may be null.
2311 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2312 * combination is when we try to BFCache aNewRequest
2314 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2315 uint32_t& aBFCacheCombo,
2316 bool aIncludeSubdocuments,
2317 bool aAllowUnloadListeners = true);
2320 * Pass principals if the correct ones are known when calling Init. That way
2321 * NodeInfoManager doesn't need to create a temporary null principal.
2323 virtual nsresult Init(nsIPrincipal* aPrincipal,
2324 nsIPrincipal* aPartitionedPrincipal);
2327 * Notify the document that its associated ContentViewer is being destroyed.
2328 * This releases circular references so that the document can go away.
2329 * Destroy() is only called on documents that have a content viewer.
2331 virtual void Destroy();
2334 * Notify the document that its associated ContentViewer is no longer
2335 * the current viewer for the docshell. The document might still
2336 * be rendered in "zombie state" until the next document is ready.
2337 * The document should save form control state.
2339 void RemovedFromDocShell();
2342 * Get the layout history state that should be used to save and restore state
2343 * for nodes in this document. This may return null; if that happens state
2344 * saving and restoration is not possible.
2346 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2349 * Methods that can be used to prevent onload firing while an event that
2350 * should block onload is posted. onload is guaranteed to not fire until
2351 * either all calls to BlockOnload() have been matched by calls to
2352 * UnblockOnload() or the load has been stopped altogether (by the user
2353 * pressing the Stop button, say).
2355 void BlockOnload();
2357 * @param aFireSync whether to fire onload synchronously. If false,
2358 * onload will fire asynchronously after all onload blocks have been
2359 * removed. It will NOT fire from inside UnblockOnload. If true,
2360 * onload may fire from inside UnblockOnload.
2362 void UnblockOnload(bool aFireSync);
2364 // Only BlockOnload should call this!
2365 void AsyncBlockOnload();
2367 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2369 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnblockDOMContentLoaded();
2372 * Notification that the page has been shown, for documents which are loaded
2373 * into a DOM window. This corresponds to the completion of document load,
2374 * or to the page's presentation being restored into an existing DOM window.
2375 * This notification fires applicable DOM events to the content window. See
2376 * PageTransitionEvent.webidl for a description of the |aPersisted|
2377 * parameter. If aDispatchStartTarget is null, the pageshow event is
2378 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2379 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2380 * event is only dispatched to listeners in the system group.
2381 * Note: if aDispatchStartTarget isn't null, the showing state of the
2382 * document won't be altered.
2384 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2385 bool aOnlySystemGroup = false);
2388 * Notification that the page has been hidden, for documents which are loaded
2389 * into a DOM window. This corresponds to the unloading of the document, or
2390 * to the document's presentation being saved but removed from an existing
2391 * DOM window. This notification fires applicable DOM events to the content
2392 * window. See PageTransitionEvent.webidl for a description of the
2393 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2394 * event is dispatched on the ScriptGlobalObject for this document,
2395 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2396 * true, the event is only dispatched to listeners in the system group.
2397 * Note: if aDispatchStartTarget isn't null, the showing state of the
2398 * document won't be altered.
2400 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2401 bool aOnlySystemGroup = false);
2404 * We record the set of links in the document that are relevant to
2405 * style.
2408 * Notification that an element is a link that is relevant to style.
2410 void AddStyleRelevantLink(Link* aLink) {
2411 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2412 #ifdef DEBUG
2413 NS_ASSERTION(!mStyledLinks.Contains(aLink),
2414 "Document already knows about this Link!");
2415 mStyledLinksCleared = false;
2416 #endif
2417 mStyledLinks.Insert(aLink);
2421 * Notification that an element is a link and its URI might have been
2422 * changed or the element removed. If the element is still a link relevant
2423 * to style, then someone must ensure that AddStyleRelevantLink is
2424 * (eventually) called on it again.
2426 void ForgetLink(Link* aLink) {
2427 MOZ_ASSERT(aLink, "Passing in a null link. Expect crashes RSN!");
2428 MOZ_ASSERT(mStyledLinks.Contains(aLink) || mStyledLinksCleared,
2429 "Document knows nothing about this Link!");
2430 mStyledLinks.Remove(aLink);
2433 // Refreshes the hrefs of all the links in the document.
2434 void RefreshLinkHrefs();
2437 * Support for window.matchMedia()
2440 already_AddRefed<MediaQueryList> MatchMedia(const nsACString& aMediaQueryList,
2441 CallerType aCallerType);
2443 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2445 nsTHashtable<LCPEntryHashEntry>& ContentIdentifiersForLCP() {
2446 return mContentIdentifiersForLCP;
2450 * Get the compatibility mode for this document
2452 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2455 * Check whether we've ever fired a DOMTitleChanged event for this
2456 * document.
2458 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2461 * To batch DOMSubtreeModified, document needs to be informed when
2462 * a mutation event might be dispatched, even if the event isn't actually
2463 * created because there are no listeners for it.
2465 * @param aTarget is the target for the mutation event.
2467 void MayDispatchMutationEvent(nsINode* aTarget) {
2468 if (mSubtreeModifiedDepth > 0) {
2469 mSubtreeModifiedTargets.AppendObject(aTarget);
2474 * Marks as not-going-to-be-collected for the given generation of
2475 * cycle collection.
2477 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2478 mMarkedCCGeneration = aGeneration;
2482 * Gets the cycle collector generation this document is marked for.
2484 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2487 * Returns whether this document is cookie averse. See
2488 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2490 bool IsCookieAverse() const {
2491 // If we are a document that "has no browsing context."
2492 if (!GetInnerWindow()) {
2493 return true;
2496 // If we are a document "whose URL's scheme is not a network scheme."
2497 // NB: Explicitly allow file: URIs to store cookies.
2499 return !NodePrincipal()->SchemeIs("http") &&
2500 !NodePrincipal()->SchemeIs("https") &&
2501 !NodePrincipal()->SchemeIs("file");
2504 bool IsLoadedAsData() { return mLoadedAsData; }
2506 void SetAddedToMemoryReportAsDataDocument() {
2507 mAddedToMemoryReportingAsDataDocument = true;
2510 void UnregisterFromMemoryReportingForDataDocument();
2512 bool MayStartLayout() { return mMayStartLayout; }
2514 void SetMayStartLayout(bool aMayStartLayout);
2516 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2518 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2520 // In case of failure, the document really can't initialize the frame loader.
2521 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2522 // In case of failure, the caller must handle the error, for example by
2523 // finalizing frame loader asynchronously.
2524 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2525 // Removes the frame loader of aShell from the initialization list.
2526 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2529 * Check whether this document is a root document that is not an
2530 * external resource.
2532 bool IsRootDisplayDocument() const {
2533 return !mParentDocument && !mDisplayDocument;
2536 bool ChromeRulesEnabled() const { return mChromeRulesEnabled; }
2538 bool IsInChromeDocShell() const {
2539 const Document* root = this;
2540 while (const Document* displayDoc = root->GetDisplayDocument()) {
2541 root = displayDoc;
2543 return root->mInChromeDocShell;
2546 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2548 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2550 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2552 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2554 bool IsResourceDoc() const {
2555 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2556 mHasDisplayDocument; // Are we an external resource doc?
2560 * Get the document for which this document is an external resource. This
2561 * will be null if this document is not an external resource. Otherwise,
2562 * GetDisplayDocument() will return a non-null document, and
2563 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2565 Document* GetDisplayDocument() const { return mDisplayDocument; }
2568 * Set the display document for this document. aDisplayDocument must not be
2569 * null.
2571 void SetDisplayDocument(Document* aDisplayDocument) {
2572 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2573 "Shouldn't set mDisplayDocument on documents that already "
2574 "have a presentation or a docshell or a window");
2575 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2576 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2577 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2578 "Display documents should not nest");
2579 mDisplayDocument = aDisplayDocument;
2580 mHasDisplayDocument = !!aDisplayDocument;
2584 * Request an external resource document for aURI. This will return the
2585 * resource document if available. If one is not available yet, it will
2586 * start loading as needed, and the pending load object will be returned in
2587 * aPendingLoad so that the caller can register an observer to wait for the
2588 * load. If this function returns null and doesn't return a pending load,
2589 * that means that there is no resource document for this URI and won't be
2590 * one in the future.
2592 * @param aURI the URI to get
2593 * @param aReferrerInfo the referrerInfo of the request
2594 * @param aRequestingNode the node making the request
2595 * @param aPendingLoad the pending load for this request, if any
2597 Document* RequestExternalResource(nsIURI* aURI,
2598 nsIReferrerInfo* aReferrerInfo,
2599 nsINode* aRequestingNode,
2600 ExternalResourceLoad** aPendingLoad);
2603 * Enumerate the external resource documents associated with this document.
2604 * The enumerator callback should return CallState::Continue to continue
2605 * enumerating, or CallState::Stop to stop. This callback will never get
2606 * passed a null aDocument.
2608 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2610 dom::ExternalResourceMap& ExternalResourceMap() {
2611 return mExternalResourceMap;
2615 * Return whether the document is currently showing (in the sense of
2616 * OnPageShow() having been called already and OnPageHide() not having been
2617 * called yet.
2619 bool IsShowing() const { return mIsShowing; }
2621 * Return whether the document is currently visible (in the sense of
2622 * OnPageHide having been called and OnPageShow not yet having been called)
2624 bool IsVisible() const { return mVisible; }
2626 void SetSuppressedEventListener(EventListener* aListener);
2628 EventListener* GetSuppressedEventListener() {
2629 return mSuppressedEventListener;
2633 * Return true when this document is active, i.e., an active document
2634 * in a content viewer and not in the bfcache.
2635 * This does NOT match the "active document" concept in the WHATWG spec -
2636 * see IsCurrentActiveDocument.
2638 bool IsActive() const;
2641 * Return true if this is the current active document for its
2642 * docshell. Note that a docshell may have multiple active documents
2643 * due to the bfcache -- this should be used when you need to
2644 * differentiate the *current* active document from any active
2645 * documents.
2647 bool IsCurrentActiveDocument() const {
2648 nsPIDOMWindowInner* inner = GetInnerWindow();
2649 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2653 * Returns whether this document should perform image loads.
2655 bool ShouldLoadImages() const {
2656 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2657 // images can themselves have data: URL image references.
2658 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2659 IsStaticDocument();
2662 void SetHasPrintCallbacks() {
2663 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2664 mHasPrintCallbacks = true;
2667 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2670 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2671 * the document's activity changes such as OnPageHide, visibility, activity.
2672 * The ActivityObserver objects can be nsIObjectLoadingContent or
2673 * nsIDocumentActivity or HTMLMEdiaElement.
2675 void RegisterActivityObserver(nsISupports* aSupports);
2676 bool UnregisterActivityObserver(nsISupports* aSupports);
2677 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2678 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2679 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2681 void NotifyActivityChanged();
2683 // Indicates whether mAnimationController has been (lazily) initialized.
2684 // If this returns true, we're promising that GetAnimationController()
2685 // will have a non-null return value.
2686 bool HasAnimationController() { return !!mAnimationController; }
2688 // Getter for this document's SMIL Animation Controller. Performs lazy
2689 // initialization, if this document supports animation and if
2690 // mAnimationController isn't yet initialized.
2692 // If HasAnimationController is true, this is guaranteed to return non-null.
2693 SMILAnimationController* GetAnimationController();
2695 // Gets the tracker for scroll-driven animations that are waiting to start.
2696 // Returns nullptr if there is no scroll-driven animation tracker for this
2697 // document which will be the case if there have never been any scroll-driven
2698 // animations in the document.
2699 ScrollTimelineAnimationTracker* GetScrollTimelineAnimationTracker() {
2700 return mScrollTimelineAnimationTracker;
2703 // Gets the tracker for scroll-driven animations that are waiting to start and
2704 // creates it if it doesn't already exist. As a result, the return value
2705 // will never be nullptr.
2706 ScrollTimelineAnimationTracker* GetOrCreateScrollTimelineAnimationTracker();
2709 * Prevents user initiated events from being dispatched to the document and
2710 * subdocuments.
2712 void SuppressEventHandling(uint32_t aIncrease = 1);
2715 * Unsuppress event handling.
2716 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2717 * asynchronously.
2719 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnsuppressEventHandlingAndFireEvents(
2720 bool aFireEvents);
2722 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2724 bool IsEventHandlingEnabled() const {
2725 return !EventHandlingSuppressed() && mScriptGlobalObject;
2728 bool WouldScheduleFrameRequestCallbacks() const {
2729 // If this function changes to depend on some other variable, make sure to
2730 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2731 // where that variable can change.
2732 return mPresShell && IsEventHandlingEnabled();
2735 void DecreaseEventSuppression() {
2736 MOZ_ASSERT(mEventsSuppressed);
2737 --mEventsSuppressed;
2738 UpdateFrameRequestCallbackSchedulingState();
2742 * Some clipboard commands are unconditionally enabled on some documents, so
2743 * as to always dispatch copy / paste events even though you'd normally not be
2744 * able to copy.
2746 bool AreClipboardCommandsUnconditionallyEnabled() const;
2749 * Note a ChannelEventQueue which has been suspended on the document's behalf
2750 * to prevent XHRs from running content scripts while event handling is
2751 * suppressed. The document is responsible for resuming the queue after
2752 * event handling is unsuppressed.
2754 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2757 * Returns true if a postMessage event should be suspended instead of running.
2758 * The document is responsible for running the event later, in the order they
2759 * were received.
2761 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2764 * Run any suspended postMessage events, or clear them.
2766 void FireOrClearPostMessageEvents(bool aFireEvents);
2768 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2771 * Flag whether we're about to fire the window's load event for this document.
2773 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2776 * Test whether we should be firing a load event for this document after a
2777 * document.close(). This is public and on Document, instead of being private
2778 * to Document, because we need to go through the normal docloader logic
2779 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2780 * semantics of firing the load event; we just don't want to fire the load
2781 * event if this tests true. So we need the docloader to be able to access
2782 * this state.
2784 * This method should only be called at the point when the load event is about
2785 * to be fired. It resets the "skip" flag, so it is not idempotent.
2787 bool SkipLoadEventAfterClose() {
2788 bool skip = mSkipLoadEventAfterClose;
2789 mSkipLoadEventAfterClose = false;
2790 return skip;
2794 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2796 void IncrementIgnoreDestructiveWritesCounter() {
2797 ++mIgnoreDestructiveWritesCounter;
2801 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2803 void DecrementIgnoreDestructiveWritesCounter() {
2804 --mIgnoreDestructiveWritesCounter;
2807 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2810 * Returns true if this document is allowed to contain XUL element and
2811 * use non-builtin XBL bindings.
2813 bool AllowXULXBL() {
2814 return mAllowXULXBL == eTriTrue ? true
2815 : mAllowXULXBL == eTriFalse ? false
2816 : InternalAllowXULXBL();
2820 * Returns true if this document is allowed to load DTDs from UI resources
2821 * no matter what.
2823 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2825 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2827 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2830 * Returns the template content owner document that owns the content of
2831 * HTMLTemplateElement.
2833 Document* GetTemplateContentsOwner();
2835 Document* GetTemplateContentsOwnerIfExists() const {
2836 return mTemplateContentsOwner.get();
2839 bool IsTemplateContentsOwner() const {
2840 // Template contents owner documents are the template contents owner of
2841 // themselves.
2842 return mTemplateContentsOwner == this;
2846 * Returns true if this document is a static clone of a normal document.
2848 * We create static clones for print preview and printing (possibly other
2849 * things in future).
2851 * Note that static documents are also "loaded as data" (if this method
2852 * returns true, IsLoadedAsData() will also return true).
2854 bool IsStaticDocument() const { return mIsStaticDocument; }
2857 * Clones the document along with any subdocuments, stylesheet, etc.
2859 * The resulting document and everything it contains (including any
2860 * sub-documents) are created purely via cloning. The returned documents and
2861 * any sub-documents are "loaded as data" documents to preserve the state as
2862 * it was during the clone process (we don't want external resources to load
2863 * and replace the cloned resources).
2865 * @param aCloneContainer The container for the clone document.
2866 * @param aDocumentViewer The viewer for the clone document. Must be the
2867 * viewer of aCloneContainer, but callers must have a
2868 * reference to it already and ensure it's not null.
2869 * @param aPrintSettings The print settings for this clone.
2870 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2872 already_AddRefed<Document> CreateStaticClone(
2873 nsIDocShell* aCloneContainer, nsIDocumentViewer* aDocumentViewer,
2874 nsIPrintSettings* aPrintSettings, bool* aOutHasInProcessPrintCallbacks);
2877 * If this document is a static clone, this returns the original
2878 * document.
2880 Document* GetOriginalDocument() const {
2881 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2882 return mOriginalDocument;
2886 * If this document is a static clone, let the original document know that
2887 * we're going away and then release our reference to it.
2889 void UnlinkOriginalDocumentIfStatic();
2892 * These are called by the parser as it encounters <picture> tags, the end of
2893 * said tags, and possible picture <source srcset> sources respectively. These
2894 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2895 * expected to be marked void.
2897 * NOTE that the parser does not attempt to track the current picture nesting
2898 * level or whether the given <source> tag is within a picture -- it is only
2899 * guaranteed to order these calls properly with respect to
2900 * ResolvePreLoadImage.
2903 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2905 void PreloadPictureClosed();
2907 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2908 const nsAString& aSizesAttr,
2909 const nsAString& aTypeAttr,
2910 const nsAString& aMediaAttr);
2913 * Called by the parser to resolve an image for preloading. The parser will
2914 * call the PreloadPicture* functions to inform us of possible <picture>
2915 * nesting and possible sources, which are used to inform URL selection
2916 * responsive <picture> or <img srcset> images. Unset attributes are expected
2917 * to be marked void.
2918 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2919 * true, false otherwise.
2921 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2922 const nsAString& aSrcAttr,
2923 const nsAString& aSrcsetAttr,
2924 const nsAString& aSizesAttr,
2925 bool* aIsImgSet);
2927 * Called by nsParser to preload images. Can be removed and code moved
2928 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2929 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2930 * be a void string if the attr is not present.
2931 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2932 * when this image is for loading <picture> or <img srcset> images.
2934 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2935 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2936 bool aLinkPreload, const nsAString& aFetchPriority);
2937 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2938 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2939 bool aLinkPreload, uint64_t aEarlyHintPreloaderId,
2940 const nsAString& aFetchPriority);
2943 * Called by images to forget an image preload when they start doing
2944 * the real load.
2946 void ForgetImagePreload(nsIURI* aURI);
2949 * Called by the parser or the preload service to preload style sheets.
2950 * aCrossOriginAttr should be a void string if the attr is not present.
2952 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2953 const nsAString& aCrossOriginAttr,
2954 ReferrerPolicyEnum aReferrerPolicy,
2955 const nsAString& aNonce,
2956 const nsAString& aIntegrity,
2957 css::StylePreloadKind,
2958 uint64_t aEarlyHintPreloaderId,
2959 const nsAString& aFetchPriority);
2962 * Called by the chrome registry to load style sheets.
2964 * This always does a synchronous load, and parses as a normal document sheet.
2966 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2969 * Returns true if the locale used for the document specifies a direction of
2970 * right to left. For chrome documents, this comes from the chrome registry.
2971 * This is used to determine the current state for the :-moz-locale-dir
2972 * pseudoclass so once can know whether a document is expected to be rendered
2973 * left-to-right or right-to-left.
2975 bool IsDocumentRightToLeft();
2978 * Called by Parser for link rel=preconnect
2980 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2983 * Set the document's pending state object (as serialized using structured
2984 * clone).
2986 void SetStateObject(nsIStructuredCloneContainer* scContainer);
2989 * Set the document's pending state object to the same state object as
2990 * aDocument.
2992 void SetStateObjectFrom(Document* aDocument) {
2993 SetStateObject(aDocument->mStateObjectContainer);
2996 // Whether we're a media document or not.
2997 enum class MediaDocumentKind {
2998 NotMedia,
2999 Video,
3000 Image,
3001 Plugin,
3004 virtual enum MediaDocumentKind MediaDocumentKind() const {
3005 return MediaDocumentKind::NotMedia;
3008 DocumentState State() const { return mState; }
3010 nsISupports* GetCurrentContentSink();
3012 void ElementWithAutoFocusInserted(Element* aAutoFocusCandidate);
3013 MOZ_CAN_RUN_SCRIPT void FlushAutoFocusCandidates();
3014 void ScheduleFlushAutoFocusCandidates();
3015 bool HasAutoFocusCandidates() const {
3016 return !mAutoFocusCandidates.IsEmpty();
3019 void SetAutoFocusFired();
3021 void SetScrollToRef(nsIURI* aDocumentURI);
3022 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3023 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3025 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3026 mChangeScrollPosWhenScrollingToRef = aValue;
3029 using DocumentOrShadowRoot::GetElementById;
3030 using DocumentOrShadowRoot::GetElementsByClassName;
3031 using DocumentOrShadowRoot::GetElementsByTagName;
3032 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3034 DocumentTimeline* Timeline();
3035 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3036 void UpdateHiddenByContentVisibilityForAnimations();
3038 SVGSVGElement* GetSVGRootElement() const;
3040 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3041 int32_t* aHandle);
3042 void CancelFrameRequestCallback(int32_t aHandle);
3045 * Returns true if the handle refers to a callback that was canceled that
3046 * we did not find in our list of callbacks (e.g. because it is one of those
3047 * in the set of callbacks currently queued to be run).
3049 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3052 * Put this document's frame request callbacks into the provided
3053 * list, and forget about them.
3055 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3058 * @return true if this document's frame request callbacks should be
3059 * throttled. We throttle requestAnimationFrame for documents which aren't
3060 * visible (e.g. scrolled out of the viewport).
3062 bool ShouldThrottleFrameRequests() const;
3064 // This returns true when the document tree is being teared down.
3065 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3067 dom::ImageTracker* ImageTracker();
3069 // Adds an element to mResponsiveContent when the element is
3070 // added to the tree.
3071 void AddResponsiveContent(HTMLImageElement* aContent) {
3072 MOZ_ASSERT(aContent);
3073 mResponsiveContent.Insert(aContent);
3076 // Removes an element from mResponsiveContent when the element is
3077 // removed from the tree.
3078 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3079 MOZ_ASSERT(aContent);
3080 mResponsiveContent.Remove(aContent);
3083 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3084 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3085 mSVGUseElementsNeedingShadowTreeUpdate.Remove(&aElement);
3088 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3089 return mSVGUseElementsNeedingShadowTreeUpdate.Contains(&aElement);
3092 using ShadowRootSet = nsTHashSet<ShadowRoot*>;
3094 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3095 mComposedShadowRoots.Insert(&aShadowRoot);
3098 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3099 mComposedShadowRoots.Remove(&aShadowRoot);
3102 // If you're considering using this, you probably want to use
3103 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3104 // sanity-checking.
3105 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3106 return mComposedShadowRoots.Contains(&aShadowRoot);
3109 const ShadowRootSet& ComposedShadowRoots() const {
3110 return mComposedShadowRoots;
3113 // WebIDL method for chrome code.
3114 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3116 // Notifies any responsive content added by AddResponsiveContent upon media
3117 // features values changing.
3118 void NotifyMediaFeatureValuesChanged();
3120 nsresult GetStateObject(JS::MutableHandle<JS::Value> aState);
3122 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3124 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3126 nsContentList* ImageMapList();
3128 // Add aLink to the set of links that need their status resolved.
3129 void RegisterPendingLinkUpdate(Link* aLink);
3131 // Update state on links in mLinksToUpdate.
3132 void FlushPendingLinkUpdates();
3134 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3135 void WarnOnceAbout(
3136 DeprecatedOperations aOperation, bool asError = false,
3137 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3139 #define DOCUMENT_WARNING(_op) e##_op,
3140 enum DocumentWarnings {
3141 #include "nsDocumentWarningList.h"
3142 eDocumentWarningCount
3144 #undef DOCUMENT_WARNING
3145 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3146 void WarnOnceAbout(
3147 DocumentWarnings aWarning, bool asError = false,
3148 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3150 // This method may fire a DOM event; if it does so it will happen
3151 // synchronously.
3153 // Whether the event fires is controlled by the argument.
3154 enum class DispatchVisibilityChange { No, Yes };
3155 void UpdateVisibilityState(
3156 DispatchVisibilityChange = DispatchVisibilityChange::Yes);
3158 // Posts an event to call UpdateVisibilityState.
3159 void PostVisibilityUpdateEvent();
3161 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3163 // Adds the size of a given node, which must not be a document node, to the
3164 // window sizes passed-in.
3165 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3167 // Note: Document is a sub-class of nsINode, which has a
3168 // SizeOfExcludingThis function. However, because Document objects can
3169 // only appear at the top of the DOM tree, we have a specialized measurement
3170 // function which returns multiple sizes.
3171 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3172 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3173 // because Document inherits from nsINode; see the comment above the
3174 // declaration of nsINode::SizeOfIncludingThis.
3175 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3177 void ConstructUbiNode(void* storage) override;
3179 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3181 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3183 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3185 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3187 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3189 void SetIsInSyncOperation(bool aSync);
3191 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3194 * Creates a new element in the HTML namespace with a local name given by
3195 * aTag.
3197 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3199 // WebIDL API
3200 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3201 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3202 ErrorResult& rv);
3203 DOMImplementation* GetImplementation(ErrorResult& rv);
3204 [[nodiscard]] nsresult GetURL(nsString& retval) const;
3205 [[nodiscard]] nsresult GetDocumentURI(nsString& retval) const;
3206 // Return the URI for the document.
3207 // The returned value may differ if the document is loaded via XHR, and
3208 // when accessed from chrome privileged script and
3209 // from content privileged script for compatibility.
3210 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3211 ErrorResult& aRv) const;
3212 void GetCompatMode(nsString& retval) const;
3213 void GetCharacterSet(nsAString& retval) const;
3214 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3215 // GetDoctype defined above
3216 Element* GetDocumentElement() const { return GetRootElement(); }
3218 WindowContext* GetTopLevelWindowContext() const;
3220 // If the top-level ancestor content document for this document is in the same
3221 // process, returns it. Otherwise, returns null. This function is not
3222 // Fission-compatible, and should not be used in new code.
3223 Document* GetTopLevelContentDocumentIfSameProcess();
3224 const Document* GetTopLevelContentDocumentIfSameProcess() const;
3226 // Returns the associated app window if this is a top-level chrome document,
3227 // null otherwise.
3228 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3230 already_AddRefed<Element> CreateElement(
3231 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3232 ErrorResult& rv);
3233 already_AddRefed<Element> CreateElementNS(
3234 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3235 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3236 already_AddRefed<Element> CreateXULElement(
3237 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3238 ErrorResult& aRv);
3239 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3240 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3241 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3242 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3243 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3244 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3245 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3246 ErrorResult& rv) const;
3247 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3248 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* AdoptNode(
3249 nsINode& aAdoptedNode, ErrorResult& rv, bool aAcceptShadowRoot = false);
3250 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3251 CallerType aCallerType,
3252 ErrorResult& rv) const;
3253 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3254 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3255 uint32_t aWhatToShow,
3256 NodeFilter* aFilter,
3257 ErrorResult& rv) const;
3258 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3259 uint32_t aWhatToShow,
3260 NodeFilter* aFilter,
3261 ErrorResult& rv) const;
3262 // Deprecated WebIDL bits
3263 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3264 ErrorResult& rv);
3265 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3266 ErrorResult& rv);
3267 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3268 const nsAString& aQualifiedName,
3269 ErrorResult& rv);
3270 void GetInputEncoding(nsAString& aInputEncoding) const;
3271 already_AddRefed<Location> GetLocation() const;
3272 void GetDomain(nsAString& aDomain);
3273 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3274 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3275 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3276 void GetReferrer(nsACString& aReferrer) const;
3277 void GetLastModified(nsAString& aLastModified) const;
3278 void GetReadyState(nsAString& aReadyState) const;
3280 void GetTitle(nsAString& aTitle);
3281 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3282 void GetDir(nsAString& aDirection) const;
3283 void SetDir(const nsAString& aDirection);
3284 nsIHTMLCollection* Images();
3285 nsIHTMLCollection* Embeds();
3286 nsIHTMLCollection* Plugins() { return Embeds(); }
3287 nsIHTMLCollection* Links();
3288 nsIHTMLCollection* Forms();
3289 nsIHTMLCollection* Scripts();
3290 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3291 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3292 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3294 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3295 const mozilla::dom::Optional<nsAString>& /* unused */,
3296 mozilla::ErrorResult& aError);
3297 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3298 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3299 mozilla::ErrorResult& rv);
3300 void Close(mozilla::ErrorResult& rv);
3301 void Write(const mozilla::dom::Sequence<nsString>& aText,
3302 mozilla::ErrorResult& rv);
3303 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3304 mozilla::ErrorResult& rv);
3305 Nullable<WindowProxyHolder> GetDefaultView() const;
3306 Element* GetActiveElement();
3307 enum class IncludeChromeOnly : bool { No, Yes };
3308 // TODO(emilio): Audit callers and remove the default argument, some seem like
3309 // they could want the IncludeChromeOnly::Yes version.
3310 nsIContent* GetUnretargetedFocusedContent(
3311 IncludeChromeOnly = IncludeChromeOnly::No) const;
3313 * Return true if this document or a subdocument has focus.
3315 bool HasFocus(ErrorResult& rv) const;
3318 * Return true if this document itself has focus.
3320 bool ThisDocumentHasFocus() const;
3322 void GetDesignMode(nsAString& aDesignMode);
3323 void SetDesignMode(const nsAString& aDesignMode,
3324 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3325 void SetDesignMode(const nsAString& aDesignMode,
3326 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3327 mozilla::ErrorResult& rv);
3328 MOZ_CAN_RUN_SCRIPT
3329 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3330 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3331 mozilla::ErrorResult& aRv);
3332 MOZ_CAN_RUN_SCRIPT bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3333 nsIPrincipal& aSubjectPrincipal,
3334 mozilla::ErrorResult& aRv);
3335 MOZ_CAN_RUN_SCRIPT bool QueryCommandIndeterm(
3336 const nsAString& aHTMLCommandName, mozilla::ErrorResult& aRv);
3337 MOZ_CAN_RUN_SCRIPT bool QueryCommandState(const nsAString& aHTMLCommandName,
3338 mozilla::ErrorResult& aRv);
3339 MOZ_CAN_RUN_SCRIPT bool QueryCommandSupported(
3340 const nsAString& aHTMLCommandName, mozilla::dom::CallerType aCallerType,
3341 mozilla::ErrorResult& aRv);
3342 MOZ_CAN_RUN_SCRIPT void QueryCommandValue(const nsAString& aHTMLCommandName,
3343 nsAString& aValue,
3344 mozilla::ErrorResult& aRv);
3345 nsIHTMLCollection* Applets();
3346 nsIHTMLCollection* Anchors();
3347 TimeStamp LastFocusTime() const;
3348 void SetLastFocusTime(const TimeStamp& aFocusTime);
3349 // Event handlers are all on nsINode already
3350 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3351 Element* GetCurrentScript();
3352 void ReleaseCapture() const;
3353 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3354 nsIURI* GetDocumentURIObject() const;
3355 // Not const because all the fullscreen goop is not const
3356 const char* GetFullscreenError(CallerType);
3357 bool FullscreenEnabled(CallerType aCallerType) {
3358 return !GetFullscreenError(aCallerType);
3361 void GetWireframeWithoutFlushing(bool aIncludeNodes, Nullable<Wireframe>&);
3363 MOZ_CAN_RUN_SCRIPT void GetWireframe(bool aIncludeNodes,
3364 Nullable<Wireframe>&);
3366 // Hides all popovers until the given end point, see
3367 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3368 MOZ_CAN_RUN_SCRIPT void HideAllPopoversUntil(nsINode& aEndpoint,
3369 bool aFocusPreviousElement,
3370 bool aFireEvents);
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 // Update intersection observers in this document and all
3713 // same-process subdocuments.
3714 void UpdateIntersections(TimeStamp aNowTime);
3715 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3717 DOMIntersectionObserver* GetLazyLoadObserver() { return mLazyLoadObserver; }
3718 DOMIntersectionObserver& EnsureLazyLoadObserver();
3720 bool HasElementsWithLastRememberedSize() const {
3721 return !mElementsObservedForLastRememberedSize.IsEmpty();
3723 void ObserveForLastRememberedSize(Element&);
3724 void UnobserveForLastRememberedSize(Element&);
3725 void UpdateLastRememberedSizes();
3727 // Dispatch a runnable related to the document.
3728 nsresult Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) const;
3730 // The URLs passed to this function should match what
3731 // JS::DescribeScriptedCaller() returns, since this API is used to
3732 // determine whether some code is being called from a tracking script.
3733 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3734 // The JSContext passed to this method represents the context that we want to
3735 // determine if it belongs to a tracker.
3736 bool IsScriptTracking(JSContext* aCx) const;
3738 // ResizeObserver usage.
3739 void AddResizeObserver(ResizeObserver&);
3740 void RemoveResizeObserver(ResizeObserver&);
3741 void ScheduleResizeObserversNotification() const;
3742 bool HasResizeObservers() const { return !mResizeObservers.IsEmpty(); }
3744 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3745 * All observations in each ResizeObserver with element's depth more than
3746 * aDepth will be gathered.
3748 void GatherAllActiveResizeObservations(uint32_t aDepth);
3750 * Calls BroadcastActiveObservations() for all ResizeObservers.
3751 * It also returns the shallowest depth of observed target elements with
3752 * active observations from all ResizeObservers or
3753 * numeric_limits<uint32_t>::max() if there aren't any active observations
3754 * at all.
3756 MOZ_CAN_RUN_SCRIPT uint32_t BroadcastAllActiveResizeObservations();
3758 * Returns whether there is any ResizeObserver that has active
3759 * observations.
3761 bool HasAnyActiveResizeObservations() const;
3763 * Returns whether there is any ResizeObserver that has skipped observations.
3765 bool HasAnySkippedResizeObservations() const;
3767 * Determine proximity to viewport for content-visibility: auto elements and
3768 * notify resize observers.
3770 MOZ_CAN_RUN_SCRIPT void
3771 DetermineProximityToViewportAndNotifyResizeObservers();
3773 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3774 PermissionDelegateHandler* GetPermissionDelegateHandler();
3776 // Notify the document that a fetch or a XHR request has completed
3777 // succesfully in this document. This is used by the password manager to infer
3778 // whether a form is submitted.
3779 void NotifyFetchOrXHRSuccess();
3781 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3782 void SetNotifyFetchSuccess(bool aShouldNotify);
3784 // When this is set, removing a form or a password field from DOM
3785 // sends a Chrome-only event. This is now only used by the password manager
3786 // and formautofill.
3787 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify);
3789 // This function is used by HTMLFormElement and HTMLInputElement to determin
3790 // whether to send an event when it is removed from DOM.
3791 bool ShouldNotifyFormOrPasswordRemoved() const {
3792 return mShouldNotifyFormOrPasswordRemoved;
3795 HTMLEditor* GetHTMLEditor() const;
3798 * Localization
3800 * For more information on DocumentL10n see
3801 * intl/l10n/docs/fluent/tutorial.rst
3804 public:
3806 * This is a public method exposed on Document WebIDL
3807 * to chrome only documents.
3809 DocumentL10n* GetL10n() const { return mDocumentL10n.get(); }
3812 * Whether there's any async l10n mutation work pending.
3814 * When this turns false, we fire the L10nMutationsFinished event.
3816 bool HasPendingL10nMutations() const;
3819 * This method should be called when the container
3820 * of l10n resources parsing is completed.
3822 * It triggers initial async fetch of the resources
3823 * as early as possible.
3825 * In HTML case this is </head>.
3826 * In XUL case this is </linkset>.
3828 void OnL10nResourceContainerParsed();
3831 * This method should be called when a link element
3832 * with rel="localization" is being added to the
3833 * l10n resource container element.
3835 void LocalizationLinkAdded(Element* aLinkElement);
3838 * This method should be called when a link element
3839 * with rel="localization" is being removed.
3841 void LocalizationLinkRemoved(Element* aLinkElement);
3844 * This method should be called as soon as the
3845 * parsing of the document is completed.
3847 * In HTML/XHTML this happens when we finish parsing
3848 * the document element.
3849 * In XUL it happens at `DoneWalking`, during
3850 * `MozBeforeInitialXULLayout`.
3852 void OnParsingCompleted();
3855 * This method is called when the initial translation
3856 * of the document is completed.
3858 * It unblocks the load event if translation was blocking it.
3860 * If the `aL10nCached` is set to `true`, and the document has
3861 * a prototype, it will set the `isL10nCached` flag on it.
3863 void InitialTranslationCompleted(bool aL10nCached);
3866 * Returns whether the document allows localization.
3868 bool AllowsL10n() const;
3870 void SetAllowDeclarativeShadowRoots(bool aAllowDeclarativeShadowRoots);
3871 bool AllowsDeclarativeShadowRoots() const;
3873 void SuspendDOMNotifications() {
3874 MOZ_ASSERT(IsHTMLDocument(),
3875 "Currently suspending DOM notifications is supported only on "
3876 "HTML documents.");
3877 mSuspendDOMNotifications = true;
3880 void ResumeDOMNotifications() { mSuspendDOMNotifications = false; }
3882 bool DOMNotificationsSuspended() const { return mSuspendDOMNotifications; }
3884 protected:
3885 RefPtr<DocumentL10n> mDocumentL10n;
3888 * Return true when you want a document without explicitly specified viewport
3889 * dimensions/scale to be treated as if "width=device-width" had in fact been
3890 * specified.
3892 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3894 private:
3895 bool IsErrorPage() const;
3897 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3898 // mUseCounters.
3899 void SetCssUseCounterBits();
3901 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3902 const nsAString& aHeightString,
3903 bool aIsAutoScale);
3905 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3906 // represents the scale property and returns the scale value if it's valid.
3907 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
3909 // Parse scale values in |aViewportMetaData| and set the values in
3910 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3911 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
3913 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3914 // stored in parent iframe or container's browsingContext (cross process)
3915 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
3917 public:
3918 const OriginTrials& Trials() const { return mTrials; }
3920 private:
3921 void DoCacheAllKnownLangPrefs();
3922 void RecomputeLanguageFromCharset();
3923 bool GetSHEntryHasUserInteraction();
3925 void AppendAutoFocusCandidateToTopDocument(Element* aAutoFocusCandidate);
3927 public:
3928 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
3930 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
3932 void SetSHEntryHasUserInteraction(bool aHasInteraction);
3934 nsAtom* GetContentLanguageAsAtomForStyle() const;
3935 nsAtom* GetLanguageForStyle() const;
3938 * Fetch the user's font preferences for the given aLanguage's
3939 * language group.
3941 const LangGroupFontPrefs* GetFontPrefsForLang(
3942 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
3944 void ForceCacheLang(nsAtom* aLanguage) {
3945 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
3946 return;
3948 GetFontPrefsForLang(aLanguage);
3951 void CacheAllKnownLangPrefs() {
3952 if (!mMayNeedFontPrefsUpdate) {
3953 return;
3955 DoCacheAllKnownLangPrefs();
3958 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
3960 uint32_t GetServoRestyleRootDirtyBits() const {
3961 MOZ_ASSERT(mServoRestyleRoot);
3962 MOZ_ASSERT(mServoRestyleRootDirtyBits);
3963 return mServoRestyleRootDirtyBits;
3966 void ClearServoRestyleRoot() {
3967 mServoRestyleRoot = nullptr;
3968 mServoRestyleRootDirtyBits = 0;
3971 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3972 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3974 bool ShouldThrowOnDynamicMarkupInsertion() {
3975 return mThrowOnDynamicMarkupInsertionCounter;
3978 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3979 ++mThrowOnDynamicMarkupInsertionCounter;
3982 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3983 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3984 --mThrowOnDynamicMarkupInsertionCounter;
3987 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
3989 void IncrementIgnoreOpensDuringUnloadCounter() {
3990 ++mIgnoreOpensDuringUnloadCounter;
3993 void DecrementIgnoreOpensDuringUnloadCounter() {
3994 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3995 --mIgnoreOpensDuringUnloadCounter;
3998 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
4001 * Find the (non-anonymous) content in this document for aFrame. It will
4002 * be aFrame's content node if that content is in this document and not
4003 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4004 * element containing the subdocument containing aFrame, and/or find the
4005 * nearest non-anonymous ancestor in this document.
4006 * Returns null if there is no such element.
4008 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
4010 void ReportShadowDOMUsage();
4012 // Sets flags for media telemetry.
4013 void SetDocTreeHadMedia();
4015 dom::XPathEvaluator* XPathEvaluator();
4017 void MaybeInitializeFinalizeFrameLoaders();
4019 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
4020 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
4023 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
4025 nsIPermissionDelegateHandler* PermDelegateHandler();
4027 // Returns whether this is a top-level about:blank page without an opener (and
4028 // thus likely not accessible by content). Likely because it shouldn't be used
4029 // for security checks for example, see bug 1860098.
4030 bool IsLikelyContentInaccessibleTopLevelAboutBlank() const;
4032 // CSS prefers-color-scheme media feature for this document.
4033 enum class IgnoreRFP { No, Yes };
4034 ColorScheme PreferredColorScheme(IgnoreRFP = IgnoreRFP::No) const;
4035 // Returns the initial color-scheme used for this document based on the
4036 // color-scheme meta tag.
4037 ColorScheme DefaultColorScheme() const;
4039 static bool HasRecentlyStartedForegroundLoads();
4041 static bool AutomaticStorageAccessPermissionCanBeGranted(
4042 nsIPrincipal* aPrincipal);
4044 already_AddRefed<Promise> AddCertException(bool aIsTemporary,
4045 ErrorResult& aError);
4047 void ReloadWithHttpsOnlyException();
4049 // Subframes need to be static cloned after the main document has been
4050 // embedded within a script global. A `PendingFrameStaticClone` is a static
4051 // clone which has not yet been performed.
4053 // The getter returns a direct reference to an internal array which is
4054 // manipulated from within printing code.
4055 struct PendingFrameStaticClone {
4056 PendingFrameStaticClone() = default;
4057 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
4058 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
4059 ~PendingFrameStaticClone();
4061 RefPtr<nsFrameLoaderOwner> mElement;
4062 RefPtr<nsFrameLoader> mStaticCloneOf;
4064 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
4065 nsFrameLoader* aStaticCloneOf);
4067 bool ShouldAvoidNativeTheme() const;
4069 static bool IsValidDomain(nsIURI* aOrigHost, nsIURI* aNewURI);
4071 // Inform a parent document that a BrowserBridgeChild has been created for
4072 // an OOP sub-document.
4073 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4074 void OOPChildLoadStarted(BrowserBridgeChild* aChild);
4076 // Inform a parent document that the BrowserBridgeChild for one of its
4077 // OOP sub-documents is done calling its onload handler.
4078 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4079 void OOPChildLoadDone(BrowserBridgeChild* aChild);
4081 void ClearOOPChildrenLoading();
4083 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading.IsEmpty(); }
4085 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache = true; }
4087 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache; }
4090 * Get the `HighlightRegistry` which contains all highlights associated
4091 * with this document.
4093 class HighlightRegistry& HighlightRegistry();
4096 * @brief Returns the `FragmentDirective` object which contains information
4097 * and functionality to extract or create text directives.
4098 * Guaranteed to be non-null.
4100 class FragmentDirective* FragmentDirective();
4102 bool ShouldResistFingerprinting(RFPTarget aTarget) const;
4103 bool IsInPrivateBrowsing() const;
4105 const Maybe<RFPTarget>& GetOverriddenFingerprintingSettings() const {
4106 return mOverriddenFingerprintingSettings;
4109 // Recompute the current resist fingerprinting state. Returns true when
4110 // the state was changed.
4111 bool RecomputeResistFingerprinting();
4113 void RecordCanvasUsage(CanvasUsage& aUsage);
4114 void RecordFontFingerprinting();
4116 bool MayHaveDOMActivateListeners() const;
4118 void DropStyleSet();
4120 protected:
4121 // Returns the WindowContext for the document that we will contribute
4122 // page use counters to.
4123 WindowContext* GetWindowContextForPageUseCounters() const;
4125 void DoUpdateSVGUseElementShadowTrees();
4127 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
4128 nsIPrincipal* aPrincipal);
4130 void EnsureOnloadBlocker();
4132 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
4134 // Returns true if the scheme for the url for this document is "about".
4135 bool IsAboutPage() const;
4137 bool ContainsEMEContent();
4138 bool ContainsMSEContent();
4141 * Returns the title element of the document as defined by the HTML
4142 * specification, or null if there isn't one. For documents whose root
4143 * element is an <svg:svg>, this is the first <svg:title> element that's a
4144 * child of the root. For other documents, it's the first HTML title element
4145 * in the document.
4147 Element* GetTitleElement();
4149 void RecordNavigationTiming(ReadyState aReadyState);
4151 // Recomputes the visibility state but doesn't set the new value.
4152 dom::VisibilityState ComputeVisibilityState() const;
4154 // Since we wouldn't automatically play media from non-visited page, we need
4155 // to notify window when the page was first visited.
4156 void MaybeActiveMediaComponents();
4158 // Apply the fullscreen state to the document, and trigger related
4159 // events. It returns false if the fullscreen element ready check
4160 // fails and nothing gets changed.
4161 MOZ_CAN_RUN_SCRIPT_BOUNDARY bool ApplyFullscreen(
4162 UniquePtr<FullscreenRequest>);
4164 void RemoveDocStyleSheetsFromStyleSets();
4165 void ResetStylesheetsToURI(nsIURI* aURI);
4166 void FillStyleSet();
4167 void FillStyleSetUserAndUASheets();
4168 void FillStyleSetDocumentSheets();
4169 void CompatibilityModeChanged();
4170 bool NeedsQuirksSheet() const {
4171 // SVG documents never load quirk.css.
4172 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4173 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
4175 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
4176 void RemoveContentEditableStyleSheets();
4177 void AddStyleSheetToStyleSets(StyleSheet&);
4178 void RemoveStyleSheetFromStyleSets(StyleSheet&);
4179 void NotifyStyleSheetApplicableStateChanged();
4180 // Just like EnableStyleSheetsForSet, but doesn't check whether
4181 // aSheetSet is null and allows the caller to control whether to set
4182 // aSheetSet as the preferred set in the CSSLoader.
4183 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
4184 bool aUpdateCSSLoader);
4186 already_AddRefed<nsIURI> GetDomainURI();
4187 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4188 const nsACString& aHostString);
4189 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4190 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4192 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4193 mozilla::ErrorResult& aRv);
4194 // A version of WriteCommon used by WebIDL bindings
4195 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4196 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4198 void* GenerateParserKey(void);
4200 private:
4201 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4202 // parameter.
4203 enum class ExecCommandParam : uint8_t {
4204 // Always ignore it.
4205 Ignore,
4206 // Treat the given parameter as-is. If the command requires it, use it.
4207 // Otherwise, ignore it.
4208 String,
4209 // Always treat it as boolean parameter.
4210 Boolean,
4211 // Always treat it as boolean, but inverted.
4212 InvertedBoolean,
4215 using GetEditorCommandFunc = mozilla::EditorCommand*();
4217 struct InternalCommandData {
4218 const char* mXULCommandName;
4219 mozilla::Command mCommand; // uint8_t
4220 // How ConvertToInternalCommand() to treats aValue.
4221 // Its callers don't need to check this.
4222 ExecCommandParam mExecCommandParam; // uint8_t
4223 GetEditorCommandFunc* mGetEditorCommandFunc;
4224 enum class CommandOnTextEditor : uint8_t {
4225 Disabled,
4226 Enabled,
4227 FallThrough, // Not disabled, but handled by HTMLEditor if there is one
4229 CommandOnTextEditor mCommandOnTextEditor;
4231 InternalCommandData()
4232 : mXULCommandName(nullptr),
4233 mCommand(mozilla::Command::DoNothing),
4234 mExecCommandParam(ExecCommandParam::Ignore),
4235 mGetEditorCommandFunc(nullptr),
4236 mCommandOnTextEditor(CommandOnTextEditor::Disabled) {}
4237 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4238 ExecCommandParam aExecCommandParam,
4239 GetEditorCommandFunc aGetEditorCommandFunc,
4240 CommandOnTextEditor aCommandOnTextEditor)
4241 : mXULCommandName(aXULCommandName),
4242 mCommand(aCommand),
4243 mExecCommandParam(aExecCommandParam),
4244 mGetEditorCommandFunc(aGetEditorCommandFunc),
4245 mCommandOnTextEditor(aCommandOnTextEditor) {}
4247 bool IsAvailableOnlyWhenEditable() const {
4248 return mCommand != mozilla::Command::Cut &&
4249 mCommand != mozilla::Command::Copy &&
4250 mCommand != mozilla::Command::Paste &&
4251 mCommand != mozilla::Command::SetDocumentReadOnly &&
4252 mCommand != mozilla::Command::SelectAll;
4254 bool IsCutOrCopyCommand() const {
4255 return mCommand == mozilla::Command::Cut ||
4256 mCommand == mozilla::Command::Copy;
4258 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4262 * AutoEditorCommandTarget considers which editor or global command manager
4263 * handles given command.
4265 class MOZ_RAII AutoEditorCommandTarget {
4266 public:
4267 MOZ_CAN_RUN_SCRIPT AutoEditorCommandTarget(
4268 Document& aDocument, const InternalCommandData& aCommandData);
4269 AutoEditorCommandTarget() = delete;
4270 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget& aOther) =
4271 delete;
4273 bool DoNothing() const { return mDoNothing; }
4274 MOZ_CAN_RUN_SCRIPT bool IsEditable(Document* aDocument) const;
4275 bool IsEditor() const {
4276 MOZ_ASSERT_IF(mEditorCommand, mActiveEditor || mHTMLEditor);
4277 return !!mEditorCommand;
4280 MOZ_CAN_RUN_SCRIPT bool IsCommandEnabled() const;
4281 MOZ_CAN_RUN_SCRIPT nsresult DoCommand(nsIPrincipal* aPrincipal) const;
4282 template <typename ParamType>
4283 MOZ_CAN_RUN_SCRIPT nsresult DoCommandParam(const ParamType& aParam,
4284 nsIPrincipal* aPrincipal) const;
4285 MOZ_CAN_RUN_SCRIPT nsresult
4286 GetCommandStateParams(nsCommandParams& aParams) const;
4288 private:
4289 // The returned editor's life is guaranteed while this instance is alive.
4290 EditorBase* GetTargetEditor() const;
4292 RefPtr<EditorBase> mActiveEditor;
4293 RefPtr<HTMLEditor> mHTMLEditor;
4294 RefPtr<EditorCommand> mEditorCommand;
4295 const InternalCommandData& mCommandData;
4296 bool mDoNothing = false;
4300 * Helper method to initialize sInternalCommandDataHashtable.
4302 static void EnsureInitializeInternalCommandDataHashtable();
4305 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4306 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4307 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4308 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4309 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4310 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4311 * returns a copy of instance created with default constructor. I.e., its
4312 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4313 * is unsupported in such case.
4315 * @param aHTMLCommandName Command name in HTML, e.g., used by
4316 * execCommand().
4317 * @param aValue The value which is set to the 3rd parameter
4318 * of execCommand().
4319 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4320 * Will be set to adjusted value for executing
4321 * the internal command.
4322 * @return Returns a copy of instance created with the
4323 * default constructor if there is no
4324 * corresponding internal command for
4325 * aHTMLCommandName or aValue is invalid for
4326 * found internal command when aAdjustedValue
4327 * is not nullptr. Otherwise, returns a copy of
4328 * instance registered in
4329 * sInternalCommandDataHashtable.
4331 static InternalCommandData ConvertToInternalCommand(
4332 const nsAString& aHTMLCommandName, const nsAString& aValue = u""_ns,
4333 nsAString* aAdjustedValue = nullptr);
4336 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4337 * Since it's a bit field, not a bool member, therefore, we cannot use
4338 * AutoRestorer for it.
4340 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4341 public:
4342 AutoRunningExecCommandMarker() = delete;
4343 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4344 delete;
4345 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4346 MOZ_CAN_RUN_SCRIPT AutoRunningExecCommandMarker(Document& aDocument,
4347 nsIPrincipal* aPrincipal);
4348 ~AutoRunningExecCommandMarker() {
4349 if (mTreatAsUserInput) {
4350 mDocument.mIsRunningExecCommandByChromeOrAddon =
4351 mHasBeenRunningByChromeOrAddon;
4352 } else {
4353 mDocument.mIsRunningExecCommandByContent = mHasBeenRunningByContent;
4357 [[nodiscard]] bool IsSafeToRun() const {
4358 // We don't allow nested calls of execCommand even if the caller is chrome
4359 // script.
4360 if (mTreatAsUserInput) {
4361 return !mHasBeenRunningByChromeOrAddon && !mHasBeenRunningByContent;
4363 // If current call is by content, we should ignore whether nested with a
4364 // call by addon (or chrome script) because the caller wants to emulate
4365 // user input for making it undoable. So, we should treat the first
4366 // call as user input.
4367 return !mHasBeenRunningByContent;
4370 private:
4371 Document& mDocument;
4372 bool mTreatAsUserInput;
4373 bool mHasBeenRunningByContent;
4374 bool mHasBeenRunningByChromeOrAddon;
4377 // Mapping table from HTML command name to internal command.
4378 using InternalCommandDataHashtable =
4379 nsTHashMap<nsStringCaseInsensitiveHashKey, InternalCommandData>;
4380 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4382 mutable std::bitset<static_cast<size_t>(
4383 DeprecatedOperations::eDeprecatedOperationCount)>
4384 mDeprecationWarnedAbout;
4385 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4387 // Lazy-initialization to have mDocGroup initialized in prior to the
4388 UniquePtr<ServoStyleSet> mStyleSet;
4390 protected:
4391 // Never ever call this. Only call GetWindow!
4392 nsPIDOMWindowOuter* GetWindowInternal() const;
4394 // Never ever call this. Only call GetScriptHandlingObject!
4395 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4397 // Never ever call this. Only call AllowXULXBL!
4398 bool InternalAllowXULXBL();
4401 * These methods should be called before and after dispatching
4402 * a mutation event.
4403 * To make this easy and painless, use the mozAutoSubtreeModified helper
4404 * class.
4406 void WillDispatchMutationEvent(nsINode* aTarget);
4407 void MutationEventDispatched(nsINode* aTarget);
4408 friend class mozAutoSubtreeModified;
4410 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4412 nsCString GetContentTypeInternal() const { return mContentType; }
4414 // Update our frame request callback scheduling state, if needed. This will
4415 // schedule or unschedule them, if necessary, and update
4416 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4417 // mPresShell is becoming null; in that case it will be used to get hold of
4418 // the relevant refresh driver.
4419 void UpdateFrameRequestCallbackSchedulingState(
4420 PresShell* aOldPresShell = nullptr);
4422 // Helper for GetScrollingElement/IsScrollingElement.
4423 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4425 void MaybeAllowStorageForOpenerAfterUserInteraction();
4427 void MaybeStoreUserInteractionAsPermission();
4429 // Helpers for GetElementsByName.
4430 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4431 nsAtom* aAtom, void* aData);
4432 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4434 void MaybeResolveReadyForIdle();
4436 using AutomaticStorageAccessPermissionGrantPromise =
4437 MozPromise<bool, bool, true>;
4438 [[nodiscard]] RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4439 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation);
4441 static void AddToplevelLoadingDocument(Document* aDoc);
4442 static void RemoveToplevelLoadingDocument(Document* aDoc);
4443 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4444 friend class cycleCollection;
4446 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4447 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4449 nsString mLastModified;
4451 nsCOMPtr<nsIURI> mDocumentURI;
4452 nsCOMPtr<nsIURI> mOriginalURI;
4453 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4454 nsCOMPtr<nsIURI> mDocumentBaseURI;
4455 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4457 // The base domain of the document for third-party checks.
4458 nsCString mBaseDomain;
4460 // A lazily-constructed URL data for style system to resolve URL values.
4461 RefPtr<URLExtraData> mCachedURLData;
4462 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfoForInternalCSSAndSVGResources;
4464 nsWeakPtr mDocumentLoadGroup;
4466 WeakPtr<nsDocShell> mDocumentContainer;
4468 NotNull<const Encoding*> mCharacterSet;
4469 int32_t mCharacterSetSource;
4471 OriginTrials mTrials;
4473 // This is just a weak pointer; the parent document owns its children.
4474 Document* mParentDocument;
4476 // A reference to the element last returned from GetRootElement().
4477 Element* mCachedRootElement;
4479 // This is maintained by AutoSetRestoreSVGContextPaint.
4480 const SVGContextPaint* mCurrentContextPaint = nullptr;
4482 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4483 // which in turn holds a strong reference to this mNodeInfoManager.
4484 nsNodeInfoManager* mNodeInfoManager;
4485 RefPtr<css::Loader> mCSSLoader;
4486 RefPtr<css::ImageLoader> mStyleImageLoader;
4488 // The object that contains link color declarations (from the <body> mapped
4489 // attributes), mapped attribute caches, and inline style attribute caches.
4490 RefPtr<AttributeStyles> mAttributeStyles;
4492 // Tracking for images in the document.
4493 RefPtr<dom::ImageTracker> mImageTracker;
4495 // A hashtable of ShadowRoots belonging to the composed doc.
4497 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4498 ShadowRootSet mComposedShadowRoots;
4500 using SVGUseElementSet = nsTHashSet<SVGUseElement*>;
4502 // The set of <svg:use> elements that need a shadow tree reclone because the
4503 // tree they map to has changed.
4504 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4506 // The set of all object, embed, video/audio elements or
4507 // nsIObjectLoadingContent or DocumentActivity for which this is
4508 // the owner document. (They might not be in the document.)
4510 // These are non-owning pointers, the elements are responsible for removing
4511 // themselves when they go away.
4512 UniquePtr<nsTHashSet<nsISupports*>> mActivityObservers;
4514 // A hashtable of styled links keyed by address pointer.
4515 nsTHashSet<Link*> mStyledLinks;
4516 #ifdef DEBUG
4517 // Indicates whether mStyledLinks was cleared or not. This is used to track
4518 // state so we can provide useful assertions to consumers of ForgetLink and
4519 // AddStyleRelevantLink.
4520 bool mStyledLinksCleared;
4521 #endif
4523 // The array of all links that need their status resolved. Links must add
4524 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4525 // document.
4526 static const size_t kSegmentSize = 128;
4528 using LinksToUpdateList =
4529 SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>;
4531 LinksToUpdateList mLinksToUpdate;
4533 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4534 RefPtr<SMILAnimationController> mAnimationController;
4536 // Table of element properties for this document.
4537 nsPropertyTable mPropertyTable;
4539 // Our cached .children collection
4540 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4542 // Various DOM lists
4543 RefPtr<nsContentList> mImages;
4544 RefPtr<nsContentList> mEmbeds;
4545 RefPtr<nsContentList> mLinks;
4546 RefPtr<nsContentList> mForms;
4547 RefPtr<nsContentList> mScripts;
4548 nsCOMPtr<nsIHTMLCollection> mApplets;
4549 RefPtr<nsContentList> mAnchors;
4551 // container for per-context fonts (downloadable, SVG, etc.)
4552 RefPtr<FontFaceSet> mFontFaceSet;
4554 // Last time this document or a one of its sub-documents was focused. If
4555 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4556 TimeStamp mLastFocusTime;
4558 // Last time we found any scroll linked effect in this document.
4559 TimeStamp mLastScrollLinkedEffectDetectionTime;
4561 DocumentState mState{DocumentState::LTR_LOCALE};
4563 RefPtr<Promise> mReadyForIdle;
4565 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4567 // Permission Delegate Handler, lazily-initialized in
4568 // GetPermissionDelegateHandler
4569 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4571 bool mCachedStateObjectValid : 1;
4572 bool mBlockAllMixedContent : 1;
4573 bool mBlockAllMixedContentPreloads : 1;
4574 bool mUpgradeInsecureRequests : 1;
4575 bool mUpgradeInsecurePreloads : 1;
4576 bool mDevToolsWatchingDOMMutations : 1;
4578 // True if BIDI is enabled.
4579 bool mBidiEnabled : 1;
4580 // True if we may need to recompute the language prefs for this document.
4581 bool mMayNeedFontPrefsUpdate : 1;
4582 // True if a MathML element has ever been owned by this document.
4583 bool mMathMLEnabled : 1;
4585 // True if this document is the initial document for a window. This should
4586 // basically be true only for documents that exist in newly-opened windows or
4587 // documents created to satisfy a GetDocument() on a window when there's no
4588 // document in it.
4589 bool mIsInitialDocumentInWindow : 1;
4591 // True if this document has ever been the initial document for a window. This
4592 // is useful to determine if a document that was the initial document at one
4593 // point, and became non-initial later.
4594 bool mIsEverInitialDocumentInWindow : 1;
4596 bool mIgnoreDocGroupMismatches : 1;
4598 // True if we're loaded as data and therefor has any dangerous stuff, such
4599 // as scripts and plugins, disabled.
4600 bool mLoadedAsData : 1;
4602 // True if the document is considered for memory reporting as a
4603 // data document
4604 bool mAddedToMemoryReportingAsDataDocument : 1;
4606 // If true, whoever is creating the document has gotten it to the
4607 // point where it's safe to start layout on it.
4608 bool mMayStartLayout : 1;
4610 // True iff we've ever fired a DOMTitleChanged event for this document
4611 bool mHaveFiredTitleChange : 1;
4613 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4614 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4615 // before the initial load completes and when we're in bfcache or unloaded,
4616 // true otherwise.
4617 bool mIsShowing : 1;
4619 // State for IsVisible(). mVisible starts off true. It becomes false when
4620 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4621 // it's false only when we're in bfcache or unloaded.
4622 bool mVisible : 1;
4624 // True if our content viewer has been removed from the docshell
4625 // (it may still be displayed, but in zombie state). Form control data
4626 // has been saved.
4627 bool mRemovedFromDocShell : 1;
4629 // True iff DNS prefetch is allowed for this document. Note that if the
4630 // document has no window, DNS prefetch won't be performed no matter what.
4631 bool mAllowDNSPrefetch : 1;
4633 // True when this document is a static clone of a normal document
4634 bool mIsStaticDocument : 1;
4636 // True while this document is being cloned to a static document.
4637 bool mCreatingStaticClone : 1;
4639 // True if this static document has any <canvas> element with a
4640 // mozPrintCallback property at the time of the clone.
4641 bool mHasPrintCallbacks : 1;
4643 // True iff the document is being unlinked or deleted.
4644 bool mInUnlinkOrDeletion : 1;
4646 // True if document has ever had script handling object.
4647 bool mHasHadScriptHandlingObject : 1;
4649 // True if we're an SVG document being used as an image.
4650 bool mIsBeingUsedAsImage : 1;
4652 // True if our current document URI's scheme enables privileged CSS rules.
4653 bool mChromeRulesEnabled : 1;
4655 // True if we're loaded in a chrome docshell.
4656 bool mInChromeDocShell : 1;
4658 // True is this document is synthetic : stand alone image, video, audio
4659 // file, etc.
4660 bool mIsSyntheticDocument : 1;
4662 // True is there is a pending runnable which will call
4663 // FlushPendingLinkUpdates().
4664 bool mHasLinksToUpdateRunnable : 1;
4666 // True if we're flushing pending link updates.
4667 bool mFlushingPendingLinkUpdates : 1;
4669 // True if a DOMMutationObserver is perhaps attached to a node in the
4670 // document.
4671 bool mMayHaveDOMMutationObservers : 1;
4673 // True if an nsIAnimationObserver is perhaps attached to a node in the
4674 // document.
4675 bool mMayHaveAnimationObservers : 1;
4677 // True if the document has a CSP delivered throuh a header
4678 bool mHasCSPDeliveredThroughHeader : 1;
4680 // True if DisallowBFCaching has been called on this document.
4681 bool mBFCacheDisallowed : 1;
4683 bool mHasHadDefaultView : 1;
4685 // Whether style sheet change events will be dispatched for this document
4686 bool mStyleSheetChangeEventsEnabled : 1;
4688 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4689 // will be dispatched for this document.
4690 bool mDevToolsAnonymousAndShadowEventsEnabled : 1;
4692 // Whether the document was created by a srcdoc iframe.
4693 bool mIsSrcdocDocument : 1;
4695 // Whether this document has a display document and thus is considered to
4696 // be a resource document. Normally this is the same as !!mDisplayDocument,
4697 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4698 // valid in the document's destructor.
4699 bool mHasDisplayDocument : 1;
4701 // Is the current mFontFaceSet valid?
4702 bool mFontFaceSetDirty : 1;
4704 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4705 // (e.g. we're not being parsed at all).
4706 bool mDidFireDOMContentLoaded : 1;
4708 // True if we have frame request callbacks scheduled with the refresh driver.
4709 // This should generally be updated only via
4710 // UpdateFrameRequestCallbackSchedulingState.
4711 bool mFrameRequestCallbacksScheduled : 1;
4713 bool mIsTopLevelContentDocument : 1;
4715 bool mIsContentDocument : 1;
4717 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4718 bool mDidCallBeginLoad : 1;
4720 // True if the encoding menu should be disabled.
4721 bool mEncodingMenuDisabled : 1;
4723 // False if we've disabled link handling for elements inside this document,
4724 // true otherwise.
4725 bool mLinksEnabled : 1;
4727 // True if this document is for an SVG-in-OpenType font.
4728 bool mIsSVGGlyphsDocument : 1;
4730 // True if the document is being destroyed.
4731 bool mInDestructor : 1;
4733 // True if the document has been detached from its content viewer.
4734 bool mIsGoingAway : 1;
4736 // Whether we have filled our style set with all the stylesheets.
4737 bool mStyleSetFilled : 1;
4739 // Whether we have a quirks mode stylesheet in the style set.
4740 bool mQuirkSheetAdded : 1;
4742 // Whether we have a contenteditable.css stylesheet in the style set.
4743 bool mContentEditableSheetAdded : 1;
4745 // Whether we have a designmode.css stylesheet in the style set.
4746 bool mDesignModeSheetAdded : 1;
4748 // True if this document has ever had an HTML or SVG <title> element
4749 // bound to it
4750 bool mMayHaveTitleElement : 1;
4752 bool mDOMLoadingSet : 1;
4753 bool mDOMInteractiveSet : 1;
4754 bool mDOMCompleteSet : 1;
4755 bool mAutoFocusFired : 1;
4757 bool mScrolledToRefAlready : 1;
4758 bool mChangeScrollPosWhenScrollingToRef : 1;
4760 bool mDelayFrameLoaderInitialization : 1;
4762 bool mSynchronousDOMContentLoaded : 1;
4764 // Set to true when the document is possibly controlled by the ServiceWorker.
4765 // Used to prevent multiple requests to ServiceWorkerManager.
4766 bool mMaybeServiceWorkerControlled : 1;
4768 // These member variables cache information about the viewport so we don't
4769 // have to recalculate it each time.
4770 bool mAllowZoom : 1;
4771 bool mValidScaleFloat : 1;
4772 bool mValidMinScale : 1;
4773 bool mValidMaxScale : 1;
4774 bool mWidthStrEmpty : 1;
4776 // Parser aborted. True if the parser of this document was forcibly
4777 // terminated instead of letting it finish at its own pace.
4778 bool mParserAborted : 1;
4780 // Whether we have reported document use counters for this document with
4781 // Telemetry yet. Normally this is only done at document destruction time,
4782 // but for image documents (SVG documents) that are not guaranteed to be
4783 // destroyed, we report use counters when the image cache no longer has any
4784 // imgRequestProxys pointing to them. We track whether we ever reported use
4785 // counters so that we only report them once for the document.
4786 bool mReportedDocumentUseCounters : 1;
4788 bool mHasReportedShadowDOMUsage : 1;
4790 // Whether an event triggered by the refresh driver was delayed because this
4791 // document has suppressed events.
4792 bool mHasDelayedRefreshEvent : 1;
4794 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4795 // to have the right semantics. See
4796 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4797 // flag that is set while the window's 'load' event is firing if this document
4798 // is the window's document.
4799 bool mLoadEventFiring : 1;
4801 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4802 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4803 // What we have instead is a flag that is set if completion of our document
4804 // via document.close() should skip firing the load event. Note that this
4805 // flag is only relevant for HTML documents, but lives here for reasons that
4806 // are documented above on SkipLoadEventAfterClose().
4807 bool mSkipLoadEventAfterClose : 1;
4809 // When false, the .cookies property is completely disabled
4810 bool mDisableCookieAccess : 1;
4812 // When false, the document.write() API is disabled.
4813 bool mDisableDocWrite : 1;
4815 // Has document.write() been called with a recursion depth higher than
4816 // allowed?
4817 bool mTooDeepWriteRecursion : 1;
4820 * Temporary flag that is set in EndUpdate() to ignore
4821 * MaybeEditingStateChanged() script runners from a nested scope.
4823 bool mPendingMaybeEditingStateChanged : 1;
4825 // mHasBeenEditable is set to true when mEditingState is firstly set to
4826 // eDesignMode or eContentEditable.
4827 bool mHasBeenEditable : 1;
4829 // Whether we've warned about the CSS zoom property.
4831 // We don't use the general deprecated operation mechanism for this because we
4832 // also record this as a `CountedUnknownProperty`.
4833 bool mHasWarnedAboutZoom : 1;
4835 // While we're handling an execCommand call by web app, set
4836 // to true.
4837 bool mIsRunningExecCommandByContent : 1;
4838 // While we're handling an execCommand call by an addon (or chrome script),
4839 // set to true.
4840 bool mIsRunningExecCommandByChromeOrAddon : 1;
4842 // True if we should change the readystate to complete after we fire
4843 // DOMContentLoaded. This happens when we abort a load and
4844 // nsDocumentViewer::EndLoad runs while we still have things blocking
4845 // DOMContentLoaded. We wait for those to complete, and then update the
4846 // readystate when they finish.
4847 bool mSetCompleteAfterDOMContentLoaded : 1;
4849 // Set the true if a completed cached stylesheet was created for the document.
4850 bool mDidHitCompleteSheetCache : 1;
4852 // Whether we have initialized mShouldReportUseCounters and
4853 // mShouldSendPageUseCounters, and sent any needed message to the parent
4854 // process to indicate that use counter data will be sent at some later point.
4855 bool mUseCountersInitialized : 1;
4857 // Whether this document should report use counters.
4858 bool mShouldReportUseCounters : 1;
4860 // Whether this document should send page use counters. Set to true after
4861 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4862 bool mShouldSendPageUseCounters : 1;
4864 // Whether the user has interacted with the document or not:
4865 bool mUserHasInteracted : 1;
4867 // We constantly update the user-interaction anti-tracking permission at any
4868 // user-interaction using a timer. This boolean value is set to true when this
4869 // timer is scheduled.
4870 bool mHasUserInteractionTimerScheduled : 1;
4872 // Whether we should resist fingerprinting.
4873 bool mShouldResistFingerprinting : 1;
4875 // Whether we are in private browsing mode.
4876 bool mIsInPrivateBrowsing : 1;
4878 // Whether we're cloning the contents of an SVG use element.
4879 bool mCloningForSVGUse : 1;
4881 bool mAllowDeclarativeShadowRoots : 1;
4883 bool mSuspendDOMNotifications : 1;
4885 // The fingerprinting protections overrides for this document. The value will
4886 // override the default enabled fingerprinting protections for this document.
4887 // This will only get populated if these is one that comes from the local
4888 // fingerprinting protection override pref or WebCompat. Otherwise, a value of
4889 // Nothing() indicates no overrides are present for this document.
4890 Maybe<RFPTarget> mOverriddenFingerprintingSettings;
4892 uint8_t mXMLDeclarationBits;
4894 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4895 // use uint8_t to avoid having to include a bunch of style system headers
4896 // everywhere.
4897 uint8_t mColorSchemeBits = 0;
4899 // Currently active onload blockers.
4900 uint32_t mOnloadBlockCount;
4902 // Tracks if we are currently processing any document.write calls (either
4903 // implicit or explicit). Note that if a write call writes out something which
4904 // would block the parser, then mWriteLevel will be incorrect until the parser
4905 // finishes processing that script.
4906 uint32_t mWriteLevel;
4908 uint32_t mContentEditableCount;
4909 EditingState mEditingState;
4911 // Compatibility mode
4912 nsCompatibility mCompatMode;
4914 // Our readyState
4915 ReadyState mReadyState;
4917 // Ancestor's loading state
4918 bool mAncestorIsLoading;
4920 // Our visibility state
4921 dom::VisibilityState mVisibilityState;
4923 enum Type {
4924 eUnknown, // should never be used
4925 eHTML,
4926 eXHTML,
4927 eGenericXML,
4928 eSVG
4931 Type mType;
4933 uint8_t mDefaultElementType;
4935 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4937 Tri mAllowXULXBL;
4939 bool mSkipDTDSecurityChecks;
4941 // The document's script global object, the object from which the
4942 // document can get its script context and scope. This is the
4943 // *inner* window object.
4944 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4946 // If mIsStaticDocument is true, mOriginalDocument points to the original
4947 // document.
4948 RefPtr<Document> mOriginalDocument;
4950 // The bidi options for this document. What this bitfield means is
4951 // defined in nsBidiUtils.h
4952 uint32_t mBidiOptions;
4954 // The sandbox flags on the document. These reflect the value of the sandbox
4955 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4956 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4957 // possible flags.
4958 uint32_t mSandboxFlags;
4960 // The embedder policy obtained from parsing the HTTP response header or from
4961 // our opener if this is the initial about:blank document.
4962 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4964 RefPtr<nsAtom> mContentLanguage;
4966 // The channel that got passed to Document::StartDocumentLoad(), if any.
4967 nsCOMPtr<nsIChannel> mChannel;
4969 // The CSP for every load lives in the Client within the LoadInfo. For all
4970 // document-initiated subresource loads we can use that cached version of the
4971 // CSP so we do not have to deserialize the CSP from the Client all the time.
4972 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4973 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4975 private:
4976 nsCString mContentType;
4978 protected:
4979 // The document's security info
4980 nsCOMPtr<nsITransportSecurityInfo> mSecurityInfo;
4982 // The channel that failed to load and resulted in an error page.
4983 // This only applies to error pages. Might be null.
4984 nsCOMPtr<nsIChannel> mFailedChannel;
4986 // if this document is part of a multipart document,
4987 // the ID can be used to distinguish it from the other parts.
4988 uint32_t mPartID;
4990 // Cycle collector generation in which we're certain that this document
4991 // won't be collected
4992 uint32_t mMarkedCCGeneration;
4994 PresShell* mPresShell;
4996 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4997 uint32_t mSubtreeModifiedDepth;
4999 // All images in process of being preloaded. This is a hashtable so
5000 // we can remove them as the real image loads start; that way we
5001 // make sure to not keep the image load going when no one cares
5002 // about it anymore.
5003 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
5005 // A list of preconnects initiated by the preloader. This prevents
5006 // the same uri from being used more than once, and allows the dom
5007 // builder to not repeat the work of the preloader.
5008 nsTHashMap<nsURIHashKey, bool> mPreloadedPreconnects;
5010 // Current depth of picture elements from parser
5011 uint32_t mPreloadPictureDepth;
5013 // Set if we've found a URL for the current picture
5014 nsString mPreloadPictureFoundSource;
5016 // If we're an external resource document, this will be non-null and will
5017 // point to our "display document": the one that all resource lookups should
5018 // go to.
5019 RefPtr<Document> mDisplayDocument;
5021 uint32_t mEventsSuppressed;
5023 // Any XHR ChannelEventQueues that were suspended on this document while
5024 // events were suppressed.
5025 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
5027 // Any postMessage events that were suspended on this document while events
5028 // were suppressed.
5029 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
5031 RefPtr<EventListener> mSuppressedEventListener;
5034 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5036 uint32_t mIgnoreDestructiveWritesCounter;
5038 // Count of live static clones of this document.
5039 uint32_t mStaticCloneCount;
5041 // If the document is currently printing (or in print preview) this will point
5042 // to the current static clone of this document. This is weak since the clone
5043 // also has a reference to this document.
5044 WeakPtr<Document> mLatestStaticClone;
5046 // Array of nodes that have been blocked to prevent user tracking.
5047 // They most likely have had their nsIChannel canceled by the URL
5048 // classifier. (Safebrowsing)
5050 // Weak nsINode pointers are used to allow nodes to disappear.
5051 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
5053 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5054 // updated on every set of mScriptGlobalObject.
5055 nsPIDOMWindowInner* mWindow;
5057 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
5059 FrameRequestManager mFrameRequestManager;
5061 // This object allows us to evict ourself from the back/forward cache. The
5062 // pointer is non-null iff we're currently in the bfcache.
5063 nsIBFCacheEntry* mBFCacheEntry;
5065 // Our base target.
5066 nsString mBaseTarget;
5068 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
5069 JS::Heap<JS::Value> mCachedStateObject;
5071 uint32_t mInSyncOperationCount;
5073 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
5075 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
5077 uint32_t mBlockDOMContentLoaded;
5079 // Our live MediaQueryLists
5080 LinkedList<MediaQueryList> mDOMMediaQueryLists;
5082 // A hashset to keep track of which {element, imgRequestProxy}
5083 // combination has been processed to avoid considering the same
5084 // element twice for LargestContentfulPaint.
5085 nsTHashtable<LCPEntryHashEntry> mContentIdentifiersForLCP;
5087 // Array of observers
5088 nsTObserverArray<nsIDocumentObserver*> mObservers;
5090 // Flags for use counters used directly by this document.
5091 UseCounters mUseCounters;
5092 // Flags for use counters from resource documents, static clones,
5093 // and SVG images referenced by this document. Those documents propagate
5094 // their use counters up to here, which then count towards the top-level
5095 // document's page use counters.
5096 UseCounters mChildDocumentUseCounters;
5098 // The CSS property use counters.
5099 UniquePtr<StyleUseCounters> mStyleUseCounters;
5101 TimeStamp mPageUnloadingEventTimeStamp;
5103 RefPtr<DocGroup> mDocGroup;
5105 RefPtr<nsCommandManager> mMidasCommandManager;
5107 // The set of all the tracking script URLs. URLs are added to this set by
5108 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5109 // existing in the set means the corresponding script isn't a tracking script.
5110 nsTHashSet<nsCString> mTrackingScripts;
5112 // Pointer to our parser if we're currently in the process of being
5113 // parsed into.
5114 nsCOMPtr<nsIParser> mParser;
5116 // If the document was created from the the prototype cache there will be a
5117 // reference to the prototype document to allow tracing.
5118 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
5120 // Weak reference to our sink for in case we no longer have a parser. This
5121 // will allow us to flush out any pending stuff from the sink even if
5122 // EndLoad() has already happened.
5123 nsWeakPtr mWeakSink;
5125 // Our update nesting level
5126 uint32_t mUpdateNestLevel;
5128 // HTTPS-Only Mode Status
5129 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5130 uint32_t mHttpsOnlyStatus;
5132 enum ViewportType : uint8_t {
5133 DisplayWidthHeight,
5134 Specified,
5135 Unknown,
5138 ViewportType mViewportType;
5140 // viewport-fit described by
5141 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5142 ViewportFitType mViewportFit;
5144 // XXXdholbert This should really be modernized to a nsTHashMap or similar,
5145 // though note that the modernization will need to take care to also convert
5146 // the special hash_table_ops logic (e.g. how SubDocClearEntry clears the
5147 // parent document as part of cleaning up an entry in this table).
5148 UniquePtr<PLDHashTable> mSubDocuments;
5150 class HeaderData;
5151 UniquePtr<HeaderData> mHeaderData;
5153 nsTArray<net::EarlyHintConnectArgs> mEarlyHints;
5155 class TitleChangeEvent;
5156 nsRevocableEventPtr<TitleChangeEvent> mPendingTitleChangeEvent;
5158 RefPtr<nsDOMNavigationTiming> mTiming;
5160 // Recorded time of change to 'loading' state
5161 // or time of the page gets restored from BFCache.
5162 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp;
5164 // Decided to use nsTObserverArray because it allows us to
5165 // remove candidates while iterating them and this is what
5166 // the spec defines. We could implement the spec without
5167 // using nsTObserverArray, however using nsTObserverArray is more clear.
5168 nsTObserverArray<nsWeakPtr> mAutoFocusCandidates;
5170 nsCString mScrollToRef;
5172 // Weak reference to the scope object (aka the script global object)
5173 // that, unlike mScriptGlobalObject, is never unset once set. This
5174 // is a weak reference to avoid leaks due to circular references.
5175 nsWeakPtr mScopeObject;
5177 // Array of intersection observers
5178 nsTHashSet<DOMIntersectionObserver*> mIntersectionObservers;
5180 // Array of resize observers
5181 nsTArray<ResizeObserver*> mResizeObservers;
5183 RefPtr<DOMIntersectionObserver> mLazyLoadObserver;
5185 // Elements observed for a last remembered size.
5186 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5187 nsTHashSet<RefPtr<Element>> mElementsObservedForLastRememberedSize;
5189 // Stack of top layer elements.
5190 nsTArray<nsWeakPtr> mTopLayer;
5192 // The root of the doc tree in which this document is in. This is only
5193 // non-null when this document is in fullscreen mode.
5194 WeakPtr<Document> mFullscreenRoot;
5196 RefPtr<DOMImplementation> mDOMImplementation;
5198 RefPtr<nsContentList> mImageMaps;
5200 // A set of responsive images keyed by address pointer.
5201 nsTHashSet<HTMLImageElement*> mResponsiveContent;
5203 RefPtr<DocumentTimeline> mDocumentTimeline;
5204 LinkedList<DocumentTimeline> mTimelines;
5206 RefPtr<dom::ScriptLoader> mScriptLoader;
5208 // Tracker for scroll-driven animations that are waiting to start.
5209 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5210 RefPtr<ScrollTimelineAnimationTracker> mScrollTimelineAnimationTracker;
5212 // A document "without a browsing context" that owns the content of
5213 // HTMLTemplateElement.
5214 RefPtr<Document> mTemplateContentsOwner;
5216 dom::ExternalResourceMap mExternalResourceMap;
5218 // ScreenOrientation "pending promise" as described by
5219 // http://www.w3.org/TR/screen-orientation/
5220 RefPtr<Promise> mOrientationPendingPromise;
5222 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
5223 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
5224 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
5226 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
5228 // The layout history state that should be used by nodes in this
5229 // document. We only actually store a pointer to it when:
5230 // 1) We have no script global object.
5231 // 2) We haven't had Destroy() called on us yet.
5232 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
5234 // Mapping of wake lock types to sets of wake locks sentinels
5235 // https://w3c.github.io/screen-wake-lock/#internal-slots
5236 nsTHashMap<WakeLockType, nsTHashSet<RefPtr<WakeLockSentinel>>> mActiveLocks;
5238 // The parsed viewport metadata of the last modified <meta name=viewport>
5239 // element.
5240 UniquePtr<ViewportMetaData> mLastModifiedViewportMetaData;
5242 // A tree ordered list of all color-scheme meta tags in this document.
5244 // TODO(emilio): There are other meta tags in the spec that have a similar
5245 // processing model to color-scheme. We could store all in-document meta tags
5246 // here to get sane and fast <meta> element processing.
5247 TreeOrderedArray<HTMLMetaElement*> mColorSchemeMetaTags;
5249 // These member variables cache information about the viewport so we don't
5250 // have to recalculate it each time.
5251 LayoutDeviceToScreenScale mScaleMinFloat;
5252 LayoutDeviceToScreenScale mScaleMaxFloat;
5253 LayoutDeviceToScreenScale mScaleFloat;
5254 CSSToLayoutDeviceScale mPixelRatio;
5256 CSSCoord mMinWidth;
5257 CSSCoord mMaxWidth;
5258 CSSCoord mMinHeight;
5259 CSSCoord mMaxHeight;
5261 RefPtr<EventListenerManager> mListenerManager;
5263 nsCOMPtr<nsIRequest> mOnloadBlocker;
5265 // Gecko-internal sheets used for extensions and such.
5266 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5267 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5269 // Member to store out last-selected stylesheet set.
5270 nsString mLastStyleSheetSet;
5271 nsString mPreferredStyleSheetSet;
5273 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5275 // We lazily calculate declaration blocks for elements with mapped
5276 // attributes. This set contains all elements which need lazy resolution.
5277 nsTHashSet<Element*> mLazyPresElements;
5279 nsTHashSet<RefPtr<nsAtom>> mLanguagesUsed;
5281 // TODO(emilio): Is this hot enough to warrant to be cached?
5282 RefPtr<nsAtom> mLanguageFromCharset;
5284 // Restyle root for servo's style system.
5286 // We store this as an nsINode, rather than as an Element, so that we can
5287 // store the Document node as the restyle root if the entire document (along
5288 // with all document-level native-anonymous content) needs to be restyled.
5290 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5291 // root corresponds to.
5292 nsCOMPtr<nsINode> mServoRestyleRoot;
5293 uint32_t mServoRestyleRootDirtyBits;
5295 // Used in conjunction with the create-an-element-for-the-token algorithm to
5296 // prevent custom element constructors from being able to use document.open(),
5297 // document.close(), and document.write() when they are invoked by the parser.
5298 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5300 // Count of unload/beforeunload/pagehide operations in progress.
5301 uint32_t mIgnoreOpensDuringUnloadCounter;
5303 nsCOMPtr<nsIDOMXULCommandDispatcher>
5304 mCommandDispatcher; // [OWNER] of the focus tracker
5306 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5307 RefPtr<XULPersist> mXULPersist;
5308 RefPtr<ChromeObserver> mChromeObserver;
5310 RefPtr<HTMLAllCollection> mAll;
5312 nsTHashSet<RefPtr<WorkerDocumentListener>> mWorkerListeners;
5314 // Pres shell resolution saved before entering fullscreen mode.
5315 float mSavedResolution;
5317 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5319 bool mHasStoragePermission;
5321 // Document generation. Gets incremented everytime it changes.
5322 int32_t mGeneration;
5324 // Cached TabSizes values for the document.
5325 int32_t mCachedTabSizeGeneration;
5326 nsTabSizes mCachedTabSizes;
5328 // This is equal to document's principal but with an isolation key. See
5329 // StoragePrincipalHelper.h to know more.
5330 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5332 // The cached storage principal for this document.
5333 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5334 // which is required due to its CloneDocHelper() call site. :-(
5335 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5337 // The cached cookie principal for this document.
5338 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5339 // which is required due to its CloneDocHelper() call site. :-(
5340 mutable nsCOMPtr<nsIPrincipal> mActiveCookiePrincipal;
5342 // See GetNextFormNumber and GetNextControlNumber.
5343 int32_t mNextFormNumber;
5344 int32_t mNextControlNumber;
5346 uint32_t mMediaElementWithMSECount = 0;
5348 // Scope preloads per document. This is used by speculative loading as well.
5349 PreloadService mPreloadService;
5351 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5352 bool mShouldNotifyFetchSuccess;
5354 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5355 bool mShouldNotifyFormOrPasswordRemoved;
5357 // Record page load telemetry
5358 void RecordPageLoadEventTelemetry(
5359 glean::perf::PageLoadExtra& aEventTelemetryData);
5361 // Accumulate JS telemetry collected
5362 void AccumulateJSTelemetry(
5363 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5365 // Accumulate page load metrics
5366 void AccumulatePageLoadTelemetry(
5367 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5369 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5370 // Not holding strong refs here since we don't actually use the BBCs.
5371 nsTArray<const BrowserBridgeChild*> mOOPChildrenLoading;
5373 // Registry of custom highlight definitions associated with this document.
5374 RefPtr<class HighlightRegistry> mHighlightRegistry;
5376 // Used for tracking a number of recent canvas extractions (e.g. toDataURL),
5377 // this is used for a canvas fingerprinter detection heuristic.
5378 nsTArray<CanvasUsage> mCanvasUsage;
5379 uint64_t mLastCanvasUsage = 0;
5381 RefPtr<class FragmentDirective> mFragmentDirective;
5382 UniquePtr<RadioGroupContainer> mRadioGroupContainer;
5384 public:
5385 // Needs to be public because the bindings code pokes at it.
5386 JS::ExpandoAndGeneration mExpandoAndGeneration;
5388 bool HasPendingInitialTranslation();
5390 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5391 mL10nProtoElements;
5393 void LoadEventFired();
5395 RadioGroupContainer& OwnedRadioGroupContainer();
5397 static already_AddRefed<Document> ParseHTMLUnsafe(GlobalObject& aGlobal,
5398 const nsAString& aHTML);
5401 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5404 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5405 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5406 * object is deleted.
5408 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5409 public:
5411 * @param aSubTreeOwner The document in which a subtree will be modified.
5412 * @param aTarget The target of the possible DOMSubtreeModified event.
5413 * Can be nullptr, in which case mozAutoSubtreeModified
5414 * is just used to batch DOM mutations.
5416 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5417 UpdateTarget(aSubtreeOwner, aTarget);
5420 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5422 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5423 if (mSubtreeOwner) {
5424 mSubtreeOwner->MutationEventDispatched(mTarget);
5427 mTarget = aTarget;
5428 mSubtreeOwner = aSubtreeOwner;
5429 if (mSubtreeOwner) {
5430 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5434 private:
5435 nsCOMPtr<nsINode> mTarget;
5436 RefPtr<Document> mSubtreeOwner;
5439 enum class SyncOperationBehavior { eSuspendInput, eAllowInput };
5441 class AutoWalkBrowsingContextGroup {
5442 public:
5443 virtual ~AutoWalkBrowsingContextGroup() = default;
5445 protected:
5446 void SuppressBrowsingContext(BrowsingContext* aContext);
5447 void SuppressBrowsingContextGroup(BrowsingContextGroup* aGroup);
5448 void UnsuppressDocuments() {
5449 for (const auto& doc : mDocuments) {
5450 UnsuppressDocument(doc);
5453 virtual void SuppressDocument(Document* aDocument) = 0;
5454 virtual void UnsuppressDocument(Document* aDocument) = 0;
5455 AutoTArray<RefPtr<Document>, 16> mDocuments;
5458 class MOZ_RAII nsAutoSyncOperation : private AutoWalkBrowsingContextGroup {
5459 public:
5460 explicit nsAutoSyncOperation(Document* aDocument,
5461 SyncOperationBehavior aSyncBehavior);
5462 ~nsAutoSyncOperation();
5464 protected:
5465 void SuppressDocument(Document* aDocument) override;
5466 void UnsuppressDocument(Document* aDocument) override;
5468 private:
5469 uint32_t mMicroTaskLevel;
5470 const SyncOperationBehavior mSyncBehavior;
5471 RefPtr<BrowsingContext> mBrowsingContext;
5474 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5475 public:
5476 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5477 : mDocument(aDocument) {
5478 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5481 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5482 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5485 private:
5486 Document* mDocument;
5489 class MOZ_RAII IgnoreOpensDuringUnload final {
5490 public:
5491 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5492 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5495 ~IgnoreOpensDuringUnload() {
5496 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5499 private:
5500 Document* mDoc;
5503 bool IsInFocusedTab(Document* aDoc);
5505 // This covers all cases covered by IsInFocusedTab, but also ensures that
5506 // focused tab is "active" meaning not occluded.
5507 bool IsInActiveTab(Document* aDoc);
5509 } // namespace mozilla::dom
5511 NON_VIRTUAL_ADDREF_RELEASE(mozilla::dom::Document)
5513 // XXX These belong somewhere else
5514 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5515 nsIPrincipal* aPrincipal,
5516 nsIPrincipal* aPartitionedPrincipal,
5517 bool aLoadedAsData = false);
5519 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5520 nsIPrincipal* aPrincipal,
5521 nsIPrincipal* aPartitionedPrincipal,
5522 bool aLoadedAsData = false,
5523 bool aIsPlainDocument = false);
5525 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult,
5526 nsIPrincipal* aPrincipal,
5527 nsIPrincipal* aPartitionedPrincipal);
5529 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult,
5530 nsIPrincipal* aPrincipal,
5531 nsIPrincipal* aPartitionedPrincipal);
5533 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult,
5534 nsIPrincipal* aPrincipal,
5535 nsIPrincipal* aPartitionedPrincipal);
5537 // Enum for requesting a particular type of document when creating a doc
5538 enum DocumentFlavor {
5539 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5540 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5541 DocumentFlavorSVG, // SVGDocument
5542 DocumentFlavorXML, // XMLDocument
5543 DocumentFlavorPlain, // Just a Document
5546 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5547 // -- this method will not attempt to get a principal based on aDocumentURI.
5548 // Also, both aDocumentURI and aBaseURI must not be null.
5549 nsresult NS_NewDOMDocument(
5550 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5551 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5552 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5553 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5555 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5556 mozilla::dom::Document* ownerDoc = OwnerDoc();
5558 return ownerDoc != this ? ownerDoc : nullptr;
5561 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5563 inline mozilla::dom::Document* nsINode::AsDocument() {
5564 MOZ_ASSERT(IsDocument());
5565 return static_cast<mozilla::dom::Document*>(this);
5568 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5569 MOZ_ASSERT(IsDocument());
5570 return static_cast<const mozilla::dom::Document*>(this);
5573 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5574 return static_cast<nsINode*>(aDoc);
5577 #endif /* mozilla_dom_Document_h___ */