Backed out 4 changesets (bug 1825722) for causing reftest failures CLOSED TREE
[gecko.git] / dom / base / Document.h
blobca9638a2d6c428649dc734e050e5412e49a5b253
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 "mozilla/glean/GleanMetrics.h"
61 #include "nsAtom.h"
62 #include "nsCOMArray.h"
63 #include "nsCOMPtr.h"
64 #include "nsClassHashtable.h"
65 #include "nsCompatibility.h"
66 #include "nsContentListDeclarations.h"
67 #include "nsCycleCollectionParticipant.h"
68 #include "nsTHashMap.h"
69 #include "nsDebug.h"
70 #include "nsGkAtoms.h"
71 #include "nsHashKeys.h"
72 #include "nsIChannel.h"
73 #include "nsIChannelEventSink.h"
74 #include "nsID.h"
75 #include "nsIDocumentViewer.h"
76 #include "nsIInterfaceRequestor.h"
77 #include "nsILoadContext.h"
78 #include "nsILoadGroup.h"
79 #include "nsILoadInfo.h"
80 #include "nsINode.h"
81 #include "nsIObserver.h"
82 #include "nsIParser.h"
83 #include "nsIPrincipal.h"
84 #include "nsIProgressEventSink.h"
85 #include "nsIReferrerInfo.h"
86 #include "nsIRequestObserver.h"
87 #include "nsIScriptObjectPrincipal.h"
88 #include "nsIStreamListener.h"
89 #include "nsISupports.h"
90 #include "nsISupportsUtils.h"
91 #include "nsITransportSecurityInfo.h"
92 #include "nsIURI.h"
93 #include "nsIWeakReferenceUtils.h"
94 #include "nsLiteralString.h"
95 #include "nsPIDOMWindow.h"
96 #include "nsPropertyTable.h"
97 #include "nsRefPtrHashtable.h"
98 #include "nsString.h"
99 #include "nsTArray.h"
100 #include "nsTHashSet.h"
101 #include "nsTLiteralString.h"
102 #include "nsTObserverArray.h"
103 #include "nsThreadUtils.h"
104 #include "nsURIHashKey.h"
105 #include "nsViewportInfo.h"
106 #include "nsWeakReference.h"
107 #include "nsWindowSizes.h"
108 #include "nsXULElement.h"
109 #include "nscore.h"
111 // XXX We need to include this here to ensure that DefaultDeleter for Servo
112 // types is specialized before the template is instantiated. Probably, this
113 // should be included at some other place already that's generated by cbindgen.
114 #include "mozilla/ServoBindingTypes.h"
116 // windows.h #defines CreateEvent
117 #ifdef CreateEvent
118 # undef CreateEvent
119 #endif
121 #ifdef MOZILLA_INTERNAL_API
122 # include "mozilla/dom/DocumentBinding.h"
123 #else
124 namespace mozilla {
125 namespace dom {
126 class ElementCreationOptionsOrString;
127 } // namespace dom
128 } // namespace mozilla
129 #endif // MOZILLA_INTERNAL_API
131 class InfallibleAllocPolicy;
132 class JSObject;
133 class JSTracer;
134 class PLDHashTable;
135 class gfxUserFontSet;
136 class mozIDOMWindowProxy;
137 class nsCachableElementsByNameNodeList;
138 class nsCommandManager;
139 class nsContentList;
140 class nsCycleCollectionTraversalCallback;
141 class nsDOMCaretPosition;
142 class nsDOMNavigationTiming;
143 class nsDocShell;
144 class nsFrameLoader;
145 class nsFrameLoaderOwner;
146 class nsGenericHTMLElement;
147 class nsGlobalWindowInner;
148 class nsHTMLDocument;
149 class nsHtml5TreeOpExecutor;
150 class nsIAppWindow;
151 class nsIAsyncVerifyRedirectCallback;
152 class nsIBFCacheEntry;
153 class nsIContent;
154 class nsIContentSecurityPolicy;
155 class nsIContentSink;
156 class nsICookieJarSettings;
157 class nsIDOMXULCommandDispatcher;
158 class nsIDocShell;
159 class nsIDocShellTreeItem;
160 class nsIDocumentEncoder;
161 class nsIDocumentObserver;
162 class nsIEventTarget;
163 class nsIFrame;
164 class nsIGlobalObject;
165 class nsIHTMLCollection;
166 class nsIInputStream;
167 class nsILayoutHistoryState;
168 class nsIObjectLoadingContent;
169 class nsIPermissionDelegateHandler;
170 class nsIRadioVisitor;
171 class nsIRequest;
172 class nsIRunnable;
173 class nsIScriptGlobalObject;
174 class nsISecurityConsoleMessage;
175 class nsISerialEventTarget;
176 class nsIStructuredCloneContainer;
177 class nsIVariant;
178 class nsNodeInfoManager;
179 class nsPIWindowRoot;
180 class nsPresContext;
181 class nsRange;
182 class nsSimpleContentList;
183 class nsTextNode;
184 class nsViewManager;
185 class nsXULPrototypeDocument;
186 struct JSContext;
187 struct nsFont;
189 namespace mozilla {
190 class AbstractThread;
191 class AttributeStyles;
192 class CanvasUsage;
193 class StyleSheet;
194 class EditorBase;
195 class EditorCommand;
196 class Encoding;
197 class ErrorResult;
198 class EventListenerManager;
199 class FullscreenExit;
200 class FullscreenRequest;
201 class HTMLEditor;
202 struct LangGroupFontPrefs;
203 class PermissionDelegateHandler;
204 class PresShell;
205 class ScrollTimelineAnimationTracker;
206 class ServoStyleSet;
207 enum class StyleOrigin : uint8_t;
208 class SMILAnimationController;
209 enum class StyleCursorKind : uint8_t;
210 class SVGContextPaint;
211 enum class ColorScheme : uint8_t;
212 enum class StyleRuleChangeKind : uint32_t;
213 struct StyleUseCounters;
214 template <typename>
215 class OwningNonNull;
216 struct URLExtraData;
218 namespace css {
219 class Loader;
220 class ImageLoader;
221 class Rule;
222 } // namespace css
224 namespace dom {
225 class AnonymousContent;
226 class Attr;
227 class XULBroadcastManager;
228 class XULPersist;
229 class BrowserBridgeChild;
230 class ChromeObserver;
231 class ClientInfo;
232 class ClientState;
233 class CDATASection;
234 class Comment;
235 class CSSImportRule;
236 class DocumentL10n;
237 class DocumentFragment;
238 class DocumentTimeline;
239 class DocumentType;
240 class DOMImplementation;
241 class DOMIntersectionObserver;
242 class DOMStringList;
243 class Event;
244 class EventListener;
245 struct FailedCertSecurityInfo;
246 class FeaturePolicy;
247 class FontFaceSet;
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 mozilla
325 namespace mozilla::net {
326 class ChannelEventQueue;
327 class EarlyHintConnectArgs;
328 } // namespace mozilla::net
330 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
331 #define NS_IDOCUMENT_IID \
333 0xce1f7627, 0x7109, 0x4977, { \
334 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
338 namespace mozilla::dom {
340 class Document;
341 class DOMStyleSheetSetList;
342 class ResizeObserver;
343 class ResizeObserverController;
344 class PostMessageEvent;
346 #define DEPRECATED_OPERATION(_op) e##_op,
347 enum class DeprecatedOperations : uint16_t {
348 #include "nsDeprecatedOperationList.h"
349 eDeprecatedOperationCount
351 #undef DEPRECATED_OPERATION
353 class ExternalResourceMap {
354 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
356 public:
358 * A class that represents an external resource load that has begun but
359 * doesn't have a document yet. Observers can be registered on this object,
360 * and will be notified after the document is created. Observers registered
361 * after the document has been created will NOT be notified. When observers
362 * are notified, the subject will be the newly-created document, the topic
363 * will be "external-resource-document-created", and the data will be null.
364 * If document creation fails for some reason, observers will still be
365 * notified, with a null document pointer.
367 class ExternalResourceLoad : public nsISupports {
368 public:
369 virtual ~ExternalResourceLoad() = default;
371 void AddObserver(nsIObserver* aObserver) {
372 MOZ_ASSERT(aObserver, "Must have observer");
373 mObservers.AppendElement(aObserver);
376 const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
378 protected:
379 AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
382 ExternalResourceMap();
385 * Request an external resource document. This does exactly what
386 * Document::RequestExternalResource is documented to do.
388 Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
389 nsINode* aRequestingNode,
390 Document* aDisplayDocument,
391 ExternalResourceLoad** aPendingLoad);
394 * Enumerate the resource documents. See
395 * Document::EnumerateExternalResources.
397 void EnumerateResources(SubDocEnumFunc aCallback);
400 * Traverse ourselves for cycle-collection
402 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
405 * Shut ourselves down (used for cycle-collection unlink), as well
406 * as for document destruction.
408 void Shutdown() {
409 mPendingLoads.Clear();
410 mMap.Clear();
411 mHaveShutDown = true;
414 bool HaveShutDown() const { return mHaveShutDown; }
416 // Needs to be public so we can traverse them sanely
417 struct ExternalResource {
418 ~ExternalResource();
419 RefPtr<Document> mDocument;
420 nsCOMPtr<nsIDocumentViewer> mViewer;
421 nsCOMPtr<nsILoadGroup> mLoadGroup;
424 // Hide all our viewers
425 void HideViewers();
427 // Show all our viewers
428 void ShowViewers();
430 protected:
431 class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
432 ~PendingLoad() = default;
434 public:
435 explicit PendingLoad(Document* aDisplayDocument)
436 : mDisplayDocument(aDisplayDocument) {}
438 NS_DECL_ISUPPORTS
439 NS_DECL_NSISTREAMLISTENER
440 NS_DECL_NSIREQUESTOBSERVER
443 * Start aURI loading. This will perform the necessary security checks and
444 * so forth.
446 nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
447 nsINode* aRequestingNode);
449 * Set up an nsIDocumentViewer based on aRequest. This is guaranteed to
450 * put null in *aViewer and *aLoadGroup on all failures.
452 nsresult SetupViewer(nsIRequest* aRequest, nsIDocumentViewer** aViewer,
453 nsILoadGroup** aLoadGroup);
455 private:
456 RefPtr<Document> mDisplayDocument;
457 nsCOMPtr<nsIStreamListener> mTargetListener;
458 nsCOMPtr<nsIURI> mURI;
460 friend class PendingLoad;
462 class LoadgroupCallbacks final : public nsIInterfaceRequestor {
463 ~LoadgroupCallbacks() = default;
465 public:
466 explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
467 : mCallbacks(aOtherCallbacks) {}
468 NS_DECL_ISUPPORTS
469 NS_DECL_NSIINTERFACEREQUESTOR
470 private:
471 // The only reason it's safe to hold a strong ref here without leaking is
472 // that the notificationCallbacks on a loadgroup aren't the docshell itself
473 // but a shim that holds a weak reference to the docshell.
474 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
476 // Use shims for interfaces that docshell implements directly so that we
477 // don't hand out references to the docshell. The shims should all allow
478 // getInterface back on us, but other than that each one should only
479 // implement one interface.
481 // XXXbz I wish we could just derive the _allcaps thing from _i
482 #define DECL_SHIM(_i, _allcaps) \
483 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
484 ~_i##Shim() {} \
486 public: \
487 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
488 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
489 NS_ASSERTION(mIfReq, "Expected non-null here"); \
490 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
492 NS_DECL_ISUPPORTS \
493 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
494 NS_FORWARD_##_allcaps(mRealPtr->) private \
495 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
496 nsCOMPtr<_i> mRealPtr; \
499 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
500 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
501 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
502 #undef DECL_SHIM
506 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
507 * when this is called if the URI didn't result in an XML document. This
508 * function makes sure to remove the pending load for aURI, if any, from our
509 * hashtable, and to notify its observers, if any.
511 nsresult AddExternalResource(nsIURI* aURI, nsIDocumentViewer* aViewer,
512 nsILoadGroup* aLoadGroup,
513 Document* aDisplayDocument);
515 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
516 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
517 bool mHaveShutDown;
520 // The current status for a preload.
521 enum class SheetPreloadStatus : uint8_t {
522 // There's no need to preload anything, the sheet is already in-memory.
523 AlreadyComplete,
524 // The load is in-progress. There's no guarantee that a load was started, it
525 // could be coalesced with other redundant loads.
526 InProgress,
527 // Something went wrong, and we errored out.
528 Errored,
531 //----------------------------------------------------------------------
533 // Document interface. This is implemented by all document objects in
534 // Gecko.
535 class Document : public nsINode,
536 public DocumentOrShadowRoot,
537 public nsSupportsWeakReference,
538 public nsIScriptObjectPrincipal,
539 public SupportsWeakPtr {
540 friend class DocumentOrShadowRoot;
542 protected:
543 explicit Document(const char* aContentType);
544 virtual ~Document();
546 Document(const Document&) = delete;
547 Document& operator=(const Document&) = delete;
549 public:
550 using ExternalResourceLoad = dom::ExternalResourceMap::ExternalResourceLoad;
551 using ReferrerPolicyEnum = dom::ReferrerPolicy;
552 using AdoptedStyleSheetCloneCache =
553 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
555 // nsINode overrides the new operator for DOM Arena allocation.
556 // to use the default one, we need to bring it back again
557 void* operator new(size_t aSize) { return ::operator new(aSize); }
560 * Called when XPCOM shutdown.
562 static void Shutdown();
564 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
566 NS_DECL_ISUPPORTS_INHERITED
567 NS_IMETHOD_(void) DeleteCycleCollectable() override;
569 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
571 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
572 nsINode)
574 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
575 do { \
576 for (RefPtr obs : mObservers.ForwardRange()) { \
577 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
578 obs->func_ params_; \
581 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
582 looks bogus. */ \
583 if (PresShell* presShell = GetObservingPresShell()) { \
584 presShell->func_ params_; \
586 } while (0)
588 nsIPrincipal* EffectiveCookiePrincipal() const;
590 nsIPrincipal* EffectiveStoragePrincipal() const;
592 // nsIScriptObjectPrincipal
593 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
595 nsIPrincipal* GetEffectiveCookiePrincipal() final {
596 return EffectiveCookiePrincipal();
599 nsIPrincipal* GetEffectiveStoragePrincipal() final {
600 return EffectiveStoragePrincipal();
603 // You should probably not be using this function, since it performs no checks
604 // to ensure that the partitioned principal should really be used here. It is
605 // only designed to be used in very specific circumstances, such as when
606 // inheriting the document/storage principal.
607 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
609 // Gets the appropriate principal to check the URI against a blocklist /
610 // allowlist.
611 nsIPrincipal* GetPrincipalForPrefBasedHacks() const;
613 void ClearActiveCookieAndStoragePrincipals() {
614 mActiveStoragePrincipal = nullptr;
615 mActiveCookiePrincipal = nullptr;
618 // EventTarget
619 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
620 EventListenerManager* GetOrCreateListenerManager() override;
621 EventListenerManager* GetExistingListenerManager() const override;
623 // This helper class must be set when we dispatch beforeunload and unload
624 // events in order to avoid unterminate sync XHRs.
625 class MOZ_RAII PageUnloadingEventTimeStamp {
626 RefPtr<Document> mDocument;
627 bool mSet;
629 public:
630 explicit PageUnloadingEventTimeStamp(Document* aDocument)
631 : mDocument(aDocument), mSet(false) {
632 MOZ_ASSERT(aDocument);
633 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
634 mDocument->SetPageUnloadingEventTimeStamp();
635 mSet = true;
639 ~PageUnloadingEventTimeStamp() {
640 if (mSet) {
641 mDocument->CleanUnloadEventsTimeStamp();
647 * Let the document know that we're starting to load data into it.
648 * @param aCommand The parser command. Must not be null.
649 * XXXbz It's odd to have that here.
650 * @param aChannel The channel the data will come from. The channel must be
651 * able to report its Content-Type.
652 * @param aLoadGroup The loadgroup this document should use from now on.
653 * Note that the document might not be the only thing using
654 * this loadgroup.
655 * @param aContainer The container this document is in. This may be null.
656 * XXXbz maybe we should make it more explicit (eg make the
657 * container an nsIWebNavigation or nsIDocShell or
658 * something)?
659 * @param [out] aDocListener the listener to pump data from the channel into.
660 * Generally this will be the parser this document
661 * sets up, or some sort of data-handler for media
662 * documents.
663 * @param aReset whether the document should call Reset() on itself. If this
664 * is false, the document will NOT set its principal to the
665 * channel's owner, will not clear any event listeners that are
666 * already set on it, etc.
668 * Once this has been called, the document will return false for
669 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
670 * sure this happens is the responsibility of the caller of
671 * StartDocumentLoad().
673 * This function has an implementation, and does some setup, but does NOT set
674 * *aDocListener; this is the job of subclasses.
676 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
677 nsILoadGroup* aLoadGroup,
678 nsISupports* aContainer,
679 nsIStreamListener** aDocListener,
680 bool aReset) = 0;
681 void StopDocumentLoad();
683 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
684 virtual bool SuppressParserErrorElement() { return false; }
686 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
687 virtual bool SuppressParserErrorConsoleMessages() { return false; }
689 // nsINode
690 void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
691 bool aNotify, ErrorResult& aRv) override;
692 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
693 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
694 return NS_ERROR_NOT_IMPLEMENTED;
696 nsresult CloneDocHelper(Document* clone) const;
698 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
701 * Signal that the document title may have changed
702 * (see Document::GetTitle).
703 * @param aBoundTitleElement true if an HTML or SVG <title> element
704 * has just been bound to the document.
706 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
709 * Return the URI for the document. May return null. If it ever stops being
710 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
711 * also never return null.
713 * The value returned corresponds to the "document's address" in
714 * HTML5. As such, it may change over the lifetime of the document, for
715 * instance as a result of the user navigating to a fragment identifier on
716 * the page, or as a result to a call to pushState() or replaceState().
718 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
720 nsIURI* GetDocumentURI() const { return mDocumentURI; }
723 * Return the original URI of the document. This is the same as the
724 * document's URI unless that has changed from its original value (for
725 * example, due to history.pushState() or replaceState() being invoked on the
726 * document).
728 * This method corresponds to the "creation URL" in HTML5 and, once set,
729 * doesn't change over the lifetime of the document.
731 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
733 nsIURI* GetOriginalURI() const { return mOriginalURI; }
736 * Return the base domain of the document. This has been computed using
737 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
738 * checks. When the URI of the document changes, this value is recomputed.
740 nsCString GetBaseDomain() const { return mBaseDomain; }
743 * Set the URI for the document. This also sets the document's original URI,
744 * if it's null.
746 void SetDocumentURI(nsIURI* aURI);
749 * Set the URI for the document loaded via XHR, when accessed from
750 * chrome privileged script.
752 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
755 * Set the base URI for the document loaded via XHR, when accessed from
756 * chrome privileged script.
758 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
761 * The CSP in general is stored in the ClientInfo, but we also cache
762 * the CSP on the document so subresources loaded within a document
763 * can query that cached CSP instead of having to deserialize the CSP
764 * from the Client.
766 * Please note that at the time of CSP parsing the Client is not
767 * available yet, hence we sync CSP of document and Client when the
768 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
770 nsIContentSecurityPolicy* GetCsp() const;
771 void SetCsp(nsIContentSecurityPolicy* aCSP);
773 nsIContentSecurityPolicy* GetPreloadCsp() const;
774 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
776 void GetCspJSON(nsString& aJSON);
779 * Set referrer policy and upgrade-insecure-requests flags
781 void ApplySettingsFromCSP(bool aSpeculative);
783 already_AddRefed<nsIParser> CreatorParserOrNull() {
784 nsCOMPtr<nsIParser> parser = mParser;
785 return parser.forget();
789 * ReferrerInfo getter for Document.webidl.
791 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
793 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
795 nsIReferrerInfo* GetPreloadReferrerInfo() const {
796 return mPreloadReferrerInfo;
799 * Return the referrer policy of the document. Return "default" if there's no
800 * valid meta referrer tag found in the document.
801 * Referrer policy should be inherited from parent if the iframe is srcdoc
803 ReferrerPolicyEnum GetReferrerPolicy() const;
806 * GetReferrerPolicy() for Document.webidl.
808 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
811 * If true, this flag indicates that all mixed content subresource
812 * loads for this document (and also embeded browsing contexts) will
813 * be blocked.
815 bool GetBlockAllMixedContent(bool aPreload) const {
816 if (aPreload) {
817 return mBlockAllMixedContentPreloads;
819 return mBlockAllMixedContent;
823 * If true, this flag indicates that all subresource loads for this
824 * document need to be upgraded from http to https.
825 * This flag becomes true if the CSP of the document itself, or any
826 * of the document's ancestors up to the toplevel document makes use
827 * of the CSP directive 'upgrade-insecure-requests'.
829 bool GetUpgradeInsecureRequests(bool aPreload) const {
830 if (aPreload) {
831 return mUpgradeInsecurePreloads;
833 return mUpgradeInsecureRequests;
836 void SetReferrerInfo(nsIReferrerInfo*);
839 * Referrer policy from <meta name="referrer" content=`policy`>
840 * will have higher priority than referrer policy from Referrer-Policy
841 * header. So override the old ReferrerInfo if we get one from meta
843 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
844 bool aPreload);
847 * Set the principals responsible for this document. Chances are, you do not
848 * want to be using this.
850 void SetPrincipals(nsIPrincipal* aPrincipal,
851 nsIPrincipal* aPartitionedPrincipal);
854 * Returns true if exempt from HTTPS-Only Mode upgrade.
856 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
859 * Return the LoadGroup for the document. May return null.
861 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
862 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
863 return group.forget();
867 * Return the fallback base URL for this document, as defined in the HTML
868 * specification. Note that this can return null if there is no document URI.
870 * XXXbz: This doesn't implement the bits for about:blank yet.
872 nsIURI* GetFallbackBaseURI() const {
873 if (mIsSrcdocDocument && mParentDocument) {
874 return mParentDocument->GetDocBaseURI();
876 return mDocumentURI;
880 * Return the referrer from document URI as defined in the Referrer Policy
881 * specification.
882 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
883 * While document is an iframe srcdoc document, let document be document's
884 * browsing context's browsing context container's node document.
885 * Then referrer should be document's URL
888 nsIURI* GetDocumentURIAsReferrer() const {
889 if (mIsSrcdocDocument && mParentDocument) {
890 return mParentDocument->GetDocumentURIAsReferrer();
892 return mDocumentURI;
896 * Return the base URI for relative URIs in the document (the document uri
897 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
898 * returned URI could be null if there is no document URI. If the document is
899 * a srcdoc document and has no explicit base URL, return the parent
900 * document's base URL.
902 nsIURI* GetDocBaseURI() const {
903 if (mDocumentBaseURI) {
904 return mDocumentBaseURI;
906 return GetFallbackBaseURI();
909 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
911 void SetBaseURI(nsIURI* aURI);
914 * Resolves a URI based on the document's base URI.
916 Result<OwningNonNull<nsIURI>, nsresult> ResolveWithBaseURI(
917 const nsAString& aURI);
920 * Return the URL data which style system needs for resolving url value.
921 * This method attempts to use the cached object in mCachedURLData, but
922 * if the base URI, document URI, or principal has changed since last
923 * call to this function, or the function is called the first time for
924 * the document, a new one is created.
926 URLExtraData* DefaultStyleAttrURLData();
927 nsIReferrerInfo* ReferrerInfoForInternalCSSAndSVGResources();
930 * Get/Set the base target of a link in a document.
932 void GetBaseTarget(nsAString& aBaseTarget) const {
933 aBaseTarget = mBaseTarget;
936 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
939 * Return a standard name for the document's character set.
941 NotNull<const Encoding*> GetDocumentCharacterSet() const {
942 return mCharacterSet;
946 * Set the document's character encoding.
948 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
950 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
952 // This method MUST be called before SetDocumentCharacterSet if
953 // you're planning to call both.
954 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
955 mCharacterSetSource = aCharsetSource;
959 * Get the Content-Type of this document.
961 void GetContentType(nsAString& aContentType);
964 * Set the Content-Type of this document.
966 void SetContentType(const nsACString& aContentType);
969 * Return the language of this document, or null if not set.
971 nsAtom* GetContentLanguage() const { return mContentLanguage.get(); }
973 void GetContentLanguageForBindings(DOMString&) const;
975 // The states BidiEnabled and MathMLEnabled should persist across multiple
976 // views (screen, print) of the same document.
979 * Check if the document contains bidi data.
980 * If so, we have to apply the Unicode Bidi Algorithm.
982 bool GetBidiEnabled() const { return mBidiEnabled; }
985 * Indicate the document contains bidi data.
986 * Currently, we cannot disable bidi, because once bidi is enabled,
987 * it affects a frame model irreversibly, and plays even though
988 * the document no longer contains bidi data.
990 void SetBidiEnabled() { mBidiEnabled = true; }
992 void SetMathMLEnabled() { mMathMLEnabled = true; }
995 * Ask this document whether it's the initial document in its window.
997 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
1000 * Ask this document whether it has ever been a initial document in its
1001 * window.
1003 bool IsEverInitialDocument() const { return mIsEverInitialDocumentInWindow; }
1006 * Tell this document that it's the initial document in its window. See
1007 * comments on mIsInitialDocumentInWindow for when this should be called.
1009 void SetIsInitialDocument(bool aIsInitialDocument);
1011 void SetLoadedAsData(bool aLoadedAsData, bool aConsiderForMemoryReporting);
1013 TimeStamp GetLoadingOrRestoredFromBFCacheTimeStamp() const {
1014 return mLoadingOrRestoredFromBFCacheTimeStamp;
1016 void SetLoadingOrRestoredFromBFCacheTimeStampToNow() {
1017 mLoadingOrRestoredFromBFCacheTimeStamp = TimeStamp::Now();
1021 * Normally we assert if a runnable labeled with one DocGroup touches data
1022 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1023 * means that we can touch that document from any DocGroup without asserting.
1025 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1028 * Get the bidi options for this document.
1029 * @see nsBidiUtils.h
1031 uint32_t GetBidiOptions() const { return mBidiOptions; }
1034 * Set the bidi options for this document. This just sets the bits;
1035 * callers are expected to take action as needed if they want this
1036 * change to actually change anything immediately.
1037 * @see nsBidiUtils.h
1039 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1042 * Returns true if the document holds a CSP
1043 * delivered through an HTTP Header.
1045 bool GetHasCSPDeliveredThroughHeader() {
1046 return mHasCSPDeliveredThroughHeader;
1050 * Return a promise which resolves to the content blocking events.
1052 using GetContentBlockingEventsPromise = MozPromise<uint32_t, bool, true>;
1053 [[nodiscard]] RefPtr<GetContentBlockingEventsPromise>
1054 GetContentBlockingEvents();
1057 * Get the sandbox flags for this document.
1058 * @see nsSandboxFlags.h for the possible flags
1060 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1062 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1063 return mEmbedderPolicy;
1066 void SetEmbedderPolicy(
1067 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1068 mEmbedderPolicy = aCOEP;
1072 * Get string representation of sandbox flags (null if no flags are set)
1074 void GetSandboxFlagsAsString(nsAString& aFlags);
1077 * Set the sandbox flags for this document.
1078 * @see nsSandboxFlags.h for the possible flags
1080 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1083 * Called when the document was decoded as UTF-8 and decoder encountered no
1084 * errors.
1086 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1089 * Called to disable client access to cookies through the document.cookie API
1090 * from user JavaScript code.
1092 void DisableCookieAccess() { mDisableCookieAccess = true; }
1094 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1095 bool LinkHandlingEnabled() { return mLinksEnabled; }
1098 * Set compatibility mode for this document
1100 void SetCompatibilityMode(nsCompatibility aMode);
1103 * Called to disable client access to document.write() API from user
1104 * JavaScript code.
1106 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1109 * Whether a document.write() call is in progress.
1111 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1114 * Access HTTP header data (this may also get set from other
1115 * sources, like HTML META tags).
1117 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1118 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1121 * Set Early Hint data, moves the arrays into the function, leaving the
1122 * passed variables empty
1124 void SetEarlyHints(nsTArray<net::EarlyHintConnectArgs>&& aEarlyHints);
1125 const nsTArray<net::EarlyHintConnectArgs>& GetEarlyHints() const {
1126 return mEarlyHints;
1130 * Create a new presentation shell that will use aContext for its
1131 * presentation context (presentation contexts <b>must not</b> be
1132 * shared among multiple presentation shells). The caller of this
1133 * method is responsible for calling BeginObservingDocument() on the
1134 * presshell if the presshell should observe document mutations.
1136 MOZ_CAN_RUN_SCRIPT already_AddRefed<PresShell> CreatePresShell(
1137 nsPresContext* aContext, nsViewManager* aViewManager);
1138 void DeletePresShell();
1140 PresShell* GetPresShell() const {
1141 return GetBFCacheEntry() ? nullptr : mPresShell;
1144 inline PresShell* GetObservingPresShell() const;
1146 // Return whether the presshell for this document is safe to flush.
1147 bool IsSafeToFlush() const;
1149 inline nsPresContext* GetPresContext() const;
1151 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1153 // Instead using this method, what you probably want is
1154 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1155 void DisallowBFCaching(uint32_t aStatus = BFCacheStatus::NOT_ALLOWED);
1157 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1159 // Accepts null to clear the BFCache entry too.
1160 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1162 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1164 // Removes this document from the BFCache, if it is cached, and returns
1165 // true if it was.
1166 bool RemoveFromBFCacheSync();
1169 * Return the parent document of this document. Will return null
1170 * unless this document is within a compound document and has a
1171 * parent. Note that this parent chain may cross chrome boundaries.
1173 Document* GetInProcessParentDocument() const { return mParentDocument; }
1176 * Set the parent document of this document.
1178 void SetParentDocument(Document* aParent) {
1179 mParentDocument = aParent;
1180 if (aParent) {
1181 RecomputeResistFingerprinting();
1182 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1186 void SetCurrentContextPaint(const SVGContextPaint* aContextPaint) {
1187 mCurrentContextPaint = aContextPaint;
1190 const SVGContextPaint* GetCurrentContextPaint() const {
1191 return mCurrentContextPaint;
1195 * Set the sub document for aContent to aSubDoc.
1197 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1200 * Get the sub document for aContent
1202 Document* GetSubDocumentFor(nsIContent* aContent) const;
1205 * Get the content node for which this document is a sub document.
1207 Element* GetEmbedderElement() const;
1210 * Return the doctype for this document.
1212 DocumentType* GetDoctype() const;
1215 * Return the root element for this document.
1217 Element* GetRootElement() const;
1219 Selection* GetSelection(ErrorResult& aRv);
1221 void MakeBrowsingContextNonSynthetic();
1222 nsresult HasStorageAccessSync(bool& aHasStorageAccess);
1223 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1225 StorageAccessAPIHelper::PerformPermissionGrant CreatePermissionGrantPromise(
1226 nsPIDOMWindowInner* aInnerWindow, nsIPrincipal* aPrincipal,
1227 bool aHasUserInteraction, bool aRequireUserInteraction,
1228 const Maybe<nsCString>& aTopLevelBaseDomain, bool aFrameOnly);
1230 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1232 already_AddRefed<Promise> RequestStorageAccessForOrigin(
1233 const nsAString& aThirdPartyOrigin, const bool aRequireUserInteraction,
1234 ErrorResult& aRv);
1236 already_AddRefed<Promise> RequestStorageAccessUnderSite(
1237 const nsAString& aSerializedSite, ErrorResult& aRv);
1238 already_AddRefed<Promise> CompleteStorageAccessRequestFromSite(
1239 const nsAString& aSerializedOrigin, ErrorResult& aRv);
1241 bool UseRegularPrincipal() const;
1244 * Gets the event target to dispatch key events to if there is no focused
1245 * content in the document.
1247 virtual Element* GetUnfocusedKeyEventTarget();
1250 * Retrieve information about the viewport as a data structure.
1251 * This will return information in the viewport META data section
1252 * of the document. This can be used in lieu of ProcessViewportInfo(),
1253 * which places the viewport information in the document header instead
1254 * of returning it directly.
1256 * @param aDisplaySize size of the on-screen display area for this
1257 * document, in device pixels.
1259 * NOTE: If the site is optimized for mobile (via the doctype), this
1260 * will return viewport information that specifies default information.
1262 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1264 void SetMetaViewportData(UniquePtr<ViewportMetaData> aData);
1266 // Returns a ViewportMetaData for this document.
1267 ViewportMetaData GetViewportMetaData() const;
1270 * True iff this doc will ignore manual character encoding overrides.
1272 virtual bool WillIgnoreCharsetOverride() { return true; }
1275 * Return whether the document was created by a srcdoc iframe.
1277 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1280 * Sets whether the document was created by a srcdoc iframe.
1282 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1283 mIsSrcdocDocument = aIsSrcdocDocument;
1287 * Gets the srcdoc string from within the channel (assuming both exist).
1288 * Returns a void string if this isn't a srcdoc document or if
1289 * the channel has not been set.
1291 nsresult GetSrcdocData(nsAString& aSrcdocData);
1293 already_AddRefed<AnonymousContent> InsertAnonymousContent(bool aForce,
1294 ErrorResult&);
1295 void RemoveAnonymousContent(AnonymousContent&);
1297 * If aNode is a descendant of anonymous content inserted by
1298 * InsertAnonymousContent, this method returns the root element of the
1299 * inserted anonymous content (in other words, the clone of the aElement
1300 * that was passed to InsertAnonymousContent).
1302 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1303 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1304 return mAnonymousContents;
1307 TimeStamp GetPageUnloadingEventTimeStamp() const {
1308 if (!mParentDocument) {
1309 return mPageUnloadingEventTimeStamp;
1312 TimeStamp parentTimeStamp(
1313 mParentDocument->GetPageUnloadingEventTimeStamp());
1314 if (parentTimeStamp.IsNull()) {
1315 return mPageUnloadingEventTimeStamp;
1318 if (!mPageUnloadingEventTimeStamp ||
1319 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1320 return parentTimeStamp;
1323 return mPageUnloadingEventTimeStamp;
1326 void NotifyLayerManagerRecreated();
1328 // Add an element to the list of elements that need their mapped attributes
1329 // resolved to a declaration block.
1331 // These are weak pointers, manually unschedule them when an element is
1332 // removed from the tree.
1333 void ScheduleForPresAttrEvaluation(Element* aElement);
1335 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1336 // generally when it's unbound from the tree.
1337 void UnscheduleForPresAttrEvaluation(Element* aElement);
1339 // Resolve all presentational attributes scheduled in
1340 // ScheduleForPresAttrEvaluation
1341 void ResolveScheduledPresAttrs() {
1342 if (mLazyPresElements.IsEmpty()) {
1343 return;
1345 DoResolveScheduledPresAttrs();
1348 Maybe<ClientInfo> GetClientInfo() const;
1349 Maybe<ClientState> GetClientState() const;
1350 Maybe<ServiceWorkerDescriptor> GetController() const;
1352 // Given a node, get a weak reference to it and append that reference to
1353 // mBlockedNodesByClassifier. Can be used later on to look up a node in it.
1354 // (e.g., by the UI)
1355 // /
1356 void AddBlockedNodeByClassifier(nsINode* aNode) {
1357 if (aNode) {
1358 mBlockedNodesByClassifier.AppendElement(do_GetWeakReference(aNode));
1362 // Returns the size of the mBlockedNodesByClassifier array.
1364 // This array contains nodes that have been blocked to prevent user tracking,
1365 // fingerprinting, cryptomining, etc. They most likely have had their
1366 // nsIChannel canceled by the URL classifier (Safebrowsing).
1368 // A script can subsequently use GetBlockedNodesByClassifier()
1369 // to get a list of references to these nodes.
1371 // Note:
1372 // This expresses how many tracking nodes have been blocked for this document
1373 // since its beginning, not how many of them are still around in the DOM tree.
1374 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1375 // array but they are not removed when those nodes are removed from the tree
1376 // or even garbage collected.
1377 size_t BlockedNodeByClassifierCount() const {
1378 return mBlockedNodesByClassifier.Length();
1381 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1382 // This array contains nodes that have been blocked to prevent
1383 // user tracking. They most likely have had their nsIChannel
1384 // canceled by the URL classifier (Safebrowsing).
1385 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1387 // Helper method that returns true if the document has storage-access sandbox
1388 // flag.
1389 bool StorageAccessSandboxed() const;
1391 // Helper method that returns true if storage access API is enabled and
1392 // the passed flag has storage-access sandbox flag.
1393 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1395 // Returns the cookie jar settings for this and sub contexts.
1396 nsICookieJarSettings* CookieJarSettings();
1398 // Returns whether this document is using unpartitioned cookies
1399 bool UsingStorageAccess();
1401 // Returns whether the storage access permission of the document is granted by
1402 // the allow list.
1403 bool HasStorageAccessPermissionGrantedByAllowList();
1405 // Increments the document generation.
1406 inline void Changed() { ++mGeneration; }
1408 // Returns the current generation.
1409 inline int32_t GetGeneration() const { return mGeneration; }
1411 // Adds cached sizes values to aSizes if there's any
1412 // cached value and if the document generation hasn't
1413 // changed since the cache was created.
1414 // Returns true if sizes were added.
1415 bool GetCachedSizes(nsTabSizes* aSizes);
1417 // Sets the cache sizes for the current generation.
1418 void SetCachedSizes(nsTabSizes* aSizes);
1421 * Should be called when an element's editable changes as a result of
1422 * changing its contentEditable attribute/property.
1424 * The change should be +1 if the contentEditable attribute/property was
1425 * changed to true, -1 if it was changed to false.
1427 void ChangeContentEditableCount(Element*, int32_t aChange);
1428 MOZ_CAN_RUN_SCRIPT void DeferredContentEditableCountChange(Element*);
1430 enum class EditingState : int8_t {
1431 eTearingDown = -2,
1432 eSettingUp = -1,
1433 eOff = 0,
1434 eDesignMode,
1435 eContentEditable
1439 * Returns the editing state of the document (not editable, contentEditable or
1440 * designMode).
1442 EditingState GetEditingState() const { return mEditingState; }
1445 * Returns whether the document is editable.
1447 bool IsEditingOn() const {
1448 return GetEditingState() == EditingState::eDesignMode ||
1449 GetEditingState() == EditingState::eContentEditable;
1452 class MOZ_STACK_CLASS nsAutoEditingState {
1453 public:
1454 nsAutoEditingState(Document* aDoc, EditingState aState)
1455 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1456 aDoc->mEditingState = aState;
1458 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1460 private:
1461 RefPtr<Document> mDoc;
1462 EditingState mSavedState;
1464 friend class nsAutoEditingState;
1467 * Set the editing state of the document. Don't use this if you want
1468 * to enable/disable editing, call EditingStateChanged() or
1469 * SetDesignMode().
1471 void SetEditingState(EditingState aState) { mEditingState = aState; }
1474 * Called when this Document's editor is destroyed.
1476 void TearingDownEditor();
1478 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1480 // Gets the next form number.
1482 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1483 // parser inserted form element.
1484 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1486 // Gets the next form control number.
1488 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1489 // parser inserted form control element.
1490 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1492 PreloadService& Preloads() { return mPreloadService; }
1494 bool HasThirdPartyChannel();
1496 bool ShouldIncludeInTelemetry() const;
1498 void AddMediaElementWithMSE();
1499 void RemoveMediaElementWithMSE();
1501 void DoNotifyPossibleTitleChange();
1503 void InitFeaturePolicy();
1504 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1506 void EnsureNotEnteringAndExitFullscreen();
1508 protected:
1509 friend class nsUnblockOnloadEvent;
1511 nsresult InitCSP(nsIChannel* aChannel);
1512 nsresult InitCOEP(nsIChannel* aChannel);
1514 nsresult InitReferrerInfo(nsIChannel* aChannel);
1516 void PostUnblockOnloadEvent();
1518 void DoUnblockOnload();
1520 void DoResolveScheduledPresAttrs();
1522 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1524 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1525 NotNull<const Encoding*>& aEncoding,
1526 nsHtml5TreeOpExecutor* aExecutor);
1528 MOZ_CAN_RUN_SCRIPT void DispatchContentLoadedEvents();
1530 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1531 MOZ_CAN_RUN_SCRIPT_BOUNDARY void DispatchPageTransition(
1532 EventTarget* aDispatchTarget, const nsAString& aType, bool aInFrameSwap,
1533 bool aPersisted, bool aOnlySystemGroup);
1535 // Call this before the document does something that will unbind all content.
1536 // That will stop us from doing a lot of work as each element is removed.
1537 void DestroyElementMaps();
1539 Element* GetRootElementInternal() const;
1541 void SetPageUnloadingEventTimeStamp() {
1542 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1543 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1546 void CleanUnloadEventsTimeStamp() {
1547 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1548 mPageUnloadingEventTimeStamp = TimeStamp();
1552 * Clears any Servo element data stored on Elements in the document.
1554 void ClearStaleServoData();
1557 * Do the tree-disconnection that ResetToURI and document.open need to do.
1559 void DisconnectNodeTree();
1562 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1563 * "CheckKeyPressEventModel" event to check whether we should dispatch
1564 * keypress events in confluent model or split model. This should be
1565 * called only when mEditingState is changed to eDesignMode or
1566 * eConentEditable at first time.
1568 void MaybeDispatchCheckKeyPressEventModelEvent();
1570 /* Midas implementation */
1571 nsCommandManager* GetMidasCommandManager();
1573 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1575 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1576 // of places, and I'm pretty sure the exact ExecCommand call it
1577 // makes cannot actually run script.
1578 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1580 void MaybeEditingStateChanged();
1582 public:
1583 // Get the root <html> element, or return null if there isn't one (e.g.
1584 // if the root isn't <html>)
1585 Element* GetHtmlElement() const;
1586 // Returns the first child of GetHtmlContent which has the given tag,
1587 // or nullptr if that doesn't exist.
1588 Element* GetHtmlChildElement(nsAtom* aTag);
1589 // Get the canonical <body> element, or return null if there isn't one (e.g.
1590 // if the root isn't <html> or if the <body> isn't there)
1591 HTMLBodyElement* GetBodyElement();
1592 // Get the canonical <head> element, or return null if there isn't one (e.g.
1593 // if the root isn't <html> or if the <head> isn't there)
1594 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1595 // Get the "body" in the sense of document.body: The first <body> or
1596 // <frameset> that's a child of a root <html>
1597 nsGenericHTMLElement* GetBody();
1598 // Set the "body" in the sense of document.body.
1599 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1600 // Get the "head" element in the sense of document.head.
1601 HTMLSharedElement* GetHead();
1603 ServoStyleSet* StyleSetForPresShell() const {
1604 MOZ_ASSERT(!!mStyleSet.get());
1605 return mStyleSet.get();
1608 inline ServoStyleSet& EnsureStyleSet() const;
1610 // ShadowRoot has APIs that can change styles. This notifies the shell that
1611 // stlyes applicable in the shadow tree have potentially changed.
1612 void RecordShadowStyleChange(ShadowRoot&);
1614 // Needs to be called any time the applicable style can has changed, in order
1615 // to schedule a style flush and setup all the relevant state.
1617 // If we know the stylesheet change applies only to a shadow tree we can avoid
1618 // some work (like updating the font-face-set / counter-styles / etc, as those
1619 // are global).
1620 void ApplicableStylesChanged(bool aKnownInShadowTree = false);
1622 // Whether we filled the style set with any style sheet. Only meant to be used
1623 // from DocumentOrShadowRoot::Traverse.
1624 bool StyleSetFilled() const { return mStyleSetFilled; }
1627 * Accessors to the collection of stylesheets owned by this document.
1628 * Style sheets are ordered, most significant last.
1631 void InsertSheetAt(size_t aIndex, StyleSheet&);
1634 * Add a stylesheet to the document
1636 * TODO(emilio): This is only used by parts of editor that are no longer in
1637 * use by m-c or c-c, so remove.
1639 void AddStyleSheet(StyleSheet* aSheet) {
1640 MOZ_ASSERT(aSheet);
1641 InsertSheetAt(SheetCount(), *aSheet);
1645 * Notify the document that the applicable state of the sheet changed
1646 * and that observers should be notified and style sets updated
1648 void StyleSheetApplicableStateChanged(StyleSheet&);
1649 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1650 void PostStyleSheetRemovedEvent(StyleSheet&);
1651 void PostCustomPropertyRegistered(const dom::PropertyDefinition&);
1653 enum additionalSheetType {
1654 eAgentSheet,
1655 eUserSheet,
1656 eAuthorSheet,
1657 AdditionalSheetTypeCount
1660 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1661 nsIURI* aSheetURI);
1662 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1663 StyleSheet* aSheet);
1664 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1666 StyleSheet* GetFirstAdditionalAuthorSheet() {
1667 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1671 * Returns the index that aSheet should be inserted at to maintain document
1672 * ordering.
1674 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1677 * Get this document's CSSLoader. This is guaranteed to not return null.
1679 css::Loader* CSSLoader() const { return mCSSLoader; }
1682 * Get this document's StyleImageLoader. This is guaranteed to not return
1683 * null.
1685 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1688 * Get the channel that was passed to StartDocumentLoad or Reset for this
1689 * document. Note that this may be null in some cases (eg if
1690 * StartDocumentLoad or Reset were never called)
1692 nsIChannel* GetChannel() const { return mChannel; }
1695 * Get this document's attribute stylesheet. May return null if
1696 * there isn't one.
1698 AttributeStyles* GetAttributeStyles() const { return mAttributeStyles.get(); }
1700 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1703 * Get/set the object from which the context for the event/script handling can
1704 * be got. Normally GetScriptHandlingObject() returns the same object as
1705 * GetScriptGlobalObject(), but if the document is loaded as data,
1706 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1707 * aHasHadScriptHandlingObject is set true if document has had the object
1708 * for event/script handling. Do not process any events/script if the method
1709 * returns null, but aHasHadScriptHandlingObject is true.
1711 nsIScriptGlobalObject* GetScriptHandlingObject(
1712 bool& aHasHadScriptHandlingObject) const {
1713 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1714 return mScriptGlobalObject ? mScriptGlobalObject.get()
1715 : GetScriptHandlingObjectInternal();
1717 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1720 * Get the object that is used as the scope for all of the content
1721 * wrappers whose owner document is this document. Unlike the script global
1722 * object, this will only return null when the global object for this
1723 * document is truly gone. Use this object when you're trying to find a
1724 * content wrapper in XPConnect.
1726 nsIGlobalObject* GetScopeObject() const;
1727 void SetScopeObject(nsIGlobalObject* aGlobal);
1730 * Return the window containing the document (the outer window).
1732 nsPIDOMWindowOuter* GetWindow() const {
1733 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1736 bool IsInBackgroundWindow() const {
1737 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1738 return outer && outer->IsBackground();
1742 * Return the inner window used as the script compilation scope for
1743 * this document. If you're not absolutely sure you need this, use
1744 * GetWindow().
1746 nsPIDOMWindowInner* GetInnerWindow() const {
1747 return mRemovedFromDocShell ? nullptr : mWindow;
1751 * Return the outer window ID.
1753 uint64_t OuterWindowID() const {
1754 nsPIDOMWindowOuter* window = GetWindow();
1755 return window ? window->WindowID() : 0;
1759 * Return the inner window ID.
1761 uint64_t InnerWindowID() const {
1762 nsPIDOMWindowInner* window = GetInnerWindow();
1763 return window ? window->WindowID() : 0;
1767 * Return WindowGlobalChild that is associated with the inner window.
1769 WindowGlobalChild* GetWindowGlobalChild() {
1770 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1771 : nullptr;
1775 * Return WindowContext associated with the inner window.
1777 WindowContext* GetWindowContext() const {
1778 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1781 bool IsTopLevelWindowInactive() const {
1782 return mState.HasState(DocumentState::WINDOW_INACTIVE);
1786 * Get the script loader for this document
1788 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1791 * Add/Remove an element to the document's id and name hashes
1793 void AddToIdTable(Element* aElement, nsAtom* aId);
1794 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1795 void AddToNameTable(Element* aElement, nsAtom* aName);
1796 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1799 * Returns all elements in the top layer in the insertion order.
1801 nsTArray<Element*> GetTopLayer() const;
1803 bool TopLayerContains(Element&) const;
1805 // Do the "fullscreen element ready check" from the fullscreen spec.
1806 // It returns true if the given element is allowed to go into fullscreen.
1807 // It is responsive to dispatch "fullscreenerror" event when necessary.
1808 bool FullscreenElementReadyCheck(FullscreenRequest&);
1811 * When this is called on content process, this asynchronously requests that
1812 * the document make aElement the fullscreen element, and move into fullscreen
1813 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1814 * and it can be returned to fullscreen status by calling
1815 * RestorePreviousFullscreenState().
1816 * If on chrome process, this is synchronously.
1818 * Note that requesting fullscreen in a document also makes the element which
1819 * contains this document in this document's parent document fullscreen. i.e.
1820 * the <iframe> or <browser> that contains this document is also mode
1821 * fullscreen. This happens recursively in all ancestor documents.
1823 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1824 bool aApplyFullscreenDirectly = false);
1826 private:
1827 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1828 bool aApplyFullscreenDirectly);
1829 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1830 bool aApplyFullscreenDirectly);
1832 // Pushes aElement onto the top layer
1833 void TopLayerPush(Element&);
1835 // Removes the topmost element for which aPredicate returns true from the top
1836 // layer. The removed element, if any, is returned.
1837 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicate);
1839 // Removes the given element from the top layer. The removed element, if any,
1840 // is returned.
1841 Element* TopLayerPop(Element&);
1843 MOZ_CAN_RUN_SCRIPT bool TryAutoFocusCandidate(Element& aElement);
1845 public:
1846 // Removes all the elements with fullscreen flag set from the top layer, and
1847 // clears their fullscreen flag.
1848 void CleanupFullscreenState();
1850 // Pops the fullscreen element from the top layer and clears its
1851 // fullscreen flag. Returns whether there was any fullscreen element.
1852 enum class UpdateViewport : bool { No, Yes };
1853 bool PopFullscreenElement(UpdateViewport = UpdateViewport::Yes);
1855 // Pushes the given element into the top of top layer and set fullscreen
1856 // flag.
1857 void SetFullscreenElement(Element&);
1859 // Whether we has pending fullscreen request.
1860 bool HasPendingFullscreenRequests();
1863 * When Esc key is pressed, cancel the dialog element if the document is
1864 * blocked by the dialog or hide popover if popover is shown.
1866 MOZ_CAN_RUN_SCRIPT void HandleEscKey();
1868 void AddModalDialog(HTMLDialogElement&);
1869 void RemoveModalDialog(HTMLDialogElement&);
1872 * Called when a frame in a child process has entered fullscreen or when a
1873 * fullscreen frame in a child process changes to another origin.
1874 * aFrameElement is the frame element which contains the child-process
1875 * fullscreen document.
1877 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1880 * Called when a frame in a remote child document has rolled back fullscreen
1881 * so that all its top layer are empty; we must continue the
1882 * rollback in this parent process' doc tree branch which is fullscreen.
1883 * Note that only one branch of the document tree can have its documents in
1884 * fullscreen state at one time. We're in inconsistent state if a
1885 * fullscreen document has a parent and that parent isn't fullscreen. We
1886 * preserve this property across process boundaries.
1888 void RemoteFrameFullscreenReverted();
1891 * Restores the previous fullscreen element to fullscreen status. If there
1892 * is no former fullscreen element, this exits fullscreen, moving the
1893 * top-level browser window out of fullscreen mode.
1895 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1898 * Returns true if this document is a fullscreen leaf document, i.e. it
1899 * is in fullscreen mode and has no fullscreen children.
1901 bool IsFullscreenLeaf();
1904 * Returns the document which is at the root of this document's branch
1905 * in the in-process document tree. Returns nullptr if the document isn't
1906 * fullscreen.
1908 Document* GetFullscreenRoot() const { return mFullscreenRoot; }
1910 size_t CountFullscreenElements() const;
1913 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1914 * in this document.
1916 void SetFullscreenRoot(Document* aRoot) { mFullscreenRoot = aRoot; }
1919 * Synchronously cleans up the fullscreen state on the given document.
1921 * Calling this without performing fullscreen transition could lead
1922 * to undesired effect (the transition happens after document state
1923 * flips), hence it should only be called either by nsGlobalWindow
1924 * when we have performed the transition, or when it is necessary to
1925 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1926 * should be called instead.
1928 * aDocument must not be null.
1930 static void ExitFullscreenInDocTree(Document* aDocument);
1933 * Ask the document to exit fullscreen state asynchronously.
1935 * Different from ExitFullscreenInDocTree(), this allows the window
1936 * to perform fullscreen transition first if any.
1938 * If aDocument is null, it will exit fullscreen from all documents
1939 * in all windows.
1941 static void AsyncExitFullscreen(Document* aDocument);
1944 * Handles any pending fullscreen in aDocument or its subdocuments.
1946 * Returns whether there is any fullscreen request handled.
1948 static bool HandlePendingFullscreenRequests(Document* aDocument);
1951 * Clear pending fullscreen in aDocument.
1953 static void ClearPendingFullscreenRequests(Document* aDocument);
1955 // ScreenOrientation related APIs
1957 void ClearOrientationPendingPromise();
1958 bool SetOrientationPendingPromise(Promise* aPromise);
1959 Promise* GetOrientationPendingPromise() const {
1960 return mOrientationPendingPromise;
1963 //----------------------------------------------------------------------
1965 // Document notification API's
1968 * Add a new observer of document change notifications. Whenever
1969 * content is changed, appended, inserted or removed the observers are
1970 * informed. An observer that is already observing the document must
1971 * not be added without being removed first.
1973 void AddObserver(nsIDocumentObserver* aObserver);
1976 * Remove an observer of document change notifications. This will
1977 * return false if the observer cannot be found.
1979 bool RemoveObserver(nsIDocumentObserver* aObserver);
1981 // Observation hooks used to propagate notifications to document observers.
1982 // BeginUpdate must be called before any batch of modifications of the
1983 // content model or of style data, EndUpdate must be called afterward.
1984 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1985 void BeginUpdate();
1986 void EndUpdate();
1987 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
1989 void BeginLoad();
1990 virtual void EndLoad();
1992 enum ReadyState {
1993 READYSTATE_UNINITIALIZED = 0,
1994 READYSTATE_LOADING = 1,
1995 READYSTATE_INTERACTIVE = 3,
1996 READYSTATE_COMPLETE = 4
1998 // Set the readystate of the document. If aUpdateTimingInformation is true,
1999 // this will record relevant timestamps in the document's performance timing.
2000 // Some consumers (document.open is the only one right now, actually) don't
2001 // want to do that, though.
2002 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2003 ReadyState GetReadyStateEnum() { return mReadyState; }
2005 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2006 ReadyState aNewState);
2008 void NotifyAbortedLoad();
2010 // Notify that an element changed state. This must happen under a
2011 // scriptblocker but NOT within a begin/end update.
2012 void ElementStateChanged(Element*, ElementState);
2014 // Update a set of document states that may have changed.
2015 // This should only be called by callers whose state is also reflected in the
2016 // implementation of Document::State.
2018 // aNotify controls whether we notify our DocumentStatesChanged observers.
2019 void UpdateDocumentStates(DocumentState aMaybeChangedStates, bool aNotify);
2021 void ResetDocumentDirection();
2023 // Observation hooks for style data to propagate notifications
2024 // to document observers
2025 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2026 void RuleAdded(StyleSheet&, css::Rule&);
2027 void RuleRemoved(StyleSheet&, css::Rule&);
2028 void SheetCloned(StyleSheet&) {}
2029 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2032 * Flush notifications for this document and its parent documents
2033 * (since those may affect the layout of this one).
2035 void FlushPendingNotifications(FlushType aType);
2038 * Another variant of the above FlushPendingNotifications. This function
2039 * takes a ChangesToFlush to specify whether throttled animations are flushed
2040 * or not.
2041 * If in doubt, use the above FlushPendingNotifications.
2043 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2044 void FlushPendingNotifications(ChangesToFlush aFlush);
2047 * Calls FlushPendingNotifications on any external resources this document
2048 * has. If this document has no external resources or is an external resource
2049 * itself this does nothing. This should only be called with
2050 * aType >= FlushType::Style.
2052 void FlushExternalResources(FlushType aType);
2054 void AddWorkerDocumentListener(WorkerDocumentListener* aListener);
2055 void RemoveWorkerDocumentListener(WorkerDocumentListener* aListener);
2057 // Triggers an update of <svg:use> element shadow trees.
2058 void UpdateSVGUseElementShadowTrees() {
2059 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2060 return;
2062 DoUpdateSVGUseElementShadowTrees();
2066 * Only to be used inside Gecko, you can't really do anything with the
2067 * pointer outside Gecko anyway.
2069 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2072 * Reset the document using the given channel and loadgroup. This works
2073 * like ResetToURI, but also sets the document's channel to aChannel.
2074 * The principal of the document will be set from the channel.
2076 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2079 * Reset this document to aURI, aLoadGroup, aPrincipal and
2080 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2081 * content principal based on aURI will be used.
2083 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2084 nsIPrincipal* aPrincipal,
2085 nsIPrincipal* aPartitionedPrincipal);
2088 * Set the container (docshell) for this document. Virtual so that
2089 * docshell can call it.
2091 virtual void SetContainer(nsDocShell* aContainer);
2094 * Get the container (docshell) for this document.
2096 nsISupports* GetContainer() const;
2099 * Get the container's load context for this document.
2101 nsILoadContext* GetLoadContext() const;
2104 * Get docshell the for this document.
2106 nsIDocShell* GetDocShell() const;
2109 * Set and get XML declaration. If aVersion is null there is no declaration.
2110 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2111 * was no standalone parameter in the declaration, that it was given as no,
2112 * or that it was given as yes.
2114 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2115 const int32_t aStandalone);
2116 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2117 nsAString& Standalone);
2120 * Returns the bits for the color-scheme specified by the
2121 * <meta name="color-scheme">.
2123 uint8_t GetColorSchemeBits() const { return mColorSchemeBits; }
2126 * Traverses the DOM and computes the supported color schemes as per
2127 * https://html.spec.whatwg.org/#meta-color-scheme
2129 void RecomputeColorScheme();
2130 void AddColorSchemeMeta(HTMLMetaElement&);
2131 void RemoveColorSchemeMeta(HTMLMetaElement&);
2134 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2135 * regular HTML document with Content-Type "text/html", image documents and
2136 * media documents). Returns false for XHTML and any other documents parsed
2137 * by the XML parser.
2139 bool IsHTMLDocument() const { return mType == eHTML; }
2140 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2141 bool IsImageDocument() const {
2142 return MediaDocumentKind() == MediaDocumentKind::Image;
2144 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2145 bool IsSVGDocument() const { return mType == eSVG; }
2146 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2147 bool LoadsFullXULStyleSheetUpFront() {
2148 if (IsSVGDocument()) {
2149 return false;
2151 return AllowXULXBL();
2154 bool IsScriptEnabled() const;
2157 * Returns true if this document was created from a nsXULPrototypeDocument.
2159 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2161 * Returns the prototype the document was created from, or null if it was not
2162 * created from a prototype.
2164 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2166 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2167 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2168 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2171 bool IsContentDocument() const { return mIsContentDocument; }
2172 void SetIsContentDocument(bool aIsContentDocument) {
2173 mIsContentDocument = aIsContentDocument;
2176 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2178 * Create an element with the specified name, prefix and namespace ID.
2179 * Returns null if element name parsing failed.
2181 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2182 int32_t aNamespaceID,
2183 const nsAString* aIs = nullptr);
2186 * Get the security info (i.e. SSL state etc) that the document got
2187 * from the channel/document that created the content of the
2188 * document.
2190 * @see nsIChannel
2192 nsITransportSecurityInfo* GetSecurityInfo() { return mSecurityInfo; }
2195 * Get the channel that failed to load and resulted in an error page, if it
2196 * exists. This is only relevant to error pages.
2198 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2201 * This function checks if the document that is trying to access
2202 * GetNetErrorInfo is a trusted about net error page or not.
2204 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2207 * This function checks if the document that is trying to access
2208 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2210 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext* aCx,
2211 JSObject* aObject);
2214 * Get security info like error code for a failed channel. This
2215 * property is only exposed to about:neterror documents.
2217 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2220 * This function checks if the document that is trying to access
2221 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2223 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2226 * This function checks if the privilege storage access api is available for
2227 * the caller. We only allow privilege SSA to be called by system principal
2228 * and webcompat extension.
2230 static bool CallerCanAccessPrivilegeSSA(JSContext* aCx, JSObject* aObject);
2233 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2234 * failed Channel. This property is only exposed for about:certerror
2235 * documents.
2237 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2238 ErrorResult& aRv);
2241 * Set the channel that failed to load and resulted in an error page.
2242 * This is only relevant to error pages.
2244 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2247 * Returns the default namespace ID used for elements created in this
2248 * document.
2250 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2252 void RemoveAllProperties();
2253 void RemoveAllPropertiesFor(nsINode* aNode);
2255 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2258 * Sets the ID used to identify this part of the multipart document
2260 void SetPartID(uint32_t aID) { mPartID = aID; }
2263 * Return the ID used to identify this part of the multipart document
2265 uint32_t GetPartID() const { return mPartID; }
2268 * Sanitize the document by resetting all input elements and forms that have
2269 * autocomplete=off to their default values.
2270 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2272 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Sanitize();
2275 * Enumerate all subdocuments.
2276 * The enumerator callback should return CallState::Continue to continue
2277 * enumerating, or CallState::Stop to stop. This will never get passed a null
2278 * aDocument.
2280 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2281 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2284 * Collect all the descendant documents for which |aCalback| returns true.
2285 * The callback function must not mutate any state for the given document.
2287 using nsDocTestFunc = bool (*)(const Document* aDocument);
2288 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2289 nsDocTestFunc aCallback) const;
2292 * Check whether it is safe to cache the presentation of this document
2293 * and all of its subdocuments (depending on the 3rd param). This method
2294 * checks the following conditions recursively:
2295 * - Some document types, such as plugin documents, cannot be safely cached.
2296 * - If there are any pending requests, we don't allow the presentation
2297 * to be cached. Ideally these requests would be suspended and resumed,
2298 * but that is difficult in some cases, such as XMLHttpRequest.
2299 * - If there are any beforeunload or unload listeners, we must fire them
2300 * for correctness, but this likely puts the document into a state where
2301 * it would not function correctly if restored.
2303 * |aNewRequest| should be the request for a new document which will
2304 * replace this document in the docshell. The new document's request
2305 * will be ignored when checking for active requests. If there is no
2306 * request associated with the new document, this parameter may be null.
2308 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2309 * combination is when we try to BFCache aNewRequest
2311 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2312 uint32_t& aBFCacheCombo,
2313 bool aIncludeSubdocuments,
2314 bool aAllowUnloadListeners = true);
2317 * Pass principals if the correct ones are known when calling Init. That way
2318 * NodeInfoManager doesn't need to create a temporary null principal.
2320 virtual nsresult Init(nsIPrincipal* aPrincipal,
2321 nsIPrincipal* aPartitionedPrincipal);
2324 * Notify the document that its associated ContentViewer is being destroyed.
2325 * This releases circular references so that the document can go away.
2326 * Destroy() is only called on documents that have a content viewer.
2328 virtual void Destroy();
2331 * Notify the document that its associated ContentViewer is no longer
2332 * the current viewer for the docshell. The document might still
2333 * be rendered in "zombie state" until the next document is ready.
2334 * The document should save form control state.
2336 void RemovedFromDocShell();
2339 * Get the layout history state that should be used to save and restore state
2340 * for nodes in this document. This may return null; if that happens state
2341 * saving and restoration is not possible.
2343 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2346 * Methods that can be used to prevent onload firing while an event that
2347 * should block onload is posted. onload is guaranteed to not fire until
2348 * either all calls to BlockOnload() have been matched by calls to
2349 * UnblockOnload() or the load has been stopped altogether (by the user
2350 * pressing the Stop button, say).
2352 void BlockOnload();
2354 * @param aFireSync whether to fire onload synchronously. If false,
2355 * onload will fire asynchronously after all onload blocks have been
2356 * removed. It will NOT fire from inside UnblockOnload. If true,
2357 * onload may fire from inside UnblockOnload.
2359 void UnblockOnload(bool aFireSync);
2361 // Only BlockOnload should call this!
2362 void AsyncBlockOnload();
2364 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2366 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnblockDOMContentLoaded();
2369 * Notification that the page has been shown, for documents which are loaded
2370 * into a DOM window. This corresponds to the completion of document load,
2371 * or to the page's presentation being restored into an existing DOM window.
2372 * This notification fires applicable DOM events to the content window. See
2373 * PageTransitionEvent.webidl for a description of the |aPersisted|
2374 * parameter. If aDispatchStartTarget is null, the pageshow event is
2375 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2376 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2377 * event is only dispatched to listeners in the system group.
2378 * Note: if aDispatchStartTarget isn't null, the showing state of the
2379 * document won't be altered.
2381 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2382 bool aOnlySystemGroup = false);
2385 * Notification that the page has been hidden, for documents which are loaded
2386 * into a DOM window. This corresponds to the unloading of the document, or
2387 * to the document's presentation being saved but removed from an existing
2388 * DOM window. This notification fires applicable DOM events to the content
2389 * window. See PageTransitionEvent.webidl for a description of the
2390 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2391 * event is dispatched on the ScriptGlobalObject for this document,
2392 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2393 * true, the event is only dispatched to listeners in the system group.
2394 * Note: if aDispatchStartTarget isn't null, the showing state of the
2395 * document won't be altered.
2397 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2398 bool aOnlySystemGroup = false);
2401 * We record the set of links in the document that are relevant to
2402 * style.
2405 * Notification that an element is a link that is relevant to style.
2407 void AddStyleRelevantLink(Link* aLink) {
2408 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2409 #ifdef DEBUG
2410 NS_ASSERTION(!mStyledLinks.Contains(aLink),
2411 "Document already knows about this Link!");
2412 mStyledLinksCleared = false;
2413 #endif
2414 mStyledLinks.Insert(aLink);
2418 * Notification that an element is a link and its URI might have been
2419 * changed or the element removed. If the element is still a link relevant
2420 * to style, then someone must ensure that AddStyleRelevantLink is
2421 * (eventually) called on it again.
2423 void ForgetLink(Link* aLink) {
2424 MOZ_ASSERT(aLink, "Passing in a null link. Expect crashes RSN!");
2425 MOZ_ASSERT(mStyledLinks.Contains(aLink) || mStyledLinksCleared,
2426 "Document knows nothing about this Link!");
2427 mStyledLinks.Remove(aLink);
2430 // Refreshes the hrefs of all the links in the document.
2431 void RefreshLinkHrefs();
2434 * Support for window.matchMedia()
2437 already_AddRefed<MediaQueryList> MatchMedia(const nsACString& aMediaQueryList,
2438 CallerType aCallerType);
2440 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2442 nsTHashtable<LCPEntryHashEntry>& ContentIdentifiersForLCP() {
2443 return mContentIdentifiersForLCP;
2447 * Get the compatibility mode for this document
2449 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2452 * Check whether we've ever fired a DOMTitleChanged event for this
2453 * document.
2455 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2458 * To batch DOMSubtreeModified, document needs to be informed when
2459 * a mutation event might be dispatched, even if the event isn't actually
2460 * created because there are no listeners for it.
2462 * @param aTarget is the target for the mutation event.
2464 void MayDispatchMutationEvent(nsINode* aTarget) {
2465 if (mSubtreeModifiedDepth > 0) {
2466 mSubtreeModifiedTargets.AppendObject(aTarget);
2471 * Marks as not-going-to-be-collected for the given generation of
2472 * cycle collection.
2474 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2475 mMarkedCCGeneration = aGeneration;
2479 * Gets the cycle collector generation this document is marked for.
2481 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2484 * Returns whether this document is cookie averse. See
2485 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2487 bool IsCookieAverse() const {
2488 // If we are a document that "has no browsing context."
2489 if (!GetInnerWindow()) {
2490 return true;
2493 // If we are a document "whose URL's scheme is not a network scheme."
2494 // NB: Explicitly allow file: URIs to store cookies.
2496 return !NodePrincipal()->SchemeIs("http") &&
2497 !NodePrincipal()->SchemeIs("https") &&
2498 !NodePrincipal()->SchemeIs("file");
2501 bool IsLoadedAsData() { return mLoadedAsData; }
2503 void SetAddedToMemoryReportAsDataDocument() {
2504 mAddedToMemoryReportingAsDataDocument = true;
2507 void UnregisterFromMemoryReportingForDataDocument();
2509 bool MayStartLayout() { return mMayStartLayout; }
2511 void SetMayStartLayout(bool aMayStartLayout);
2513 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2515 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2517 // In case of failure, the document really can't initialize the frame loader.
2518 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2519 // In case of failure, the caller must handle the error, for example by
2520 // finalizing frame loader asynchronously.
2521 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2522 // Removes the frame loader of aShell from the initialization list.
2523 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2526 * Check whether this document is a root document that is not an
2527 * external resource.
2529 bool IsRootDisplayDocument() const {
2530 return !mParentDocument && !mDisplayDocument;
2533 bool ChromeRulesEnabled() const { return mChromeRulesEnabled; }
2535 bool IsInChromeDocShell() const {
2536 const Document* root = this;
2537 while (const Document* displayDoc = root->GetDisplayDocument()) {
2538 root = displayDoc;
2540 return root->mInChromeDocShell;
2543 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2545 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2547 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2549 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2551 bool IsResourceDoc() const {
2552 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2553 mHasDisplayDocument; // Are we an external resource doc?
2557 * Get the document for which this document is an external resource. This
2558 * will be null if this document is not an external resource. Otherwise,
2559 * GetDisplayDocument() will return a non-null document, and
2560 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2562 Document* GetDisplayDocument() const { return mDisplayDocument; }
2565 * Set the display document for this document. aDisplayDocument must not be
2566 * null.
2568 void SetDisplayDocument(Document* aDisplayDocument) {
2569 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2570 "Shouldn't set mDisplayDocument on documents that already "
2571 "have a presentation or a docshell or a window");
2572 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2573 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2574 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2575 "Display documents should not nest");
2576 mDisplayDocument = aDisplayDocument;
2577 mHasDisplayDocument = !!aDisplayDocument;
2581 * Request an external resource document for aURI. This will return the
2582 * resource document if available. If one is not available yet, it will
2583 * start loading as needed, and the pending load object will be returned in
2584 * aPendingLoad so that the caller can register an observer to wait for the
2585 * load. If this function returns null and doesn't return a pending load,
2586 * that means that there is no resource document for this URI and won't be
2587 * one in the future.
2589 * @param aURI the URI to get
2590 * @param aReferrerInfo the referrerInfo of the request
2591 * @param aRequestingNode the node making the request
2592 * @param aPendingLoad the pending load for this request, if any
2594 Document* RequestExternalResource(nsIURI* aURI,
2595 nsIReferrerInfo* aReferrerInfo,
2596 nsINode* aRequestingNode,
2597 ExternalResourceLoad** aPendingLoad);
2600 * Enumerate the external resource documents associated with this document.
2601 * The enumerator callback should return CallState::Continue to continue
2602 * enumerating, or CallState::Stop to stop. This callback will never get
2603 * passed a null aDocument.
2605 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2607 dom::ExternalResourceMap& ExternalResourceMap() {
2608 return mExternalResourceMap;
2612 * Return whether the document is currently showing (in the sense of
2613 * OnPageShow() having been called already and OnPageHide() not having been
2614 * called yet.
2616 bool IsShowing() const { return mIsShowing; }
2618 * Return whether the document is currently visible (in the sense of
2619 * OnPageHide having been called and OnPageShow not yet having been called)
2621 bool IsVisible() const { return mVisible; }
2623 void SetSuppressedEventListener(EventListener* aListener);
2625 EventListener* GetSuppressedEventListener() {
2626 return mSuppressedEventListener;
2630 * Return true when this document is active, i.e., an active document
2631 * in a content viewer and not in the bfcache.
2632 * This does NOT match the "active document" concept in the WHATWG spec -
2633 * see IsCurrentActiveDocument.
2635 bool IsActive() const;
2638 * Return true if this is the current active document for its
2639 * docshell. Note that a docshell may have multiple active documents
2640 * due to the bfcache -- this should be used when you need to
2641 * differentiate the *current* active document from any active
2642 * documents.
2644 bool IsCurrentActiveDocument() const {
2645 nsPIDOMWindowInner* inner = GetInnerWindow();
2646 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2650 * Returns whether this document should perform image loads.
2652 bool ShouldLoadImages() const {
2653 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2654 // images can themselves have data: URL image references.
2655 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2656 IsStaticDocument();
2659 void SetHasPrintCallbacks() {
2660 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2661 mHasPrintCallbacks = true;
2664 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2667 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2668 * the document's activity changes such as OnPageHide, visibility, activity.
2669 * The ActivityObserver objects can be nsIObjectLoadingContent or
2670 * nsIDocumentActivity or HTMLMEdiaElement.
2672 void RegisterActivityObserver(nsISupports* aSupports);
2673 bool UnregisterActivityObserver(nsISupports* aSupports);
2674 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2675 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2676 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2678 void NotifyActivityChanged();
2680 // Indicates whether mAnimationController has been (lazily) initialized.
2681 // If this returns true, we're promising that GetAnimationController()
2682 // will have a non-null return value.
2683 bool HasAnimationController() { return !!mAnimationController; }
2685 // Getter for this document's SMIL Animation Controller. Performs lazy
2686 // initialization, if this document supports animation and if
2687 // mAnimationController isn't yet initialized.
2689 // If HasAnimationController is true, this is guaranteed to return non-null.
2690 SMILAnimationController* GetAnimationController();
2692 // Gets the tracker for scroll-driven animations that are waiting to start.
2693 // Returns nullptr if there is no scroll-driven animation tracker for this
2694 // document which will be the case if there have never been any scroll-driven
2695 // animations in the document.
2696 ScrollTimelineAnimationTracker* GetScrollTimelineAnimationTracker() {
2697 return mScrollTimelineAnimationTracker;
2700 // Gets the tracker for scroll-driven animations that are waiting to start and
2701 // creates it if it doesn't already exist. As a result, the return value
2702 // will never be nullptr.
2703 ScrollTimelineAnimationTracker* GetOrCreateScrollTimelineAnimationTracker();
2706 * Prevents user initiated events from being dispatched to the document and
2707 * subdocuments.
2709 void SuppressEventHandling(uint32_t aIncrease = 1);
2712 * Unsuppress event handling.
2713 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2714 * asynchronously.
2716 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnsuppressEventHandlingAndFireEvents(
2717 bool aFireEvents);
2719 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2721 bool IsEventHandlingEnabled() const {
2722 return !EventHandlingSuppressed() && mScriptGlobalObject;
2725 bool WouldScheduleFrameRequestCallbacks() const {
2726 // If this function changes to depend on some other variable, make sure to
2727 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2728 // where that variable can change.
2729 return mPresShell && IsEventHandlingEnabled();
2732 void DecreaseEventSuppression() {
2733 MOZ_ASSERT(mEventsSuppressed);
2734 --mEventsSuppressed;
2735 UpdateFrameRequestCallbackSchedulingState();
2739 * Some clipboard commands are unconditionally enabled on some documents, so
2740 * as to always dispatch copy / paste events even though you'd normally not be
2741 * able to copy.
2743 bool AreClipboardCommandsUnconditionallyEnabled() const;
2746 * Note a ChannelEventQueue which has been suspended on the document's behalf
2747 * to prevent XHRs from running content scripts while event handling is
2748 * suppressed. The document is responsible for resuming the queue after
2749 * event handling is unsuppressed.
2751 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2754 * Returns true if a postMessage event should be suspended instead of running.
2755 * The document is responsible for running the event later, in the order they
2756 * were received.
2758 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2761 * Run any suspended postMessage events, or clear them.
2763 void FireOrClearPostMessageEvents(bool aFireEvents);
2765 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2768 * Flag whether we're about to fire the window's load event for this document.
2770 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2773 * Test whether we should be firing a load event for this document after a
2774 * document.close(). This is public and on Document, instead of being private
2775 * to Document, because we need to go through the normal docloader logic
2776 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2777 * semantics of firing the load event; we just don't want to fire the load
2778 * event if this tests true. So we need the docloader to be able to access
2779 * this state.
2781 * This method should only be called at the point when the load event is about
2782 * to be fired. It resets the "skip" flag, so it is not idempotent.
2784 bool SkipLoadEventAfterClose() {
2785 bool skip = mSkipLoadEventAfterClose;
2786 mSkipLoadEventAfterClose = false;
2787 return skip;
2791 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2793 void IncrementIgnoreDestructiveWritesCounter() {
2794 ++mIgnoreDestructiveWritesCounter;
2798 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2800 void DecrementIgnoreDestructiveWritesCounter() {
2801 --mIgnoreDestructiveWritesCounter;
2804 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2807 * Returns true if this document is allowed to contain XUL element and
2808 * use non-builtin XBL bindings.
2810 bool AllowXULXBL() {
2811 return mAllowXULXBL == eTriTrue ? true
2812 : mAllowXULXBL == eTriFalse ? false
2813 : InternalAllowXULXBL();
2817 * Returns true if this document is allowed to load DTDs from UI resources
2818 * no matter what.
2820 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2822 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2824 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2827 * Returns the template content owner document that owns the content of
2828 * HTMLTemplateElement.
2830 Document* GetTemplateContentsOwner();
2832 Document* GetTemplateContentsOwnerIfExists() const {
2833 return mTemplateContentsOwner.get();
2836 bool IsTemplateContentsOwner() const {
2837 // Template contents owner documents are the template contents owner of
2838 // themselves.
2839 return mTemplateContentsOwner == this;
2843 * Returns true if this document is a static clone of a normal document.
2845 * We create static clones for print preview and printing (possibly other
2846 * things in future).
2848 * Note that static documents are also "loaded as data" (if this method
2849 * returns true, IsLoadedAsData() will also return true).
2851 bool IsStaticDocument() const { return mIsStaticDocument; }
2854 * Clones the document along with any subdocuments, stylesheet, etc.
2856 * The resulting document and everything it contains (including any
2857 * sub-documents) are created purely via cloning. The returned documents and
2858 * any sub-documents are "loaded as data" documents to preserve the state as
2859 * it was during the clone process (we don't want external resources to load
2860 * and replace the cloned resources).
2862 * @param aCloneContainer The container for the clone document.
2863 * @param aDocumentViewer The viewer for the clone document. Must be the
2864 * viewer of aCloneContainer, but callers must have a
2865 * reference to it already and ensure it's not null.
2866 * @param aPrintSettings The print settings for this clone.
2867 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2869 already_AddRefed<Document> CreateStaticClone(
2870 nsIDocShell* aCloneContainer, nsIDocumentViewer* aDocumentViewer,
2871 nsIPrintSettings* aPrintSettings, bool* aOutHasInProcessPrintCallbacks);
2874 * If this document is a static clone, this returns the original
2875 * document.
2877 Document* GetOriginalDocument() const {
2878 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2879 return mOriginalDocument;
2883 * If this document is a static clone, let the original document know that
2884 * we're going away and then release our reference to it.
2886 void UnlinkOriginalDocumentIfStatic();
2889 * These are called by the parser as it encounters <picture> tags, the end of
2890 * said tags, and possible picture <source srcset> sources respectively. These
2891 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2892 * expected to be marked void.
2894 * NOTE that the parser does not attempt to track the current picture nesting
2895 * level or whether the given <source> tag is within a picture -- it is only
2896 * guaranteed to order these calls properly with respect to
2897 * ResolvePreLoadImage.
2900 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2902 void PreloadPictureClosed();
2904 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2905 const nsAString& aSizesAttr,
2906 const nsAString& aTypeAttr,
2907 const nsAString& aMediaAttr);
2910 * Called by the parser to resolve an image for preloading. The parser will
2911 * call the PreloadPicture* functions to inform us of possible <picture>
2912 * nesting and possible sources, which are used to inform URL selection
2913 * responsive <picture> or <img srcset> images. Unset attributes are expected
2914 * to be marked void.
2915 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2916 * true, false otherwise.
2918 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2919 const nsAString& aSrcAttr,
2920 const nsAString& aSrcsetAttr,
2921 const nsAString& aSizesAttr,
2922 bool* aIsImgSet);
2924 * Called by nsParser to preload images. Can be removed and code moved
2925 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2926 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2927 * be a void string if the attr is not present.
2928 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2929 * when this image is for loading <picture> or <img srcset> images.
2931 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2932 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2933 bool aLinkPreload, const nsAString& aFetchPriority);
2934 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2935 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2936 bool aLinkPreload, uint64_t aEarlyHintPreloaderId,
2937 const nsAString& aFetchPriority);
2940 * Called by images to forget an image preload when they start doing
2941 * the real load.
2943 void ForgetImagePreload(nsIURI* aURI);
2946 * Called by the parser or the preload service to preload style sheets.
2947 * aCrossOriginAttr should be a void string if the attr is not present.
2949 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2950 const nsAString& aCrossOriginAttr,
2951 ReferrerPolicyEnum aReferrerPolicy,
2952 const nsAString& aNonce,
2953 const nsAString& aIntegrity,
2954 css::StylePreloadKind,
2955 uint64_t aEarlyHintPreloaderId,
2956 const nsAString& aFetchPriority);
2959 * Called by the chrome registry to load style sheets.
2961 * This always does a synchronous load, and parses as a normal document sheet.
2963 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2966 * Returns true if the locale used for the document specifies a direction of
2967 * right to left. For chrome documents, this comes from the chrome registry.
2968 * This is used to determine the current state for the :-moz-locale-dir
2969 * pseudoclass so once can know whether a document is expected to be rendered
2970 * left-to-right or right-to-left.
2972 bool IsDocumentRightToLeft();
2975 * Called by Parser for link rel=preconnect
2977 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2980 * Set the document's pending state object (as serialized using structured
2981 * clone).
2983 void SetStateObject(nsIStructuredCloneContainer* scContainer);
2986 * Set the document's pending state object to the same state object as
2987 * aDocument.
2989 void SetStateObjectFrom(Document* aDocument) {
2990 SetStateObject(aDocument->mStateObjectContainer);
2994 * Returns true if there is a lightweight theme specified. This is used to
2995 * determine the state of the :-moz-lwtheme pseudo-class.
2997 bool ComputeDocumentLWTheme() const;
2998 void ResetDocumentLWTheme() {
2999 UpdateDocumentStates(DocumentState::LWTHEME, true);
3002 // Whether we're a media document or not.
3003 enum class MediaDocumentKind {
3004 NotMedia,
3005 Video,
3006 Image,
3007 Plugin,
3010 virtual enum MediaDocumentKind MediaDocumentKind() const {
3011 return MediaDocumentKind::NotMedia;
3014 DocumentState State() const { return mState; }
3016 nsISupports* GetCurrentContentSink();
3018 void ElementWithAutoFocusInserted(Element* aAutoFocusCandidate);
3019 MOZ_CAN_RUN_SCRIPT void FlushAutoFocusCandidates();
3020 void ScheduleFlushAutoFocusCandidates();
3021 bool HasAutoFocusCandidates() const {
3022 return !mAutoFocusCandidates.IsEmpty();
3025 void SetAutoFocusFired();
3027 void SetScrollToRef(nsIURI* aDocumentURI);
3028 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3029 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3031 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3032 mChangeScrollPosWhenScrollingToRef = aValue;
3035 using DocumentOrShadowRoot::GetElementById;
3036 using DocumentOrShadowRoot::GetElementsByClassName;
3037 using DocumentOrShadowRoot::GetElementsByTagName;
3038 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3040 DocumentTimeline* Timeline();
3041 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3042 void UpdateHiddenByContentVisibilityForAnimations();
3044 SVGSVGElement* GetSVGRootElement() const;
3046 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3047 int32_t* aHandle);
3048 void CancelFrameRequestCallback(int32_t aHandle);
3051 * Returns true if the handle refers to a callback that was canceled that
3052 * we did not find in our list of callbacks (e.g. because it is one of those
3053 * in the set of callbacks currently queued to be run).
3055 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3058 * Put this document's frame request callbacks into the provided
3059 * list, and forget about them.
3061 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3064 * @return true if this document's frame request callbacks should be
3065 * throttled. We throttle requestAnimationFrame for documents which aren't
3066 * visible (e.g. scrolled out of the viewport).
3068 bool ShouldThrottleFrameRequests() const;
3070 // This returns true when the document tree is being teared down.
3071 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3073 dom::ImageTracker* ImageTracker();
3075 // Adds an element to mResponsiveContent when the element is
3076 // added to the tree.
3077 void AddResponsiveContent(HTMLImageElement* aContent) {
3078 MOZ_ASSERT(aContent);
3079 mResponsiveContent.Insert(aContent);
3082 // Removes an element from mResponsiveContent when the element is
3083 // removed from the tree.
3084 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3085 MOZ_ASSERT(aContent);
3086 mResponsiveContent.Remove(aContent);
3089 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3090 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3091 mSVGUseElementsNeedingShadowTreeUpdate.Remove(&aElement);
3094 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3095 return mSVGUseElementsNeedingShadowTreeUpdate.Contains(&aElement);
3098 using ShadowRootSet = nsTHashSet<ShadowRoot*>;
3100 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3101 mComposedShadowRoots.Insert(&aShadowRoot);
3104 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3105 mComposedShadowRoots.Remove(&aShadowRoot);
3108 // If you're considering using this, you probably want to use
3109 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3110 // sanity-checking.
3111 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3112 return mComposedShadowRoots.Contains(&aShadowRoot);
3115 const ShadowRootSet& ComposedShadowRoots() const {
3116 return mComposedShadowRoots;
3119 // WebIDL method for chrome code.
3120 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3122 // Notifies any responsive content added by AddResponsiveContent upon media
3123 // features values changing.
3124 void NotifyMediaFeatureValuesChanged();
3126 nsresult GetStateObject(JS::MutableHandle<JS::Value> aState);
3128 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3130 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3132 nsContentList* ImageMapList();
3134 // Add aLink to the set of links that need their status resolved.
3135 void RegisterPendingLinkUpdate(Link* aLink);
3137 // Update state on links in mLinksToUpdate.
3138 void FlushPendingLinkUpdates();
3140 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3141 void WarnOnceAbout(
3142 DeprecatedOperations aOperation, bool asError = false,
3143 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3145 #define DOCUMENT_WARNING(_op) e##_op,
3146 enum DocumentWarnings {
3147 #include "nsDocumentWarningList.h"
3148 eDocumentWarningCount
3150 #undef DOCUMENT_WARNING
3151 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3152 void WarnOnceAbout(
3153 DocumentWarnings aWarning, bool asError = false,
3154 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3156 // This method may fire a DOM event; if it does so it will happen
3157 // synchronously.
3159 // Whether the event fires is controlled by the argument.
3160 enum class DispatchVisibilityChange { No, Yes };
3161 void UpdateVisibilityState(
3162 DispatchVisibilityChange = DispatchVisibilityChange::Yes);
3164 // Posts an event to call UpdateVisibilityState.
3165 void PostVisibilityUpdateEvent();
3167 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3169 // Adds the size of a given node, which must not be a document node, to the
3170 // window sizes passed-in.
3171 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3173 // Note: Document is a sub-class of nsINode, which has a
3174 // SizeOfExcludingThis function. However, because Document objects can
3175 // only appear at the top of the DOM tree, we have a specialized measurement
3176 // function which returns multiple sizes.
3177 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3178 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3179 // because Document inherits from nsINode; see the comment above the
3180 // declaration of nsINode::SizeOfIncludingThis.
3181 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3183 void ConstructUbiNode(void* storage) override;
3185 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3187 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3189 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3191 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3193 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3195 void SetIsInSyncOperation(bool aSync);
3197 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3200 * Creates a new element in the HTML namespace with a local name given by
3201 * aTag.
3203 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3205 // WebIDL API
3206 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3207 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3208 ErrorResult& rv);
3209 DOMImplementation* GetImplementation(ErrorResult& rv);
3210 [[nodiscard]] nsresult GetURL(nsString& retval) const;
3211 [[nodiscard]] nsresult GetDocumentURI(nsString& retval) const;
3212 // Return the URI for the document.
3213 // The returned value may differ if the document is loaded via XHR, and
3214 // when accessed from chrome privileged script and
3215 // from content privileged script for compatibility.
3216 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3217 ErrorResult& aRv) const;
3218 void GetCompatMode(nsString& retval) const;
3219 void GetCharacterSet(nsAString& retval) const;
3220 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3221 // GetDoctype defined above
3222 Element* GetDocumentElement() const { return GetRootElement(); }
3224 WindowContext* GetTopLevelWindowContext() const;
3226 // If the top-level ancestor content document for this document is in the same
3227 // process, returns it. Otherwise, returns null. This function is not
3228 // Fission-compatible, and should not be used in new code.
3229 Document* GetTopLevelContentDocumentIfSameProcess();
3230 const Document* GetTopLevelContentDocumentIfSameProcess() const;
3232 // Returns the associated app window if this is a top-level chrome document,
3233 // null otherwise.
3234 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3236 already_AddRefed<Element> CreateElement(
3237 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3238 ErrorResult& rv);
3239 already_AddRefed<Element> CreateElementNS(
3240 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3241 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3242 already_AddRefed<Element> CreateXULElement(
3243 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3244 ErrorResult& aRv);
3245 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3246 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3247 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3248 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3249 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3250 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3251 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3252 ErrorResult& rv) const;
3253 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3254 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* AdoptNode(
3255 nsINode& aAdoptedNode, ErrorResult& rv, bool aAcceptShadowRoot = false);
3256 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3257 CallerType aCallerType,
3258 ErrorResult& rv) const;
3259 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3260 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3261 uint32_t aWhatToShow,
3262 NodeFilter* aFilter,
3263 ErrorResult& rv) const;
3264 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3265 uint32_t aWhatToShow,
3266 NodeFilter* aFilter,
3267 ErrorResult& rv) const;
3268 // Deprecated WebIDL bits
3269 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3270 ErrorResult& rv);
3271 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3272 ErrorResult& rv);
3273 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3274 const nsAString& aQualifiedName,
3275 ErrorResult& rv);
3276 void GetInputEncoding(nsAString& aInputEncoding) const;
3277 already_AddRefed<Location> GetLocation() const;
3278 void GetDomain(nsAString& aDomain);
3279 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3280 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3281 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3282 void GetReferrer(nsAString& aReferrer) const;
3283 void GetLastModified(nsAString& aLastModified) const;
3284 void GetReadyState(nsAString& aReadyState) const;
3286 void GetTitle(nsAString& aTitle);
3287 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3288 void GetDir(nsAString& aDirection) const;
3289 void SetDir(const nsAString& aDirection);
3290 nsIHTMLCollection* Images();
3291 nsIHTMLCollection* Embeds();
3292 nsIHTMLCollection* Plugins() { return Embeds(); }
3293 nsIHTMLCollection* Links();
3294 nsIHTMLCollection* Forms();
3295 nsIHTMLCollection* Scripts();
3296 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3297 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3298 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3300 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3301 const mozilla::dom::Optional<nsAString>& /* unused */,
3302 mozilla::ErrorResult& aError);
3303 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3304 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3305 mozilla::ErrorResult& rv);
3306 void Close(mozilla::ErrorResult& rv);
3307 void Write(const mozilla::dom::Sequence<nsString>& aText,
3308 mozilla::ErrorResult& rv);
3309 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3310 mozilla::ErrorResult& rv);
3311 Nullable<WindowProxyHolder> GetDefaultView() const;
3312 Element* GetActiveElement();
3313 enum class IncludeChromeOnly : bool { No, Yes };
3314 // TODO(emilio): Audit callers and remove the default argument, some seem like
3315 // they could want the IncludeChromeOnly::Yes version.
3316 nsIContent* GetUnretargetedFocusedContent(
3317 IncludeChromeOnly = IncludeChromeOnly::No) const;
3319 * Return true if this document or a subdocument has focus.
3321 bool HasFocus(ErrorResult& rv) const;
3324 * Return true if this document itself has focus.
3326 bool ThisDocumentHasFocus() const;
3328 void GetDesignMode(nsAString& aDesignMode);
3329 void SetDesignMode(const nsAString& aDesignMode,
3330 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3331 void SetDesignMode(const nsAString& aDesignMode,
3332 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3333 mozilla::ErrorResult& rv);
3334 MOZ_CAN_RUN_SCRIPT
3335 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3336 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3337 mozilla::ErrorResult& aRv);
3338 MOZ_CAN_RUN_SCRIPT bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3339 nsIPrincipal& aSubjectPrincipal,
3340 mozilla::ErrorResult& aRv);
3341 MOZ_CAN_RUN_SCRIPT bool QueryCommandIndeterm(
3342 const nsAString& aHTMLCommandName, mozilla::ErrorResult& aRv);
3343 MOZ_CAN_RUN_SCRIPT bool QueryCommandState(const nsAString& aHTMLCommandName,
3344 mozilla::ErrorResult& aRv);
3345 MOZ_CAN_RUN_SCRIPT bool QueryCommandSupported(
3346 const nsAString& aHTMLCommandName, mozilla::dom::CallerType aCallerType,
3347 mozilla::ErrorResult& aRv);
3348 MOZ_CAN_RUN_SCRIPT void QueryCommandValue(const nsAString& aHTMLCommandName,
3349 nsAString& aValue,
3350 mozilla::ErrorResult& aRv);
3351 nsIHTMLCollection* Applets();
3352 nsIHTMLCollection* Anchors();
3353 TimeStamp LastFocusTime() const;
3354 void SetLastFocusTime(const TimeStamp& aFocusTime);
3355 // Event handlers are all on nsINode already
3356 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3357 Element* GetCurrentScript();
3358 void ReleaseCapture() const;
3359 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3360 nsIURI* GetDocumentURIObject() const;
3361 // Not const because all the fullscreen goop is not const
3362 const char* GetFullscreenError(CallerType);
3363 bool FullscreenEnabled(CallerType aCallerType) {
3364 return !GetFullscreenError(aCallerType);
3367 void GetWireframeWithoutFlushing(bool aIncludeNodes, Nullable<Wireframe>&);
3369 MOZ_CAN_RUN_SCRIPT void GetWireframe(bool aIncludeNodes,
3370 Nullable<Wireframe>&);
3372 // Hides all popovers until the given end point, see
3373 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3374 MOZ_CAN_RUN_SCRIPT void HideAllPopoversUntil(nsINode& aEndpoint,
3375 bool aFocusPreviousElement,
3376 bool aFireEvents);
3378 MOZ_CAN_RUN_SCRIPT_BOUNDARY void HideAllPopoversWithoutRunningScript();
3379 // Hides the given popover element, see
3380 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3381 MOZ_CAN_RUN_SCRIPT void HidePopover(Element& popover,
3382 bool aFocusPreviousElement,
3383 bool aFireEvents, ErrorResult& aRv);
3385 // Returns a list of all the elements in the Document's top layer whose
3386 // popover attribute is in the auto state.
3387 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3388 nsTArray<Element*> AutoPopoverList() const;
3390 // Return document's auto popover list's last element.
3391 // See
3392 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3393 Element* GetTopmostAutoPopover() const;
3395 // Adds/removes an element to/from the auto popover list.
3396 void AddToAutoPopoverList(Element&);
3397 void RemoveFromAutoPopoverList(Element&);
3399 void AddPopoverToTopLayer(Element&);
3400 void RemovePopoverFromTopLayer(Element&);
3402 Element* GetTopLayerTop();
3403 // Return the fullscreen element in the top layer
3404 Element* GetUnretargetedFullscreenElement() const;
3405 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3406 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3407 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3408 void GetFgColor(nsAString& aFgColor);
3409 void SetFgColor(const nsAString& aFgColor);
3410 void GetLinkColor(nsAString& aLinkColor);
3411 void SetLinkColor(const nsAString& aLinkColor);
3412 void GetVlinkColor(nsAString& aAvlinkColor);
3413 void SetVlinkColor(const nsAString& aVlinkColor);
3414 void GetAlinkColor(nsAString& aAlinkColor);
3415 void SetAlinkColor(const nsAString& aAlinkColor);
3416 void GetBgColor(nsAString& aBgColor);
3417 void SetBgColor(const nsAString& aBgColor);
3418 void Clear() const {
3419 // Deprecated
3421 void CaptureEvents();
3422 void ReleaseEvents();
3424 mozilla::dom::HTMLAllCollection* All();
3426 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3427 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3428 JSObject* aObject);
3429 // Checks that the caller is either chrome or some addon.
3430 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3432 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3433 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3435 public:
3436 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3437 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3438 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3439 aSheetSet = mLastStyleSheetSet;
3441 const nsString& GetCurrentStyleSheetSet() const {
3442 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3443 : mLastStyleSheetSet;
3445 void SetPreferredStyleSheetSet(const nsAString&);
3446 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3447 aSheetSet = mPreferredStyleSheetSet;
3449 DOMStringList* StyleSheetSets();
3450 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3453 * Retrieve the location of the caret position (DOM node and character
3454 * offset within that node), given a point.
3456 * @param aX Horizontal point at which to determine the caret position, in
3457 * page coordinates.
3458 * @param aY Vertical point at which to determine the caret position, in
3459 * page coordinates.
3461 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3462 float aY);
3464 Element* GetScrollingElement();
3465 // A way to check whether a given element is what would get returned from
3466 // GetScrollingElement. It can be faster than comparing to the return value
3467 // of GetScrollingElement() due to being able to avoid flushes in various
3468 // cases. This method assumes that null is NOT passed.
3469 bool IsScrollingElement(Element* aElement);
3471 // QuerySelector and QuerySelectorAll already defined on nsINode
3473 UniquePtr<XPathExpression> CreateExpression(const nsAString& aExpression,
3474 XPathNSResolver* aResolver,
3475 ErrorResult& rv);
3476 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3477 already_AddRefed<XPathResult> Evaluate(
3478 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3479 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3480 ErrorResult& rv);
3481 // Touch event handlers already on nsINode
3482 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3483 EventTarget* aTarget, int32_t aIdentifier,
3484 int32_t aPageX, int32_t aPageY,
3485 int32_t aScreenX, int32_t aScreenY,
3486 int32_t aClientX, int32_t aClientY,
3487 int32_t aRadiusX, int32_t aRadiusY,
3488 float aRotationAngle, float aForce);
3489 already_AddRefed<TouchList> CreateTouchList();
3490 already_AddRefed<TouchList> CreateTouchList(
3491 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3492 already_AddRefed<TouchList> CreateTouchList(
3493 const Sequence<OwningNonNull<Touch>>& aTouches);
3495 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3496 mStyleSheetChangeEventsEnabled = aValue;
3499 bool StyleSheetChangeEventsEnabled() const {
3500 return mStyleSheetChangeEventsEnabled;
3503 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue) {
3504 mDevToolsAnonymousAndShadowEventsEnabled = aValue;
3506 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3507 return mDevToolsAnonymousAndShadowEventsEnabled;
3510 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3511 const BlockParsingOptions& aOptions,
3512 ErrorResult& aRv);
3514 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3516 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3518 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock) {
3519 if (aBlock) {
3520 BlockOnload();
3521 } else {
3522 UnblockOnload(/* aFireSync = */ false);
3526 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3527 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3528 void InitializeXULBroadcastManager();
3529 XULBroadcastManager* GetXULBroadcastManager() const {
3530 return mXULBroadcastManager;
3532 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3533 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3535 bool DevToolsWatchingDOMMutations() const {
3536 return mDevToolsWatchingDOMMutations;
3538 void SetDevToolsWatchingDOMMutations(bool aValue);
3540 void MaybeWarnAboutZoom();
3542 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3543 void EvaluateMediaQueriesAndReportChanges(bool aRecurse);
3545 nsTHashSet<RefPtr<WakeLockSentinel>>& ActiveWakeLocks(WakeLockType aType);
3547 void UnlockAllWakeLocks(WakeLockType aType);
3549 // ParentNode
3550 nsIHTMLCollection* Children();
3551 uint32_t ChildElementCount();
3554 * Asserts IsHTMLOrXHTML, and can't return null.
3555 * Defined inline in nsHTMLDocument.h
3557 inline nsHTMLDocument* AsHTMLDocument();
3558 inline const nsHTMLDocument* AsHTMLDocument() const;
3561 * Asserts IsSVGDocument, and can't return null.
3562 * Defined inline in SVGDocument.h
3564 inline SVGDocument* AsSVGDocument();
3565 inline const SVGDocument* AsSVGDocument() const;
3568 * Asserts IsImageDocument, and can't return null.
3569 * Defined inline in ImageDocument.h
3571 inline ImageDocument* AsImageDocument();
3572 inline const ImageDocument* AsImageDocument() const;
3574 gfxUserFontSet* GetUserFontSet();
3575 void FlushUserFontSet();
3576 void MarkUserFontSetDirty();
3577 FontFaceSet* GetFonts() { return mFontFaceSet; }
3579 // FontFaceSource
3580 FontFaceSet* GetFonts(ErrorResult&) { return Fonts(); }
3581 FontFaceSet* Fonts();
3583 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3585 bool IsSynthesized();
3587 // Records whether we will track use counters for this document, and if so,
3588 // which top-level document that page counters will be accumulated to.
3590 // Informs the parent process that page use counters will be sent once the
3591 // document goes away.
3592 void InitUseCounters();
3594 // Reports document use counters via telemetry. This method only has an
3595 // effect once per document, and so is called during document destruction.
3596 void ReportDocumentUseCounters();
3598 // Reports largest contentful paint via telemetry. We want the most up to
3599 // date value for LCP and so this is called during document destruction.
3600 void ReportLCP();
3602 // Report how lazyload performs for this document.
3603 void ReportDocumentLazyLoadCounters();
3605 // Sends page use counters to the parent process to accumulate against the
3606 // top-level document. Must be called while we still have access to our
3607 // WindowContext. This method has an effect each time it is called, and we
3608 // call it just before the document loses its window.
3609 void SendPageUseCounters();
3611 void SetUseCounter(UseCounter aUseCounter) {
3612 mUseCounters[aUseCounter] = true;
3615 const StyleUseCounters* GetStyleUseCounters() {
3616 return mStyleUseCounters.get();
3619 // Propagate our use counters explicitly into the specified referencing
3620 // document.
3622 // This is used for SVG image documents, which cannot be enumerated in the
3623 // referencing document's ReportUseCounters() like external resource documents
3624 // can.
3625 void PropagateImageUseCounters(Document* aReferencingDocument);
3627 // Called to track whether this document has had any interaction.
3628 // This is used to track whether we should permit "beforeunload".
3629 void SetUserHasInteracted();
3630 bool UserHasInteracted() { return mUserHasInteracted; }
3631 void ResetUserInteractionTimer();
3633 // Whether we're cloning the contents of an SVG use element.
3634 bool CloningForSVGUse() const { return mCloningForSVGUse; }
3636 // This should be called when this document receives events which are likely
3637 // to be user interaction with the document, rather than the byproduct of
3638 // interaction with the browser (i.e. a keypress to scroll the view port,
3639 // keyboard shortcuts, etc). This is used to decide whether we should
3640 // permit autoplay audible media. This also gesture activates all other
3641 // content documents in this tab.
3642 void NotifyUserGestureActivation(
3643 UserActivation::Modifiers aModifiers = UserActivation::Modifiers::None());
3645 // This function is used for mochitest only.
3646 void ClearUserGestureActivation();
3648 // Return true if NotifyUserGestureActivation() has been called on any
3649 // document in the document tree.
3650 bool HasBeenUserGestureActivated();
3652 // Reture timestamp of last user gesture in milliseconds relative to
3653 // navigation start timestamp.
3654 DOMHighResTimeStamp LastUserGestureTimeStamp();
3656 // Return true if there is transient user gesture activation and it hasn't yet
3657 // timed out or hasn't been consumed.
3658 bool HasValidTransientUserGestureActivation() const;
3660 // Return true if HasValidTransientUserGestureActivation() would return true,
3661 // and consume the activation.
3662 bool ConsumeTransientUserGestureActivation();
3664 bool GetTransientUserGestureActivationModifiers(
3665 UserActivation::Modifiers* aModifiers);
3667 BrowsingContext* GetBrowsingContext() const;
3669 // This document is a WebExtension page, it might be a background page, a
3670 // popup, a visible tab, a visible iframe ...e.t.c.
3671 bool IsExtensionPage() const;
3673 bool HasScriptsBlockedBySandbox() const;
3675 void ReportHasScrollLinkedEffect(const TimeStamp& aTimeStamp);
3676 bool HasScrollLinkedEffect() const;
3678 #ifdef DEBUG
3679 void AssertDocGroupMatchesKey() const;
3680 #endif
3682 DocGroup* GetDocGroup() const {
3683 #ifdef DEBUG
3684 AssertDocGroupMatchesKey();
3685 #endif
3686 return mDocGroup;
3689 DocGroup* GetDocGroupOrCreate();
3692 * If we're a sub-document, the parent document's layout can affect our style
3693 * and layout (due to the viewport size, viewport units, media queries...).
3695 * This function returns true if our parent document and our child document
3696 * can observe each other. If they cannot, then we don't need to synchronously
3697 * update the parent document layout every time the child document may need
3698 * up-to-date layout information.
3700 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3701 return GetInProcessParentDocument() &&
3702 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3705 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3706 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3707 "Intersection observer already in the list");
3708 mIntersectionObservers.Insert(aObserver);
3711 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3712 mIntersectionObservers.Remove(aObserver);
3715 bool HasIntersectionObservers() const {
3716 return !mIntersectionObservers.IsEmpty();
3719 void UpdateIntersectionObservations(TimeStamp aNowTime);
3720 void ScheduleIntersectionObserverNotification();
3721 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3723 DOMIntersectionObserver* GetLazyLoadObserver() { return mLazyLoadObserver; }
3724 DOMIntersectionObserver& EnsureLazyLoadObserver();
3726 bool HasElementsWithLastRememberedSize() const {
3727 return !mElementsObservedForLastRememberedSize.IsEmpty();
3729 void ObserveForLastRememberedSize(Element&);
3730 void UnobserveForLastRememberedSize(Element&);
3731 void UpdateLastRememberedSizes();
3733 // Dispatch a runnable related to the document.
3734 nsresult Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) const;
3736 // The URLs passed to this function should match what
3737 // JS::DescribeScriptedCaller() returns, since this API is used to
3738 // determine whether some code is being called from a tracking script.
3739 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3740 // The JSContext passed to this method represents the context that we want to
3741 // determine if it belongs to a tracker.
3742 bool IsScriptTracking(JSContext* aCx) const;
3744 // ResizeObserver usage.
3745 void AddResizeObserver(ResizeObserver&);
3746 void RemoveResizeObserver(ResizeObserver&);
3747 void ScheduleResizeObserversNotification() const;
3748 bool HasResizeObservers() const { return !mResizeObservers.IsEmpty(); }
3750 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3751 * All observations in each ResizeObserver with element's depth more than
3752 * aDepth will be gathered.
3754 void GatherAllActiveResizeObservations(uint32_t aDepth);
3756 * Calls BroadcastActiveObservations() for all ResizeObservers.
3757 * It also returns the shallowest depth of observed target elements with
3758 * active observations from all ResizeObservers or
3759 * numeric_limits<uint32_t>::max() if there aren't any active observations
3760 * at all.
3762 MOZ_CAN_RUN_SCRIPT uint32_t BroadcastAllActiveResizeObservations();
3764 * Returns whether there is any ResizeObserver that has active
3765 * observations.
3767 bool HasAnyActiveResizeObservations() const;
3769 * Returns whether there is any ResizeObserver that has skipped observations.
3771 bool HasAnySkippedResizeObservations() const;
3773 * Determine proximity to viewport for content-visibility: auto elements and
3774 * notify resize observers.
3776 MOZ_CAN_RUN_SCRIPT void
3777 DetermineProximityToViewportAndNotifyResizeObservers();
3779 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3780 PermissionDelegateHandler* GetPermissionDelegateHandler();
3782 // Notify the document that a fetch or a XHR request has completed
3783 // succesfully in this document. This is used by the password manager to infer
3784 // whether a form is submitted.
3785 void NotifyFetchOrXHRSuccess();
3787 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3788 void SetNotifyFetchSuccess(bool aShouldNotify);
3790 // When this is set, removing a form or a password field from DOM
3791 // sends a Chrome-only event. This is now only used by the password manager
3792 // and formautofill.
3793 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify);
3795 // This function is used by HTMLFormElement and HTMLInputElement to determin
3796 // whether to send an event when it is removed from DOM.
3797 bool ShouldNotifyFormOrPasswordRemoved() const {
3798 return mShouldNotifyFormOrPasswordRemoved;
3801 HTMLEditor* GetHTMLEditor() const;
3804 * Localization
3806 * For more information on DocumentL10n see
3807 * intl/l10n/docs/fluent/tutorial.rst
3810 public:
3812 * This is a public method exposed on Document WebIDL
3813 * to chrome only documents.
3815 DocumentL10n* GetL10n() const { return mDocumentL10n.get(); }
3818 * Whether there's any async l10n mutation work pending.
3820 * When this turns false, we fire the L10nMutationsFinished event.
3822 bool HasPendingL10nMutations() const;
3825 * This method should be called when the container
3826 * of l10n resources parsing is completed.
3828 * It triggers initial async fetch of the resources
3829 * as early as possible.
3831 * In HTML case this is </head>.
3832 * In XUL case this is </linkset>.
3834 void OnL10nResourceContainerParsed();
3837 * This method should be called when a link element
3838 * with rel="localization" is being added to the
3839 * l10n resource container element.
3841 void LocalizationLinkAdded(Element* aLinkElement);
3844 * This method should be called when a link element
3845 * with rel="localization" is being removed.
3847 void LocalizationLinkRemoved(Element* aLinkElement);
3850 * This method should be called as soon as the
3851 * parsing of the document is completed.
3853 * In HTML/XHTML this happens when we finish parsing
3854 * the document element.
3855 * In XUL it happens at `DoneWalking`, during
3856 * `MozBeforeInitialXULLayout`.
3858 void OnParsingCompleted();
3861 * This method is called when the initial translation
3862 * of the document is completed.
3864 * It unblocks the load event if translation was blocking it.
3866 * If the `aL10nCached` is set to `true`, and the document has
3867 * a prototype, it will set the `isL10nCached` flag on it.
3869 void InitialTranslationCompleted(bool aL10nCached);
3872 * Returns whether the document allows localization.
3874 bool AllowsL10n() const;
3876 void SetAllowDeclarativeShadowRoots(bool aAllowDeclarativeShadowRoots);
3877 bool AllowsDeclarativeShadowRoots() const;
3879 void SuspendDOMNotifications() { mSuspendDOMNotifications = true; }
3881 void ResumeDOMNotifications() { mSuspendDOMNotifications = false; }
3883 bool DOMNotificationsSuspended() const { return mSuspendDOMNotifications; }
3885 protected:
3886 RefPtr<DocumentL10n> mDocumentL10n;
3889 * Return true when you want a document without explicitly specified viewport
3890 * dimensions/scale to be treated as if "width=device-width" had in fact been
3891 * specified.
3893 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3895 private:
3896 bool IsErrorPage() const;
3898 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3899 // mUseCounters.
3900 void SetCssUseCounterBits();
3902 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3903 const nsAString& aHeightString,
3904 bool aIsAutoScale);
3906 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3907 // represents the scale property and returns the scale value if it's valid.
3908 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
3910 // Parse scale values in |aViewportMetaData| and set the values in
3911 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3912 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
3914 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3915 // stored in parent iframe or container's browsingContext (cross process)
3916 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
3918 public:
3919 const OriginTrials& Trials() const { return mTrials; }
3921 private:
3922 void DoCacheAllKnownLangPrefs();
3923 void RecomputeLanguageFromCharset();
3924 bool GetSHEntryHasUserInteraction();
3926 void AppendAutoFocusCandidateToTopDocument(Element* aAutoFocusCandidate);
3928 public:
3929 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
3931 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
3933 void SetSHEntryHasUserInteraction(bool aHasInteraction);
3935 nsAtom* GetContentLanguageAsAtomForStyle() const;
3936 nsAtom* GetLanguageForStyle() const;
3939 * Fetch the user's font preferences for the given aLanguage's
3940 * language group.
3942 const LangGroupFontPrefs* GetFontPrefsForLang(
3943 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
3945 void ForceCacheLang(nsAtom* aLanguage) {
3946 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
3947 return;
3949 GetFontPrefsForLang(aLanguage);
3952 void CacheAllKnownLangPrefs() {
3953 if (!mMayNeedFontPrefsUpdate) {
3954 return;
3956 DoCacheAllKnownLangPrefs();
3959 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
3961 uint32_t GetServoRestyleRootDirtyBits() const {
3962 MOZ_ASSERT(mServoRestyleRoot);
3963 MOZ_ASSERT(mServoRestyleRootDirtyBits);
3964 return mServoRestyleRootDirtyBits;
3967 void ClearServoRestyleRoot() {
3968 mServoRestyleRoot = nullptr;
3969 mServoRestyleRootDirtyBits = 0;
3972 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3973 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3975 bool ShouldThrowOnDynamicMarkupInsertion() {
3976 return mThrowOnDynamicMarkupInsertionCounter;
3979 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3980 ++mThrowOnDynamicMarkupInsertionCounter;
3983 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3984 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3985 --mThrowOnDynamicMarkupInsertionCounter;
3988 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
3990 void IncrementIgnoreOpensDuringUnloadCounter() {
3991 ++mIgnoreOpensDuringUnloadCounter;
3994 void DecrementIgnoreOpensDuringUnloadCounter() {
3995 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3996 --mIgnoreOpensDuringUnloadCounter;
3999 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
4002 * Find the (non-anonymous) content in this document for aFrame. It will
4003 * be aFrame's content node if that content is in this document and not
4004 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4005 * element containing the subdocument containing aFrame, and/or find the
4006 * nearest non-anonymous ancestor in this document.
4007 * Returns null if there is no such element.
4009 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
4011 void ReportShadowDOMUsage();
4013 // Sets flags for media telemetry.
4014 void SetDocTreeHadMedia();
4016 dom::XPathEvaluator* XPathEvaluator();
4018 void MaybeInitializeFinalizeFrameLoaders();
4020 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
4021 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
4024 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
4026 nsIPermissionDelegateHandler* PermDelegateHandler();
4028 // Returns whether this is a top-level about:blank page without an opener (and
4029 // thus likely not accessible by content). Likely because it shouldn't be used
4030 // for security checks for example, see bug 1860098.
4031 bool IsLikelyContentInaccessibleTopLevelAboutBlank() const;
4033 // CSS prefers-color-scheme media feature for this document.
4034 enum class IgnoreRFP { No, Yes };
4035 ColorScheme PreferredColorScheme(IgnoreRFP = IgnoreRFP::No) const;
4036 // Returns the initial color-scheme used for this document based on the
4037 // color-scheme meta tag.
4038 ColorScheme DefaultColorScheme() const;
4040 static bool HasRecentlyStartedForegroundLoads();
4042 static bool AutomaticStorageAccessPermissionCanBeGranted(
4043 nsIPrincipal* aPrincipal);
4045 already_AddRefed<Promise> AddCertException(bool aIsTemporary,
4046 ErrorResult& aError);
4048 void ReloadWithHttpsOnlyException();
4050 // Subframes need to be static cloned after the main document has been
4051 // embedded within a script global. A `PendingFrameStaticClone` is a static
4052 // clone which has not yet been performed.
4054 // The getter returns a direct reference to an internal array which is
4055 // manipulated from within printing code.
4056 struct PendingFrameStaticClone {
4057 PendingFrameStaticClone() = default;
4058 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
4059 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
4060 ~PendingFrameStaticClone();
4062 RefPtr<nsFrameLoaderOwner> mElement;
4063 RefPtr<nsFrameLoader> mStaticCloneOf;
4065 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
4066 nsFrameLoader* aStaticCloneOf);
4068 bool ShouldAvoidNativeTheme() const;
4070 static bool IsValidDomain(nsIURI* aOrigHost, nsIURI* aNewURI);
4072 // Inform a parent document that a BrowserBridgeChild has been created for
4073 // an OOP sub-document.
4074 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4075 void OOPChildLoadStarted(BrowserBridgeChild* aChild);
4077 // Inform a parent document that the BrowserBridgeChild for one of its
4078 // OOP sub-documents is done calling its onload handler.
4079 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4080 void OOPChildLoadDone(BrowserBridgeChild* aChild);
4082 void ClearOOPChildrenLoading();
4084 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading.IsEmpty(); }
4086 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache = true; }
4088 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache; }
4091 * Get the `HighlightRegistry` which contains all highlights associated
4092 * with this document.
4094 class HighlightRegistry& HighlightRegistry();
4096 bool ShouldResistFingerprinting(RFPTarget aTarget) const;
4097 bool IsInPrivateBrowsing() const;
4099 const Maybe<RFPTarget>& GetOverriddenFingerprintingSettings() const {
4100 return mOverriddenFingerprintingSettings;
4103 // Recompute the current resist fingerprinting state. Returns true when
4104 // the state was changed.
4105 bool RecomputeResistFingerprinting();
4107 void RecordCanvasUsage(CanvasUsage& aUsage);
4108 void RecordFontFingerprinting();
4110 bool MayHaveDOMActivateListeners() const;
4112 void DropStyleSet();
4114 protected:
4115 // Returns the WindowContext for the document that we will contribute
4116 // page use counters to.
4117 WindowContext* GetWindowContextForPageUseCounters() const;
4119 void DoUpdateSVGUseElementShadowTrees();
4121 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
4122 nsIPrincipal* aPrincipal);
4124 void EnsureOnloadBlocker();
4126 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
4128 // Returns true if the scheme for the url for this document is "about".
4129 bool IsAboutPage() const;
4131 bool ContainsEMEContent();
4132 bool ContainsMSEContent();
4135 * Returns the title element of the document as defined by the HTML
4136 * specification, or null if there isn't one. For documents whose root
4137 * element is an <svg:svg>, this is the first <svg:title> element that's a
4138 * child of the root. For other documents, it's the first HTML title element
4139 * in the document.
4141 Element* GetTitleElement();
4143 void RecordNavigationTiming(ReadyState aReadyState);
4145 // Recomputes the visibility state but doesn't set the new value.
4146 dom::VisibilityState ComputeVisibilityState() const;
4148 // Since we wouldn't automatically play media from non-visited page, we need
4149 // to notify window when the page was first visited.
4150 void MaybeActiveMediaComponents();
4152 // Apply the fullscreen state to the document, and trigger related
4153 // events. It returns false if the fullscreen element ready check
4154 // fails and nothing gets changed.
4155 bool ApplyFullscreen(UniquePtr<FullscreenRequest>);
4157 void RemoveDocStyleSheetsFromStyleSets();
4158 void ResetStylesheetsToURI(nsIURI* aURI);
4159 void FillStyleSet();
4160 void FillStyleSetUserAndUASheets();
4161 void FillStyleSetDocumentSheets();
4162 void CompatibilityModeChanged();
4163 bool NeedsQuirksSheet() const {
4164 // SVG documents never load quirk.css.
4165 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4166 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
4168 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
4169 void RemoveContentEditableStyleSheets();
4170 void AddStyleSheetToStyleSets(StyleSheet&);
4171 void RemoveStyleSheetFromStyleSets(StyleSheet&);
4172 void NotifyStyleSheetApplicableStateChanged();
4173 // Just like EnableStyleSheetsForSet, but doesn't check whether
4174 // aSheetSet is null and allows the caller to control whether to set
4175 // aSheetSet as the preferred set in the CSSLoader.
4176 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
4177 bool aUpdateCSSLoader);
4179 already_AddRefed<nsIURI> GetDomainURI();
4180 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4181 const nsACString& aHostString);
4182 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4183 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4185 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4186 mozilla::ErrorResult& aRv);
4187 // A version of WriteCommon used by WebIDL bindings
4188 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4189 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4191 void* GenerateParserKey(void);
4193 private:
4194 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4195 // parameter.
4196 enum class ExecCommandParam : uint8_t {
4197 // Always ignore it.
4198 Ignore,
4199 // Treat the given parameter as-is. If the command requires it, use it.
4200 // Otherwise, ignore it.
4201 String,
4202 // Always treat it as boolean parameter.
4203 Boolean,
4204 // Always treat it as boolean, but inverted.
4205 InvertedBoolean,
4208 using GetEditorCommandFunc = mozilla::EditorCommand*();
4210 struct InternalCommandData {
4211 const char* mXULCommandName;
4212 mozilla::Command mCommand; // uint8_t
4213 // How ConvertToInternalCommand() to treats aValue.
4214 // Its callers don't need to check this.
4215 ExecCommandParam mExecCommandParam; // uint8_t
4216 GetEditorCommandFunc* mGetEditorCommandFunc;
4217 enum class CommandOnTextEditor : uint8_t {
4218 Disabled,
4219 Enabled,
4220 FallThrough, // Not disabled, but handled by HTMLEditor if there is one
4222 CommandOnTextEditor mCommandOnTextEditor;
4224 InternalCommandData()
4225 : mXULCommandName(nullptr),
4226 mCommand(mozilla::Command::DoNothing),
4227 mExecCommandParam(ExecCommandParam::Ignore),
4228 mGetEditorCommandFunc(nullptr),
4229 mCommandOnTextEditor(CommandOnTextEditor::Disabled) {}
4230 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4231 ExecCommandParam aExecCommandParam,
4232 GetEditorCommandFunc aGetEditorCommandFunc,
4233 CommandOnTextEditor aCommandOnTextEditor)
4234 : mXULCommandName(aXULCommandName),
4235 mCommand(aCommand),
4236 mExecCommandParam(aExecCommandParam),
4237 mGetEditorCommandFunc(aGetEditorCommandFunc),
4238 mCommandOnTextEditor(aCommandOnTextEditor) {}
4240 bool IsAvailableOnlyWhenEditable() const {
4241 return mCommand != mozilla::Command::Cut &&
4242 mCommand != mozilla::Command::Copy &&
4243 mCommand != mozilla::Command::Paste &&
4244 mCommand != mozilla::Command::SetDocumentReadOnly &&
4245 mCommand != mozilla::Command::SelectAll;
4247 bool IsCutOrCopyCommand() const {
4248 return mCommand == mozilla::Command::Cut ||
4249 mCommand == mozilla::Command::Copy;
4251 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4255 * AutoEditorCommandTarget considers which editor or global command manager
4256 * handles given command.
4258 class MOZ_RAII AutoEditorCommandTarget {
4259 public:
4260 MOZ_CAN_RUN_SCRIPT AutoEditorCommandTarget(
4261 Document& aDocument, const InternalCommandData& aCommandData);
4262 AutoEditorCommandTarget() = delete;
4263 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget& aOther) =
4264 delete;
4266 bool DoNothing() const { return mDoNothing; }
4267 MOZ_CAN_RUN_SCRIPT bool IsEditable(Document* aDocument) const;
4268 bool IsEditor() const {
4269 MOZ_ASSERT_IF(mEditorCommand, mActiveEditor || mHTMLEditor);
4270 return !!mEditorCommand;
4273 MOZ_CAN_RUN_SCRIPT bool IsCommandEnabled() const;
4274 MOZ_CAN_RUN_SCRIPT nsresult DoCommand(nsIPrincipal* aPrincipal) const;
4275 template <typename ParamType>
4276 MOZ_CAN_RUN_SCRIPT nsresult DoCommandParam(const ParamType& aParam,
4277 nsIPrincipal* aPrincipal) const;
4278 MOZ_CAN_RUN_SCRIPT nsresult
4279 GetCommandStateParams(nsCommandParams& aParams) const;
4281 private:
4282 // The returned editor's life is guaranteed while this instance is alive.
4283 EditorBase* GetTargetEditor() const;
4285 RefPtr<EditorBase> mActiveEditor;
4286 RefPtr<HTMLEditor> mHTMLEditor;
4287 RefPtr<EditorCommand> mEditorCommand;
4288 const InternalCommandData& mCommandData;
4289 bool mDoNothing = false;
4293 * Helper method to initialize sInternalCommandDataHashtable.
4295 static void EnsureInitializeInternalCommandDataHashtable();
4298 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4299 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4300 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4301 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4302 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4303 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4304 * returns a copy of instance created with default constructor. I.e., its
4305 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4306 * is unsupported in such case.
4308 * @param aHTMLCommandName Command name in HTML, e.g., used by
4309 * execCommand().
4310 * @param aValue The value which is set to the 3rd parameter
4311 * of execCommand().
4312 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4313 * Will be set to adjusted value for executing
4314 * the internal command.
4315 * @return Returns a copy of instance created with the
4316 * default constructor if there is no
4317 * corresponding internal command for
4318 * aHTMLCommandName or aValue is invalid for
4319 * found internal command when aAdjustedValue
4320 * is not nullptr. Otherwise, returns a copy of
4321 * instance registered in
4322 * sInternalCommandDataHashtable.
4324 static InternalCommandData ConvertToInternalCommand(
4325 const nsAString& aHTMLCommandName, const nsAString& aValue = u""_ns,
4326 nsAString* aAdjustedValue = nullptr);
4329 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4330 * Since it's a bit field, not a bool member, therefore, we cannot use
4331 * AutoRestorer for it.
4333 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4334 public:
4335 AutoRunningExecCommandMarker() = delete;
4336 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4337 delete;
4338 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4339 MOZ_CAN_RUN_SCRIPT AutoRunningExecCommandMarker(Document& aDocument,
4340 nsIPrincipal* aPrincipal);
4341 ~AutoRunningExecCommandMarker() {
4342 if (mTreatAsUserInput) {
4343 mDocument.mIsRunningExecCommandByChromeOrAddon =
4344 mHasBeenRunningByChromeOrAddon;
4345 } else {
4346 mDocument.mIsRunningExecCommandByContent = mHasBeenRunningByContent;
4350 [[nodiscard]] bool IsSafeToRun() const {
4351 // We don't allow nested calls of execCommand even if the caller is chrome
4352 // script.
4353 if (mTreatAsUserInput) {
4354 return !mHasBeenRunningByChromeOrAddon && !mHasBeenRunningByContent;
4356 // If current call is by content, we should ignore whether nested with a
4357 // call by addon (or chrome script) because the caller wants to emulate
4358 // user input for making it undoable. So, we should treat the first
4359 // call as user input.
4360 return !mHasBeenRunningByContent;
4363 private:
4364 Document& mDocument;
4365 bool mTreatAsUserInput;
4366 bool mHasBeenRunningByContent;
4367 bool mHasBeenRunningByChromeOrAddon;
4370 // Mapping table from HTML command name to internal command.
4371 using InternalCommandDataHashtable =
4372 nsTHashMap<nsStringCaseInsensitiveHashKey, InternalCommandData>;
4373 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4375 mutable std::bitset<static_cast<size_t>(
4376 DeprecatedOperations::eDeprecatedOperationCount)>
4377 mDeprecationWarnedAbout;
4378 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4380 // Lazy-initialization to have mDocGroup initialized in prior to the
4381 UniquePtr<ServoStyleSet> mStyleSet;
4383 protected:
4384 // Never ever call this. Only call GetWindow!
4385 nsPIDOMWindowOuter* GetWindowInternal() const;
4387 // Never ever call this. Only call GetScriptHandlingObject!
4388 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4390 // Never ever call this. Only call AllowXULXBL!
4391 bool InternalAllowXULXBL();
4394 * These methods should be called before and after dispatching
4395 * a mutation event.
4396 * To make this easy and painless, use the mozAutoSubtreeModified helper
4397 * class.
4399 void WillDispatchMutationEvent(nsINode* aTarget);
4400 void MutationEventDispatched(nsINode* aTarget);
4401 friend class mozAutoSubtreeModified;
4403 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4405 nsCString GetContentTypeInternal() const { return mContentType; }
4407 // Update our frame request callback scheduling state, if needed. This will
4408 // schedule or unschedule them, if necessary, and update
4409 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4410 // mPresShell is becoming null; in that case it will be used to get hold of
4411 // the relevant refresh driver.
4412 void UpdateFrameRequestCallbackSchedulingState(
4413 PresShell* aOldPresShell = nullptr);
4415 // Helper for GetScrollingElement/IsScrollingElement.
4416 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4418 void MaybeAllowStorageForOpenerAfterUserInteraction();
4420 void MaybeStoreUserInteractionAsPermission();
4422 // Helpers for GetElementsByName.
4423 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4424 nsAtom* aAtom, void* aData);
4425 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4427 void MaybeResolveReadyForIdle();
4429 using AutomaticStorageAccessPermissionGrantPromise =
4430 MozPromise<bool, bool, true>;
4431 [[nodiscard]] RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4432 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation);
4434 static void AddToplevelLoadingDocument(Document* aDoc);
4435 static void RemoveToplevelLoadingDocument(Document* aDoc);
4436 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4437 friend class cycleCollection;
4439 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4440 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4442 nsString mLastModified;
4444 nsCOMPtr<nsIURI> mDocumentURI;
4445 nsCOMPtr<nsIURI> mOriginalURI;
4446 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4447 nsCOMPtr<nsIURI> mDocumentBaseURI;
4448 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4450 // The base domain of the document for third-party checks.
4451 nsCString mBaseDomain;
4453 // A lazily-constructed URL data for style system to resolve URL values.
4454 RefPtr<URLExtraData> mCachedURLData;
4455 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfoForInternalCSSAndSVGResources;
4457 nsWeakPtr mDocumentLoadGroup;
4459 WeakPtr<nsDocShell> mDocumentContainer;
4461 NotNull<const Encoding*> mCharacterSet;
4462 int32_t mCharacterSetSource;
4464 OriginTrials mTrials;
4466 // This is just a weak pointer; the parent document owns its children.
4467 Document* mParentDocument;
4469 // A reference to the element last returned from GetRootElement().
4470 Element* mCachedRootElement;
4472 // This is maintained by AutoSetRestoreSVGContextPaint.
4473 const SVGContextPaint* mCurrentContextPaint = nullptr;
4475 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4476 // which in turn holds a strong reference to this mNodeInfoManager.
4477 nsNodeInfoManager* mNodeInfoManager;
4478 RefPtr<css::Loader> mCSSLoader;
4479 RefPtr<css::ImageLoader> mStyleImageLoader;
4481 // The object that contains link color declarations (from the <body> mapped
4482 // attributes), mapped attribute caches, and inline style attribute caches.
4483 RefPtr<AttributeStyles> mAttributeStyles;
4485 // Tracking for images in the document.
4486 RefPtr<dom::ImageTracker> mImageTracker;
4488 // A hashtable of ShadowRoots belonging to the composed doc.
4490 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4491 ShadowRootSet mComposedShadowRoots;
4493 using SVGUseElementSet = nsTHashSet<SVGUseElement*>;
4495 // The set of <svg:use> elements that need a shadow tree reclone because the
4496 // tree they map to has changed.
4497 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4499 // The set of all object, embed, video/audio elements or
4500 // nsIObjectLoadingContent or DocumentActivity for which this is
4501 // the owner document. (They might not be in the document.)
4503 // These are non-owning pointers, the elements are responsible for removing
4504 // themselves when they go away.
4505 UniquePtr<nsTHashSet<nsISupports*>> mActivityObservers;
4507 // A hashtable of styled links keyed by address pointer.
4508 nsTHashSet<Link*> mStyledLinks;
4509 #ifdef DEBUG
4510 // Indicates whether mStyledLinks was cleared or not. This is used to track
4511 // state so we can provide useful assertions to consumers of ForgetLink and
4512 // AddStyleRelevantLink.
4513 bool mStyledLinksCleared;
4514 #endif
4516 // The array of all links that need their status resolved. Links must add
4517 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4518 // document.
4519 static const size_t kSegmentSize = 128;
4521 using LinksToUpdateList =
4522 SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>;
4524 LinksToUpdateList mLinksToUpdate;
4526 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4527 RefPtr<SMILAnimationController> mAnimationController;
4529 // Table of element properties for this document.
4530 nsPropertyTable mPropertyTable;
4532 // Our cached .children collection
4533 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4535 // Various DOM lists
4536 RefPtr<nsContentList> mImages;
4537 RefPtr<nsContentList> mEmbeds;
4538 RefPtr<nsContentList> mLinks;
4539 RefPtr<nsContentList> mForms;
4540 RefPtr<nsContentList> mScripts;
4541 nsCOMPtr<nsIHTMLCollection> mApplets;
4542 RefPtr<nsContentList> mAnchors;
4544 // container for per-context fonts (downloadable, SVG, etc.)
4545 RefPtr<FontFaceSet> mFontFaceSet;
4547 // Last time this document or a one of its sub-documents was focused. If
4548 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4549 TimeStamp mLastFocusTime;
4551 // Last time we found any scroll linked effect in this document.
4552 TimeStamp mLastScrollLinkedEffectDetectionTime;
4554 DocumentState mState{DocumentState::LTR_LOCALE};
4556 RefPtr<Promise> mReadyForIdle;
4558 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4560 // Permission Delegate Handler, lazily-initialized in
4561 // GetPermissionDelegateHandler
4562 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4564 bool mCachedStateObjectValid : 1;
4565 bool mBlockAllMixedContent : 1;
4566 bool mBlockAllMixedContentPreloads : 1;
4567 bool mUpgradeInsecureRequests : 1;
4568 bool mUpgradeInsecurePreloads : 1;
4569 bool mDevToolsWatchingDOMMutations : 1;
4571 // True if BIDI is enabled.
4572 bool mBidiEnabled : 1;
4573 // True if we may need to recompute the language prefs for this document.
4574 bool mMayNeedFontPrefsUpdate : 1;
4575 // True if a MathML element has ever been owned by this document.
4576 bool mMathMLEnabled : 1;
4578 // True if this document is the initial document for a window. This should
4579 // basically be true only for documents that exist in newly-opened windows or
4580 // documents created to satisfy a GetDocument() on a window when there's no
4581 // document in it.
4582 bool mIsInitialDocumentInWindow : 1;
4584 // True if this document has ever been the initial document for a window. This
4585 // is useful to determine if a document that was the initial document at one
4586 // point, and became non-initial later.
4587 bool mIsEverInitialDocumentInWindow : 1;
4589 bool mIgnoreDocGroupMismatches : 1;
4591 // True if we're loaded as data and therefor has any dangerous stuff, such
4592 // as scripts and plugins, disabled.
4593 bool mLoadedAsData : 1;
4595 // True if the document is considered for memory reporting as a
4596 // data document
4597 bool mAddedToMemoryReportingAsDataDocument : 1;
4599 // If true, whoever is creating the document has gotten it to the
4600 // point where it's safe to start layout on it.
4601 bool mMayStartLayout : 1;
4603 // True iff we've ever fired a DOMTitleChanged event for this document
4604 bool mHaveFiredTitleChange : 1;
4606 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4607 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4608 // before the initial load completes and when we're in bfcache or unloaded,
4609 // true otherwise.
4610 bool mIsShowing : 1;
4612 // State for IsVisible(). mVisible starts off true. It becomes false when
4613 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4614 // it's false only when we're in bfcache or unloaded.
4615 bool mVisible : 1;
4617 // True if our content viewer has been removed from the docshell
4618 // (it may still be displayed, but in zombie state). Form control data
4619 // has been saved.
4620 bool mRemovedFromDocShell : 1;
4622 // True iff DNS prefetch is allowed for this document. Note that if the
4623 // document has no window, DNS prefetch won't be performed no matter what.
4624 bool mAllowDNSPrefetch : 1;
4626 // True when this document is a static clone of a normal document
4627 bool mIsStaticDocument : 1;
4629 // True while this document is being cloned to a static document.
4630 bool mCreatingStaticClone : 1;
4632 // True if this static document has any <canvas> element with a
4633 // mozPrintCallback property at the time of the clone.
4634 bool mHasPrintCallbacks : 1;
4636 // True iff the document is being unlinked or deleted.
4637 bool mInUnlinkOrDeletion : 1;
4639 // True if document has ever had script handling object.
4640 bool mHasHadScriptHandlingObject : 1;
4642 // True if we're an SVG document being used as an image.
4643 bool mIsBeingUsedAsImage : 1;
4645 // True if our current document URI's scheme enables privileged CSS rules.
4646 bool mChromeRulesEnabled : 1;
4648 // True if we're loaded in a chrome docshell.
4649 bool mInChromeDocShell : 1;
4651 // True is this document is synthetic : stand alone image, video, audio
4652 // file, etc.
4653 bool mIsSyntheticDocument : 1;
4655 // True is there is a pending runnable which will call
4656 // FlushPendingLinkUpdates().
4657 bool mHasLinksToUpdateRunnable : 1;
4659 // True if we're flushing pending link updates.
4660 bool mFlushingPendingLinkUpdates : 1;
4662 // True if a DOMMutationObserver is perhaps attached to a node in the
4663 // document.
4664 bool mMayHaveDOMMutationObservers : 1;
4666 // True if an nsIAnimationObserver is perhaps attached to a node in the
4667 // document.
4668 bool mMayHaveAnimationObservers : 1;
4670 // True if the document has a CSP delivered throuh a header
4671 bool mHasCSPDeliveredThroughHeader : 1;
4673 // True if DisallowBFCaching has been called on this document.
4674 bool mBFCacheDisallowed : 1;
4676 bool mHasHadDefaultView : 1;
4678 // Whether style sheet change events will be dispatched for this document
4679 bool mStyleSheetChangeEventsEnabled : 1;
4681 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4682 // will be dispatched for this document.
4683 bool mDevToolsAnonymousAndShadowEventsEnabled : 1;
4685 // Whether the document was created by a srcdoc iframe.
4686 bool mIsSrcdocDocument : 1;
4688 // Whether this document has a display document and thus is considered to
4689 // be a resource document. Normally this is the same as !!mDisplayDocument,
4690 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4691 // valid in the document's destructor.
4692 bool mHasDisplayDocument : 1;
4694 // Is the current mFontFaceSet valid?
4695 bool mFontFaceSetDirty : 1;
4697 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4698 // (e.g. we're not being parsed at all).
4699 bool mDidFireDOMContentLoaded : 1;
4701 // True if we have frame request callbacks scheduled with the refresh driver.
4702 // This should generally be updated only via
4703 // UpdateFrameRequestCallbackSchedulingState.
4704 bool mFrameRequestCallbacksScheduled : 1;
4706 bool mIsTopLevelContentDocument : 1;
4708 bool mIsContentDocument : 1;
4710 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4711 bool mDidCallBeginLoad : 1;
4713 // True if the encoding menu should be disabled.
4714 bool mEncodingMenuDisabled : 1;
4716 // False if we've disabled link handling for elements inside this document,
4717 // true otherwise.
4718 bool mLinksEnabled : 1;
4720 // True if this document is for an SVG-in-OpenType font.
4721 bool mIsSVGGlyphsDocument : 1;
4723 // True if the document is being destroyed.
4724 bool mInDestructor : 1;
4726 // True if the document has been detached from its content viewer.
4727 bool mIsGoingAway : 1;
4729 // Whether we have filled our style set with all the stylesheets.
4730 bool mStyleSetFilled : 1;
4732 // Whether we have a quirks mode stylesheet in the style set.
4733 bool mQuirkSheetAdded : 1;
4735 // Whether we have a contenteditable.css stylesheet in the style set.
4736 bool mContentEditableSheetAdded : 1;
4738 // Whether we have a designmode.css stylesheet in the style set.
4739 bool mDesignModeSheetAdded : 1;
4741 // True if this document has ever had an HTML or SVG <title> element
4742 // bound to it
4743 bool mMayHaveTitleElement : 1;
4745 bool mDOMLoadingSet : 1;
4746 bool mDOMInteractiveSet : 1;
4747 bool mDOMCompleteSet : 1;
4748 bool mAutoFocusFired : 1;
4750 bool mScrolledToRefAlready : 1;
4751 bool mChangeScrollPosWhenScrollingToRef : 1;
4753 bool mDelayFrameLoaderInitialization : 1;
4755 bool mSynchronousDOMContentLoaded : 1;
4757 // Set to true when the document is possibly controlled by the ServiceWorker.
4758 // Used to prevent multiple requests to ServiceWorkerManager.
4759 bool mMaybeServiceWorkerControlled : 1;
4761 // These member variables cache information about the viewport so we don't
4762 // have to recalculate it each time.
4763 bool mAllowZoom : 1;
4764 bool mValidScaleFloat : 1;
4765 bool mValidMinScale : 1;
4766 bool mValidMaxScale : 1;
4767 bool mWidthStrEmpty : 1;
4769 // Parser aborted. True if the parser of this document was forcibly
4770 // terminated instead of letting it finish at its own pace.
4771 bool mParserAborted : 1;
4773 // Whether we have reported document use counters for this document with
4774 // Telemetry yet. Normally this is only done at document destruction time,
4775 // but for image documents (SVG documents) that are not guaranteed to be
4776 // destroyed, we report use counters when the image cache no longer has any
4777 // imgRequestProxys pointing to them. We track whether we ever reported use
4778 // counters so that we only report them once for the document.
4779 bool mReportedDocumentUseCounters : 1;
4781 bool mHasReportedShadowDOMUsage : 1;
4783 // Whether an event triggered by the refresh driver was delayed because this
4784 // document has suppressed events.
4785 bool mHasDelayedRefreshEvent : 1;
4787 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4788 // to have the right semantics. See
4789 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4790 // flag that is set while the window's 'load' event is firing if this document
4791 // is the window's document.
4792 bool mLoadEventFiring : 1;
4794 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4795 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4796 // What we have instead is a flag that is set if completion of our document
4797 // via document.close() should skip firing the load event. Note that this
4798 // flag is only relevant for HTML documents, but lives here for reasons that
4799 // are documented above on SkipLoadEventAfterClose().
4800 bool mSkipLoadEventAfterClose : 1;
4802 // When false, the .cookies property is completely disabled
4803 bool mDisableCookieAccess : 1;
4805 // When false, the document.write() API is disabled.
4806 bool mDisableDocWrite : 1;
4808 // Has document.write() been called with a recursion depth higher than
4809 // allowed?
4810 bool mTooDeepWriteRecursion : 1;
4813 * Temporary flag that is set in EndUpdate() to ignore
4814 * MaybeEditingStateChanged() script runners from a nested scope.
4816 bool mPendingMaybeEditingStateChanged : 1;
4818 // mHasBeenEditable is set to true when mEditingState is firstly set to
4819 // eDesignMode or eContentEditable.
4820 bool mHasBeenEditable : 1;
4822 // Whether we've warned about the CSS zoom property.
4824 // We don't use the general deprecated operation mechanism for this because we
4825 // also record this as a `CountedUnknownProperty`.
4826 bool mHasWarnedAboutZoom : 1;
4828 // While we're handling an execCommand call by web app, set
4829 // to true.
4830 bool mIsRunningExecCommandByContent : 1;
4831 // While we're handling an execCommand call by an addon (or chrome script),
4832 // set to true.
4833 bool mIsRunningExecCommandByChromeOrAddon : 1;
4835 // True if we should change the readystate to complete after we fire
4836 // DOMContentLoaded. This happens when we abort a load and
4837 // nsDocumentViewer::EndLoad runs while we still have things blocking
4838 // DOMContentLoaded. We wait for those to complete, and then update the
4839 // readystate when they finish.
4840 bool mSetCompleteAfterDOMContentLoaded : 1;
4842 // Set the true if a completed cached stylesheet was created for the document.
4843 bool mDidHitCompleteSheetCache : 1;
4845 // Whether we have initialized mShouldReportUseCounters and
4846 // mShouldSendPageUseCounters, and sent any needed message to the parent
4847 // process to indicate that use counter data will be sent at some later point.
4848 bool mUseCountersInitialized : 1;
4850 // Whether this document should report use counters.
4851 bool mShouldReportUseCounters : 1;
4853 // Whether this document should send page use counters. Set to true after
4854 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4855 bool mShouldSendPageUseCounters : 1;
4857 // Whether the user has interacted with the document or not:
4858 bool mUserHasInteracted : 1;
4860 // We constantly update the user-interaction anti-tracking permission at any
4861 // user-interaction using a timer. This boolean value is set to true when this
4862 // timer is scheduled.
4863 bool mHasUserInteractionTimerScheduled : 1;
4865 // Whether we should resist fingerprinting.
4866 bool mShouldResistFingerprinting : 1;
4868 // Whether we are in private browsing mode.
4869 bool mIsInPrivateBrowsing : 1;
4871 // Whether we're cloning the contents of an SVG use element.
4872 bool mCloningForSVGUse : 1;
4874 bool mAllowDeclarativeShadowRoots : 1;
4876 bool mSuspendDOMNotifications : 1;
4878 // The fingerprinting protections overrides for this document. The value will
4879 // override the default enabled fingerprinting protections for this document.
4880 // This will only get populated if these is one that comes from the local
4881 // fingerprinting protection override pref or WebCompat. Otherwise, a value of
4882 // Nothing() indicates no overrides are present for this document.
4883 Maybe<RFPTarget> mOverriddenFingerprintingSettings;
4885 uint8_t mXMLDeclarationBits;
4887 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4888 // use uint8_t to avoid having to include a bunch of style system headers
4889 // everywhere.
4890 uint8_t mColorSchemeBits = 0;
4892 // Currently active onload blockers.
4893 uint32_t mOnloadBlockCount;
4895 // Tracks if we are currently processing any document.write calls (either
4896 // implicit or explicit). Note that if a write call writes out something which
4897 // would block the parser, then mWriteLevel will be incorrect until the parser
4898 // finishes processing that script.
4899 uint32_t mWriteLevel;
4901 uint32_t mContentEditableCount;
4902 EditingState mEditingState;
4904 // Compatibility mode
4905 nsCompatibility mCompatMode;
4907 // Our readyState
4908 ReadyState mReadyState;
4910 // Ancestor's loading state
4911 bool mAncestorIsLoading;
4913 // Our visibility state
4914 dom::VisibilityState mVisibilityState;
4916 enum Type {
4917 eUnknown, // should never be used
4918 eHTML,
4919 eXHTML,
4920 eGenericXML,
4921 eSVG
4924 Type mType;
4926 uint8_t mDefaultElementType;
4928 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4930 Tri mAllowXULXBL;
4932 bool mSkipDTDSecurityChecks;
4934 // The document's script global object, the object from which the
4935 // document can get its script context and scope. This is the
4936 // *inner* window object.
4937 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4939 // If mIsStaticDocument is true, mOriginalDocument points to the original
4940 // document.
4941 RefPtr<Document> mOriginalDocument;
4943 // The bidi options for this document. What this bitfield means is
4944 // defined in nsBidiUtils.h
4945 uint32_t mBidiOptions;
4947 // The sandbox flags on the document. These reflect the value of the sandbox
4948 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4949 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4950 // possible flags.
4951 uint32_t mSandboxFlags;
4953 // The embedder policy obtained from parsing the HTTP response header or from
4954 // our opener if this is the initial about:blank document.
4955 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4957 RefPtr<nsAtom> mContentLanguage;
4959 // The channel that got passed to Document::StartDocumentLoad(), if any.
4960 nsCOMPtr<nsIChannel> mChannel;
4962 // The CSP for every load lives in the Client within the LoadInfo. For all
4963 // document-initiated subresource loads we can use that cached version of the
4964 // CSP so we do not have to deserialize the CSP from the Client all the time.
4965 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4966 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4968 private:
4969 nsCString mContentType;
4971 protected:
4972 // The document's security info
4973 nsCOMPtr<nsITransportSecurityInfo> mSecurityInfo;
4975 // The channel that failed to load and resulted in an error page.
4976 // This only applies to error pages. Might be null.
4977 nsCOMPtr<nsIChannel> mFailedChannel;
4979 // if this document is part of a multipart document,
4980 // the ID can be used to distinguish it from the other parts.
4981 uint32_t mPartID;
4983 // Cycle collector generation in which we're certain that this document
4984 // won't be collected
4985 uint32_t mMarkedCCGeneration;
4987 PresShell* mPresShell;
4989 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4990 uint32_t mSubtreeModifiedDepth;
4992 // All images in process of being preloaded. This is a hashtable so
4993 // we can remove them as the real image loads start; that way we
4994 // make sure to not keep the image load going when no one cares
4995 // about it anymore.
4996 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4998 // A list of preconnects initiated by the preloader. This prevents
4999 // the same uri from being used more than once, and allows the dom
5000 // builder to not repeat the work of the preloader.
5001 nsTHashMap<nsURIHashKey, bool> mPreloadedPreconnects;
5003 // Current depth of picture elements from parser
5004 uint32_t mPreloadPictureDepth;
5006 // Set if we've found a URL for the current picture
5007 nsString mPreloadPictureFoundSource;
5009 // If we're an external resource document, this will be non-null and will
5010 // point to our "display document": the one that all resource lookups should
5011 // go to.
5012 RefPtr<Document> mDisplayDocument;
5014 uint32_t mEventsSuppressed;
5016 // Any XHR ChannelEventQueues that were suspended on this document while
5017 // events were suppressed.
5018 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
5020 // Any postMessage events that were suspended on this document while events
5021 // were suppressed.
5022 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
5024 RefPtr<EventListener> mSuppressedEventListener;
5027 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5029 uint32_t mIgnoreDestructiveWritesCounter;
5031 // Count of live static clones of this document.
5032 uint32_t mStaticCloneCount;
5034 // If the document is currently printing (or in print preview) this will point
5035 // to the current static clone of this document. This is weak since the clone
5036 // also has a reference to this document.
5037 WeakPtr<Document> mLatestStaticClone;
5039 // Array of nodes that have been blocked to prevent user tracking.
5040 // They most likely have had their nsIChannel canceled by the URL
5041 // classifier. (Safebrowsing)
5043 // Weak nsINode pointers are used to allow nodes to disappear.
5044 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
5046 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5047 // updated on every set of mScriptGlobalObject.
5048 nsPIDOMWindowInner* mWindow;
5050 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
5052 FrameRequestManager mFrameRequestManager;
5054 // This object allows us to evict ourself from the back/forward cache. The
5055 // pointer is non-null iff we're currently in the bfcache.
5056 nsIBFCacheEntry* mBFCacheEntry;
5058 // Our base target.
5059 nsString mBaseTarget;
5061 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
5062 JS::Heap<JS::Value> mCachedStateObject;
5064 uint32_t mInSyncOperationCount;
5066 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
5068 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
5070 uint32_t mBlockDOMContentLoaded;
5072 // Our live MediaQueryLists
5073 LinkedList<MediaQueryList> mDOMMediaQueryLists;
5075 // A hashset to keep track of which {element, imgRequestProxy}
5076 // combination has been processed to avoid considering the same
5077 // element twice for LargestContentfulPaint.
5078 nsTHashtable<LCPEntryHashEntry> mContentIdentifiersForLCP;
5080 // Array of observers
5081 nsTObserverArray<nsIDocumentObserver*> mObservers;
5083 // Flags for use counters used directly by this document.
5084 UseCounters mUseCounters;
5085 // Flags for use counters from resource documents, static clones,
5086 // and SVG images referenced by this document. Those documents propagate
5087 // their use counters up to here, which then count towards the top-level
5088 // document's page use counters.
5089 UseCounters mChildDocumentUseCounters;
5091 // The CSS property use counters.
5092 UniquePtr<StyleUseCounters> mStyleUseCounters;
5094 TimeStamp mPageUnloadingEventTimeStamp;
5096 RefPtr<DocGroup> mDocGroup;
5098 RefPtr<nsCommandManager> mMidasCommandManager;
5100 // The set of all the tracking script URLs. URLs are added to this set by
5101 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5102 // existing in the set means the corresponding script isn't a tracking script.
5103 nsTHashSet<nsCString> mTrackingScripts;
5105 // Pointer to our parser if we're currently in the process of being
5106 // parsed into.
5107 nsCOMPtr<nsIParser> mParser;
5109 // If the document was created from the the prototype cache there will be a
5110 // reference to the prototype document to allow tracing.
5111 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
5113 // Weak reference to our sink for in case we no longer have a parser. This
5114 // will allow us to flush out any pending stuff from the sink even if
5115 // EndLoad() has already happened.
5116 nsWeakPtr mWeakSink;
5118 // Our update nesting level
5119 uint32_t mUpdateNestLevel;
5121 // HTTPS-Only Mode Status
5122 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5123 uint32_t mHttpsOnlyStatus;
5125 enum ViewportType : uint8_t {
5126 DisplayWidthHeight,
5127 Specified,
5128 Unknown,
5131 ViewportType mViewportType;
5133 // viewport-fit described by
5134 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5135 ViewportFitType mViewportFit;
5137 // XXXdholbert This should really be modernized to a nsTHashMap or similar,
5138 // though note that the modernization will need to take care to also convert
5139 // the special hash_table_ops logic (e.g. how SubDocClearEntry clears the
5140 // parent document as part of cleaning up an entry in this table).
5141 UniquePtr<PLDHashTable> mSubDocuments;
5143 class HeaderData;
5144 UniquePtr<HeaderData> mHeaderData;
5146 nsTArray<net::EarlyHintConnectArgs> mEarlyHints;
5148 class TitleChangeEvent;
5149 nsRevocableEventPtr<TitleChangeEvent> mPendingTitleChangeEvent;
5151 RefPtr<nsDOMNavigationTiming> mTiming;
5153 // Recorded time of change to 'loading' state
5154 // or time of the page gets restored from BFCache.
5155 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp;
5157 // Decided to use nsTObserverArray because it allows us to
5158 // remove candidates while iterating them and this is what
5159 // the spec defines. We could implement the spec without
5160 // using nsTObserverArray, however using nsTObserverArray is more clear.
5161 nsTObserverArray<nsWeakPtr> mAutoFocusCandidates;
5163 nsCString mScrollToRef;
5165 // Weak reference to the scope object (aka the script global object)
5166 // that, unlike mScriptGlobalObject, is never unset once set. This
5167 // is a weak reference to avoid leaks due to circular references.
5168 nsWeakPtr mScopeObject;
5170 // Array of intersection observers
5171 nsTHashSet<DOMIntersectionObserver*> mIntersectionObservers;
5173 // Array of resize observers
5174 nsTArray<ResizeObserver*> mResizeObservers;
5176 RefPtr<DOMIntersectionObserver> mLazyLoadObserver;
5178 // Elements observed for a last remembered size.
5179 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5180 nsTHashSet<RefPtr<Element>> mElementsObservedForLastRememberedSize;
5182 // Stack of top layer elements.
5183 nsTArray<nsWeakPtr> mTopLayer;
5185 // The root of the doc tree in which this document is in. This is only
5186 // non-null when this document is in fullscreen mode.
5187 WeakPtr<Document> mFullscreenRoot;
5189 RefPtr<DOMImplementation> mDOMImplementation;
5191 RefPtr<nsContentList> mImageMaps;
5193 // A set of responsive images keyed by address pointer.
5194 nsTHashSet<HTMLImageElement*> mResponsiveContent;
5196 RefPtr<DocumentTimeline> mDocumentTimeline;
5197 LinkedList<DocumentTimeline> mTimelines;
5199 RefPtr<dom::ScriptLoader> mScriptLoader;
5201 // Tracker for scroll-driven animations that are waiting to start.
5202 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5203 RefPtr<ScrollTimelineAnimationTracker> mScrollTimelineAnimationTracker;
5205 // A document "without a browsing context" that owns the content of
5206 // HTMLTemplateElement.
5207 RefPtr<Document> mTemplateContentsOwner;
5209 dom::ExternalResourceMap mExternalResourceMap;
5211 // ScreenOrientation "pending promise" as described by
5212 // http://www.w3.org/TR/screen-orientation/
5213 RefPtr<Promise> mOrientationPendingPromise;
5215 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
5216 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
5217 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
5219 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
5221 // The layout history state that should be used by nodes in this
5222 // document. We only actually store a pointer to it when:
5223 // 1) We have no script global object.
5224 // 2) We haven't had Destroy() called on us yet.
5225 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
5227 // Mapping of wake lock types to sets of wake locks sentinels
5228 // https://w3c.github.io/screen-wake-lock/#internal-slots
5229 nsTHashMap<WakeLockType, nsTHashSet<RefPtr<WakeLockSentinel>>> mActiveLocks;
5231 // The parsed viewport metadata of the last modified <meta name=viewport>
5232 // element.
5233 UniquePtr<ViewportMetaData> mLastModifiedViewportMetaData;
5235 // A tree ordered list of all color-scheme meta tags in this document.
5237 // TODO(emilio): There are other meta tags in the spec that have a similar
5238 // processing model to color-scheme. We could store all in-document meta tags
5239 // here to get sane and fast <meta> element processing.
5240 TreeOrderedArray<HTMLMetaElement*> mColorSchemeMetaTags;
5242 // These member variables cache information about the viewport so we don't
5243 // have to recalculate it each time.
5244 LayoutDeviceToScreenScale mScaleMinFloat;
5245 LayoutDeviceToScreenScale mScaleMaxFloat;
5246 LayoutDeviceToScreenScale mScaleFloat;
5247 CSSToLayoutDeviceScale mPixelRatio;
5249 CSSCoord mMinWidth;
5250 CSSCoord mMaxWidth;
5251 CSSCoord mMinHeight;
5252 CSSCoord mMaxHeight;
5254 RefPtr<EventListenerManager> mListenerManager;
5256 nsCOMPtr<nsIRequest> mOnloadBlocker;
5258 // Gecko-internal sheets used for extensions and such.
5259 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5260 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5262 // Member to store out last-selected stylesheet set.
5263 nsString mLastStyleSheetSet;
5264 nsString mPreferredStyleSheetSet;
5266 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5268 // We lazily calculate declaration blocks for elements with mapped
5269 // attributes. This set contains all elements which need lazy resolution.
5270 nsTHashSet<Element*> mLazyPresElements;
5272 nsTHashSet<RefPtr<nsAtom>> mLanguagesUsed;
5274 // TODO(emilio): Is this hot enough to warrant to be cached?
5275 RefPtr<nsAtom> mLanguageFromCharset;
5277 // Restyle root for servo's style system.
5279 // We store this as an nsINode, rather than as an Element, so that we can
5280 // store the Document node as the restyle root if the entire document (along
5281 // with all document-level native-anonymous content) needs to be restyled.
5283 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5284 // root corresponds to.
5285 nsCOMPtr<nsINode> mServoRestyleRoot;
5286 uint32_t mServoRestyleRootDirtyBits;
5288 // Used in conjunction with the create-an-element-for-the-token algorithm to
5289 // prevent custom element constructors from being able to use document.open(),
5290 // document.close(), and document.write() when they are invoked by the parser.
5291 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5293 // Count of unload/beforeunload/pagehide operations in progress.
5294 uint32_t mIgnoreOpensDuringUnloadCounter;
5296 nsCOMPtr<nsIDOMXULCommandDispatcher>
5297 mCommandDispatcher; // [OWNER] of the focus tracker
5299 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5300 RefPtr<XULPersist> mXULPersist;
5301 RefPtr<ChromeObserver> mChromeObserver;
5303 RefPtr<HTMLAllCollection> mAll;
5305 nsTHashSet<RefPtr<WorkerDocumentListener>> mWorkerListeners;
5307 // Pres shell resolution saved before entering fullscreen mode.
5308 float mSavedResolution;
5310 // Pres shell resolution saved before creating a MobileViewportManager.
5311 float mSavedResolutionBeforeMVM;
5313 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5315 bool mHasStoragePermission;
5317 // Document generation. Gets incremented everytime it changes.
5318 int32_t mGeneration;
5320 // Cached TabSizes values for the document.
5321 int32_t mCachedTabSizeGeneration;
5322 nsTabSizes mCachedTabSizes;
5324 // This is equal to document's principal but with an isolation key. See
5325 // StoragePrincipalHelper.h to know more.
5326 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5328 // The cached storage principal for this document.
5329 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5330 // which is required due to its CloneDocHelper() call site. :-(
5331 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5333 // The cached cookie principal for this document.
5334 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5335 // which is required due to its CloneDocHelper() call site. :-(
5336 mutable nsCOMPtr<nsIPrincipal> mActiveCookiePrincipal;
5338 // See GetNextFormNumber and GetNextControlNumber.
5339 int32_t mNextFormNumber;
5340 int32_t mNextControlNumber;
5342 uint32_t mMediaElementWithMSECount = 0;
5344 // Scope preloads per document. This is used by speculative loading as well.
5345 PreloadService mPreloadService;
5347 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5348 bool mShouldNotifyFetchSuccess;
5350 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5351 bool mShouldNotifyFormOrPasswordRemoved;
5353 // Record page load telemetry
5354 void RecordPageLoadEventTelemetry(
5355 glean::perf::PageLoadExtra& aEventTelemetryData);
5357 // Accumulate JS telemetry collected
5358 void AccumulateJSTelemetry(
5359 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5361 // Accumulate page load metrics
5362 void AccumulatePageLoadTelemetry(
5363 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5365 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5366 // Not holding strong refs here since we don't actually use the BBCs.
5367 nsTArray<const BrowserBridgeChild*> mOOPChildrenLoading;
5369 // Registry of custom highlight definitions associated with this document.
5370 RefPtr<class HighlightRegistry> mHighlightRegistry;
5372 // Used for tracking a number of recent canvas extractions (e.g. toDataURL),
5373 // this is used for a canvas fingerprinter detection heuristic.
5374 nsTArray<CanvasUsage> mCanvasUsage;
5375 uint64_t mLastCanvasUsage = 0;
5377 UniquePtr<RadioGroupContainer> mRadioGroupContainer;
5379 public:
5380 // Needs to be public because the bindings code pokes at it.
5381 JS::ExpandoAndGeneration mExpandoAndGeneration;
5383 bool HasPendingInitialTranslation();
5385 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5386 mL10nProtoElements;
5388 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5389 void SetSavedResolutionBeforeMVM(float aResolution) {
5390 mSavedResolutionBeforeMVM = aResolution;
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___ */