Bug 1842773 - Part 5: Add ArrayBuffer.prototype.{maxByteLength,resizable} getters...
[gecko.git] / dom / base / Document.h
blob25201b807c5485d19d12188603f7d4cfd67899b5
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 * Are plugins allowed in this document ?
1197 bool GetAllowPlugins();
1200 * Set the sub document for aContent to aSubDoc.
1202 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1205 * Get the sub document for aContent
1207 Document* GetSubDocumentFor(nsIContent* aContent) const;
1210 * Get the content node for which this document is a sub document.
1212 Element* GetEmbedderElement() const;
1215 * Return the doctype for this document.
1217 DocumentType* GetDoctype() const;
1220 * Return the root element for this document.
1222 Element* GetRootElement() const;
1224 Selection* GetSelection(ErrorResult& aRv);
1226 void MakeBrowsingContextNonSynthetic();
1227 nsresult HasStorageAccessSync(bool& aHasStorageAccess);
1228 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1230 StorageAccessAPIHelper::PerformPermissionGrant CreatePermissionGrantPromise(
1231 nsPIDOMWindowInner* aInnerWindow, nsIPrincipal* aPrincipal,
1232 bool aHasUserInteraction, bool aRequireUserInteraction,
1233 const Maybe<nsCString>& aTopLevelBaseDomain, bool aFrameOnly);
1235 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1237 already_AddRefed<Promise> RequestStorageAccessForOrigin(
1238 const nsAString& aThirdPartyOrigin, const bool aRequireUserInteraction,
1239 ErrorResult& aRv);
1241 already_AddRefed<Promise> RequestStorageAccessUnderSite(
1242 const nsAString& aSerializedSite, ErrorResult& aRv);
1243 already_AddRefed<Promise> CompleteStorageAccessRequestFromSite(
1244 const nsAString& aSerializedOrigin, ErrorResult& aRv);
1246 bool UseRegularPrincipal() const;
1249 * Gets the event target to dispatch key events to if there is no focused
1250 * content in the document.
1252 virtual Element* GetUnfocusedKeyEventTarget();
1255 * Retrieve information about the viewport as a data structure.
1256 * This will return information in the viewport META data section
1257 * of the document. This can be used in lieu of ProcessViewportInfo(),
1258 * which places the viewport information in the document header instead
1259 * of returning it directly.
1261 * @param aDisplaySize size of the on-screen display area for this
1262 * document, in device pixels.
1264 * NOTE: If the site is optimized for mobile (via the doctype), this
1265 * will return viewport information that specifies default information.
1267 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1269 void SetMetaViewportData(UniquePtr<ViewportMetaData> aData);
1271 // Returns a ViewportMetaData for this document.
1272 ViewportMetaData GetViewportMetaData() const;
1275 * True iff this doc will ignore manual character encoding overrides.
1277 virtual bool WillIgnoreCharsetOverride() { return true; }
1280 * Return whether the document was created by a srcdoc iframe.
1282 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1285 * Sets whether the document was created by a srcdoc iframe.
1287 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1288 mIsSrcdocDocument = aIsSrcdocDocument;
1292 * Gets the srcdoc string from within the channel (assuming both exist).
1293 * Returns a void string if this isn't a srcdoc document or if
1294 * the channel has not been set.
1296 nsresult GetSrcdocData(nsAString& aSrcdocData);
1298 already_AddRefed<AnonymousContent> InsertAnonymousContent(bool aForce,
1299 ErrorResult&);
1300 void RemoveAnonymousContent(AnonymousContent&);
1302 * If aNode is a descendant of anonymous content inserted by
1303 * InsertAnonymousContent, this method returns the root element of the
1304 * inserted anonymous content (in other words, the clone of the aElement
1305 * that was passed to InsertAnonymousContent).
1307 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1308 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1309 return mAnonymousContents;
1312 TimeStamp GetPageUnloadingEventTimeStamp() const {
1313 if (!mParentDocument) {
1314 return mPageUnloadingEventTimeStamp;
1317 TimeStamp parentTimeStamp(
1318 mParentDocument->GetPageUnloadingEventTimeStamp());
1319 if (parentTimeStamp.IsNull()) {
1320 return mPageUnloadingEventTimeStamp;
1323 if (!mPageUnloadingEventTimeStamp ||
1324 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1325 return parentTimeStamp;
1328 return mPageUnloadingEventTimeStamp;
1331 void NotifyLayerManagerRecreated();
1333 // Add an element to the list of elements that need their mapped attributes
1334 // resolved to a declaration block.
1336 // These are weak pointers, manually unschedule them when an element is
1337 // removed from the tree.
1338 void ScheduleForPresAttrEvaluation(Element* aElement);
1340 // Un-schedule an element scheduled by ScheduleForPresAttrEvaluation,
1341 // generally when it's unbound from the tree.
1342 void UnscheduleForPresAttrEvaluation(Element* aElement);
1344 // Resolve all presentational attributes scheduled in
1345 // ScheduleForPresAttrEvaluation
1346 void ResolveScheduledPresAttrs() {
1347 if (mLazyPresElements.IsEmpty()) {
1348 return;
1350 DoResolveScheduledPresAttrs();
1353 Maybe<ClientInfo> GetClientInfo() const;
1354 Maybe<ClientState> GetClientState() const;
1355 Maybe<ServiceWorkerDescriptor> GetController() const;
1357 // Given a node, get a weak reference to it and append that reference to
1358 // mBlockedNodesByClassifier. Can be used later on to look up a node in it.
1359 // (e.g., by the UI)
1360 // /
1361 void AddBlockedNodeByClassifier(nsINode* aNode) {
1362 if (aNode) {
1363 mBlockedNodesByClassifier.AppendElement(do_GetWeakReference(aNode));
1367 // Returns the size of the mBlockedNodesByClassifier array.
1369 // This array contains nodes that have been blocked to prevent user tracking,
1370 // fingerprinting, cryptomining, etc. They most likely have had their
1371 // nsIChannel canceled by the URL classifier (Safebrowsing).
1373 // A script can subsequently use GetBlockedNodesByClassifier()
1374 // to get a list of references to these nodes.
1376 // Note:
1377 // This expresses how many tracking nodes have been blocked for this document
1378 // since its beginning, not how many of them are still around in the DOM tree.
1379 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1380 // array but they are not removed when those nodes are removed from the tree
1381 // or even garbage collected.
1382 size_t BlockedNodeByClassifierCount() const {
1383 return mBlockedNodesByClassifier.Length();
1386 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1387 // This array contains nodes that have been blocked to prevent
1388 // user tracking. They most likely have had their nsIChannel
1389 // canceled by the URL classifier (Safebrowsing).
1390 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1392 // Helper method that returns true if the document has storage-access sandbox
1393 // flag.
1394 bool StorageAccessSandboxed() const;
1396 // Helper method that returns true if storage access API is enabled and
1397 // the passed flag has storage-access sandbox flag.
1398 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1400 // Returns the cookie jar settings for this and sub contexts.
1401 nsICookieJarSettings* CookieJarSettings();
1403 // Returns whether this document is using unpartitioned cookies
1404 bool UsingStorageAccess();
1406 // Returns whether the storage access permission of the document is granted by
1407 // the allow list.
1408 bool HasStorageAccessPermissionGrantedByAllowList();
1410 // Increments the document generation.
1411 inline void Changed() { ++mGeneration; }
1413 // Returns the current generation.
1414 inline int32_t GetGeneration() const { return mGeneration; }
1416 // Adds cached sizes values to aSizes if there's any
1417 // cached value and if the document generation hasn't
1418 // changed since the cache was created.
1419 // Returns true if sizes were added.
1420 bool GetCachedSizes(nsTabSizes* aSizes);
1422 // Sets the cache sizes for the current generation.
1423 void SetCachedSizes(nsTabSizes* aSizes);
1426 * Should be called when an element's editable changes as a result of
1427 * changing its contentEditable attribute/property.
1429 * The change should be +1 if the contentEditable attribute/property was
1430 * changed to true, -1 if it was changed to false.
1432 void ChangeContentEditableCount(Element*, int32_t aChange);
1433 MOZ_CAN_RUN_SCRIPT void DeferredContentEditableCountChange(Element*);
1435 enum class EditingState : int8_t {
1436 eTearingDown = -2,
1437 eSettingUp = -1,
1438 eOff = 0,
1439 eDesignMode,
1440 eContentEditable
1444 * Returns the editing state of the document (not editable, contentEditable or
1445 * designMode).
1447 EditingState GetEditingState() const { return mEditingState; }
1450 * Returns whether the document is editable.
1452 bool IsEditingOn() const {
1453 return GetEditingState() == EditingState::eDesignMode ||
1454 GetEditingState() == EditingState::eContentEditable;
1457 class MOZ_STACK_CLASS nsAutoEditingState {
1458 public:
1459 nsAutoEditingState(Document* aDoc, EditingState aState)
1460 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1461 aDoc->mEditingState = aState;
1463 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1465 private:
1466 RefPtr<Document> mDoc;
1467 EditingState mSavedState;
1469 friend class nsAutoEditingState;
1472 * Set the editing state of the document. Don't use this if you want
1473 * to enable/disable editing, call EditingStateChanged() or
1474 * SetDesignMode().
1476 void SetEditingState(EditingState aState) { mEditingState = aState; }
1479 * Called when this Document's editor is destroyed.
1481 void TearingDownEditor();
1483 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1485 // Gets the next form number.
1487 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1488 // parser inserted form element.
1489 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1491 // Gets the next form control number.
1493 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1494 // parser inserted form control element.
1495 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1497 PreloadService& Preloads() { return mPreloadService; }
1499 bool HasThirdPartyChannel();
1501 bool ShouldIncludeInTelemetry() const;
1503 void AddMediaElementWithMSE();
1504 void RemoveMediaElementWithMSE();
1506 void DoNotifyPossibleTitleChange();
1508 void InitFeaturePolicy();
1509 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1511 void EnsureNotEnteringAndExitFullscreen();
1513 protected:
1514 friend class nsUnblockOnloadEvent;
1516 nsresult InitCSP(nsIChannel* aChannel);
1517 nsresult InitCOEP(nsIChannel* aChannel);
1519 nsresult InitReferrerInfo(nsIChannel* aChannel);
1521 void PostUnblockOnloadEvent();
1523 void DoUnblockOnload();
1525 void DoResolveScheduledPresAttrs();
1527 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1529 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1530 NotNull<const Encoding*>& aEncoding,
1531 nsHtml5TreeOpExecutor* aExecutor);
1533 MOZ_CAN_RUN_SCRIPT void DispatchContentLoadedEvents();
1535 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1536 MOZ_CAN_RUN_SCRIPT_BOUNDARY void DispatchPageTransition(
1537 EventTarget* aDispatchTarget, const nsAString& aType, bool aInFrameSwap,
1538 bool aPersisted, bool aOnlySystemGroup);
1540 // Call this before the document does something that will unbind all content.
1541 // That will stop us from doing a lot of work as each element is removed.
1542 void DestroyElementMaps();
1544 Element* GetRootElementInternal() const;
1546 void SetPageUnloadingEventTimeStamp() {
1547 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1548 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1551 void CleanUnloadEventsTimeStamp() {
1552 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1553 mPageUnloadingEventTimeStamp = TimeStamp();
1557 * Clears any Servo element data stored on Elements in the document.
1559 void ClearStaleServoData();
1562 * Do the tree-disconnection that ResetToURI and document.open need to do.
1564 void DisconnectNodeTree();
1567 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1568 * "CheckKeyPressEventModel" event to check whether we should dispatch
1569 * keypress events in confluent model or split model. This should be
1570 * called only when mEditingState is changed to eDesignMode or
1571 * eConentEditable at first time.
1573 void MaybeDispatchCheckKeyPressEventModelEvent();
1575 /* Midas implementation */
1576 nsCommandManager* GetMidasCommandManager();
1578 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1580 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1581 // of places, and I'm pretty sure the exact ExecCommand call it
1582 // makes cannot actually run script.
1583 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1585 void MaybeEditingStateChanged();
1587 public:
1588 // Get the root <html> element, or return null if there isn't one (e.g.
1589 // if the root isn't <html>)
1590 Element* GetHtmlElement() const;
1591 // Returns the first child of GetHtmlContent which has the given tag,
1592 // or nullptr if that doesn't exist.
1593 Element* GetHtmlChildElement(nsAtom* aTag);
1594 // Get the canonical <body> element, or return null if there isn't one (e.g.
1595 // if the root isn't <html> or if the <body> isn't there)
1596 HTMLBodyElement* GetBodyElement();
1597 // Get the canonical <head> element, or return null if there isn't one (e.g.
1598 // if the root isn't <html> or if the <head> isn't there)
1599 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1600 // Get the "body" in the sense of document.body: The first <body> or
1601 // <frameset> that's a child of a root <html>
1602 nsGenericHTMLElement* GetBody();
1603 // Set the "body" in the sense of document.body.
1604 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1605 // Get the "head" element in the sense of document.head.
1606 HTMLSharedElement* GetHead();
1608 ServoStyleSet* StyleSetForPresShell() const {
1609 MOZ_ASSERT(!!mStyleSet.get());
1610 return mStyleSet.get();
1613 inline ServoStyleSet& EnsureStyleSet() const;
1615 // ShadowRoot has APIs that can change styles. This notifies the shell that
1616 // stlyes applicable in the shadow tree have potentially changed.
1617 void RecordShadowStyleChange(ShadowRoot&);
1619 // Needs to be called any time the applicable style can has changed, in order
1620 // to schedule a style flush and setup all the relevant state.
1622 // If we know the stylesheet change applies only to a shadow tree we can avoid
1623 // some work (like updating the font-face-set / counter-styles / etc, as those
1624 // are global).
1625 void ApplicableStylesChanged(bool aKnownInShadowTree = false);
1627 // Whether we filled the style set with any style sheet. Only meant to be used
1628 // from DocumentOrShadowRoot::Traverse.
1629 bool StyleSetFilled() const { return mStyleSetFilled; }
1632 * Accessors to the collection of stylesheets owned by this document.
1633 * Style sheets are ordered, most significant last.
1636 void InsertSheetAt(size_t aIndex, StyleSheet&);
1639 * Add a stylesheet to the document
1641 * TODO(emilio): This is only used by parts of editor that are no longer in
1642 * use by m-c or c-c, so remove.
1644 void AddStyleSheet(StyleSheet* aSheet) {
1645 MOZ_ASSERT(aSheet);
1646 InsertSheetAt(SheetCount(), *aSheet);
1650 * Notify the document that the applicable state of the sheet changed
1651 * and that observers should be notified and style sets updated
1653 void StyleSheetApplicableStateChanged(StyleSheet&);
1654 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1655 void PostStyleSheetRemovedEvent(StyleSheet&);
1656 void PostCustomPropertyRegistered(const dom::PropertyDefinition&);
1658 enum additionalSheetType {
1659 eAgentSheet,
1660 eUserSheet,
1661 eAuthorSheet,
1662 AdditionalSheetTypeCount
1665 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1666 nsIURI* aSheetURI);
1667 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1668 StyleSheet* aSheet);
1669 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1671 StyleSheet* GetFirstAdditionalAuthorSheet() {
1672 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1676 * Returns the index that aSheet should be inserted at to maintain document
1677 * ordering.
1679 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1682 * Get this document's CSSLoader. This is guaranteed to not return null.
1684 css::Loader* CSSLoader() const { return mCSSLoader; }
1687 * Get this document's StyleImageLoader. This is guaranteed to not return
1688 * null.
1690 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1693 * Get the channel that was passed to StartDocumentLoad or Reset for this
1694 * document. Note that this may be null in some cases (eg if
1695 * StartDocumentLoad or Reset were never called)
1697 nsIChannel* GetChannel() const { return mChannel; }
1700 * Get this document's attribute stylesheet. May return null if
1701 * there isn't one.
1703 AttributeStyles* GetAttributeStyles() const { return mAttributeStyles.get(); }
1705 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1708 * Get/set the object from which the context for the event/script handling can
1709 * be got. Normally GetScriptHandlingObject() returns the same object as
1710 * GetScriptGlobalObject(), but if the document is loaded as data,
1711 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1712 * aHasHadScriptHandlingObject is set true if document has had the object
1713 * for event/script handling. Do not process any events/script if the method
1714 * returns null, but aHasHadScriptHandlingObject is true.
1716 nsIScriptGlobalObject* GetScriptHandlingObject(
1717 bool& aHasHadScriptHandlingObject) const {
1718 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1719 return mScriptGlobalObject ? mScriptGlobalObject.get()
1720 : GetScriptHandlingObjectInternal();
1722 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1725 * Get the object that is used as the scope for all of the content
1726 * wrappers whose owner document is this document. Unlike the script global
1727 * object, this will only return null when the global object for this
1728 * document is truly gone. Use this object when you're trying to find a
1729 * content wrapper in XPConnect.
1731 nsIGlobalObject* GetScopeObject() const;
1732 void SetScopeObject(nsIGlobalObject* aGlobal);
1735 * Return the window containing the document (the outer window).
1737 nsPIDOMWindowOuter* GetWindow() const {
1738 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1741 bool IsInBackgroundWindow() const {
1742 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1743 return outer && outer->IsBackground();
1747 * Return the inner window used as the script compilation scope for
1748 * this document. If you're not absolutely sure you need this, use
1749 * GetWindow().
1751 nsPIDOMWindowInner* GetInnerWindow() const {
1752 return mRemovedFromDocShell ? nullptr : mWindow;
1756 * Return the outer window ID.
1758 uint64_t OuterWindowID() const {
1759 nsPIDOMWindowOuter* window = GetWindow();
1760 return window ? window->WindowID() : 0;
1764 * Return the inner window ID.
1766 uint64_t InnerWindowID() const {
1767 nsPIDOMWindowInner* window = GetInnerWindow();
1768 return window ? window->WindowID() : 0;
1772 * Return WindowGlobalChild that is associated with the inner window.
1774 WindowGlobalChild* GetWindowGlobalChild() {
1775 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1776 : nullptr;
1780 * Return WindowContext associated with the inner window.
1782 WindowContext* GetWindowContext() const {
1783 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1786 bool IsTopLevelWindowInactive() const {
1787 return mState.HasState(DocumentState::WINDOW_INACTIVE);
1791 * Get the script loader for this document
1793 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1796 * Add/Remove an element to the document's id and name hashes
1798 void AddToIdTable(Element* aElement, nsAtom* aId);
1799 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1800 void AddToNameTable(Element* aElement, nsAtom* aName);
1801 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1804 * Returns all elements in the top layer in the insertion order.
1806 nsTArray<Element*> GetTopLayer() const;
1808 bool TopLayerContains(Element&) const;
1810 // Do the "fullscreen element ready check" from the fullscreen spec.
1811 // It returns true if the given element is allowed to go into fullscreen.
1812 // It is responsive to dispatch "fullscreenerror" event when necessary.
1813 bool FullscreenElementReadyCheck(FullscreenRequest&);
1816 * When this is called on content process, this asynchronously requests that
1817 * the document make aElement the fullscreen element, and move into fullscreen
1818 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1819 * and it can be returned to fullscreen status by calling
1820 * RestorePreviousFullscreenState().
1821 * If on chrome process, this is synchronously.
1823 * Note that requesting fullscreen in a document also makes the element which
1824 * contains this document in this document's parent document fullscreen. i.e.
1825 * the <iframe> or <browser> that contains this document is also mode
1826 * fullscreen. This happens recursively in all ancestor documents.
1828 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1829 bool aApplyFullscreenDirectly = false);
1831 private:
1832 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1833 bool aApplyFullscreenDirectly);
1834 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1835 bool aApplyFullscreenDirectly);
1837 // Pushes aElement onto the top layer
1838 void TopLayerPush(Element&);
1840 // Removes the topmost element for which aPredicate returns true from the top
1841 // layer. The removed element, if any, is returned.
1842 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicate);
1844 // Removes the given element from the top layer. The removed element, if any,
1845 // is returned.
1846 Element* TopLayerPop(Element&);
1848 MOZ_CAN_RUN_SCRIPT bool TryAutoFocusCandidate(Element& aElement);
1850 public:
1851 // Removes all the elements with fullscreen flag set from the top layer, and
1852 // clears their fullscreen flag.
1853 void CleanupFullscreenState();
1855 // Pops the fullscreen element from the top layer and clears its
1856 // fullscreen flag. Returns whether there was any fullscreen element.
1857 enum class UpdateViewport : bool { No, Yes };
1858 bool PopFullscreenElement(UpdateViewport = UpdateViewport::Yes);
1860 // Pushes the given element into the top of top layer and set fullscreen
1861 // flag.
1862 void SetFullscreenElement(Element&);
1864 // Whether we has pending fullscreen request.
1865 bool HasPendingFullscreenRequests();
1868 * When Esc key is pressed, cancel the dialog element if the document is
1869 * blocked by the dialog or hide popover if popover is shown.
1871 MOZ_CAN_RUN_SCRIPT void HandleEscKey();
1873 void AddModalDialog(HTMLDialogElement&);
1874 void RemoveModalDialog(HTMLDialogElement&);
1877 * Called when a frame in a child process has entered fullscreen or when a
1878 * fullscreen frame in a child process changes to another origin.
1879 * aFrameElement is the frame element which contains the child-process
1880 * fullscreen document.
1882 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1885 * Called when a frame in a remote child document has rolled back fullscreen
1886 * so that all its top layer are empty; we must continue the
1887 * rollback in this parent process' doc tree branch which is fullscreen.
1888 * Note that only one branch of the document tree can have its documents in
1889 * fullscreen state at one time. We're in inconsistent state if a
1890 * fullscreen document has a parent and that parent isn't fullscreen. We
1891 * preserve this property across process boundaries.
1893 void RemoteFrameFullscreenReverted();
1896 * Restores the previous fullscreen element to fullscreen status. If there
1897 * is no former fullscreen element, this exits fullscreen, moving the
1898 * top-level browser window out of fullscreen mode.
1900 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1903 * Returns true if this document is a fullscreen leaf document, i.e. it
1904 * is in fullscreen mode and has no fullscreen children.
1906 bool IsFullscreenLeaf();
1909 * Returns the document which is at the root of this document's branch
1910 * in the in-process document tree. Returns nullptr if the document isn't
1911 * fullscreen.
1913 Document* GetFullscreenRoot() const { return mFullscreenRoot; }
1915 size_t CountFullscreenElements() const;
1918 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1919 * in this document.
1921 void SetFullscreenRoot(Document* aRoot) { mFullscreenRoot = aRoot; }
1924 * Synchronously cleans up the fullscreen state on the given document.
1926 * Calling this without performing fullscreen transition could lead
1927 * to undesired effect (the transition happens after document state
1928 * flips), hence it should only be called either by nsGlobalWindow
1929 * when we have performed the transition, or when it is necessary to
1930 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1931 * should be called instead.
1933 * aDocument must not be null.
1935 static void ExitFullscreenInDocTree(Document* aDocument);
1938 * Ask the document to exit fullscreen state asynchronously.
1940 * Different from ExitFullscreenInDocTree(), this allows the window
1941 * to perform fullscreen transition first if any.
1943 * If aDocument is null, it will exit fullscreen from all documents
1944 * in all windows.
1946 static void AsyncExitFullscreen(Document* aDocument);
1949 * Handles any pending fullscreen in aDocument or its subdocuments.
1951 * Returns whether there is any fullscreen request handled.
1953 static bool HandlePendingFullscreenRequests(Document* aDocument);
1956 * Clear pending fullscreen in aDocument.
1958 static void ClearPendingFullscreenRequests(Document* aDocument);
1960 // ScreenOrientation related APIs
1962 void ClearOrientationPendingPromise();
1963 bool SetOrientationPendingPromise(Promise* aPromise);
1964 Promise* GetOrientationPendingPromise() const {
1965 return mOrientationPendingPromise;
1968 //----------------------------------------------------------------------
1970 // Document notification API's
1973 * Add a new observer of document change notifications. Whenever
1974 * content is changed, appended, inserted or removed the observers are
1975 * informed. An observer that is already observing the document must
1976 * not be added without being removed first.
1978 void AddObserver(nsIDocumentObserver* aObserver);
1981 * Remove an observer of document change notifications. This will
1982 * return false if the observer cannot be found.
1984 bool RemoveObserver(nsIDocumentObserver* aObserver);
1986 // Observation hooks used to propagate notifications to document observers.
1987 // BeginUpdate must be called before any batch of modifications of the
1988 // content model or of style data, EndUpdate must be called afterward.
1989 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1990 void BeginUpdate();
1991 void EndUpdate();
1992 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
1994 void BeginLoad();
1995 virtual void EndLoad();
1997 enum ReadyState {
1998 READYSTATE_UNINITIALIZED = 0,
1999 READYSTATE_LOADING = 1,
2000 READYSTATE_INTERACTIVE = 3,
2001 READYSTATE_COMPLETE = 4
2003 // Set the readystate of the document. If aUpdateTimingInformation is true,
2004 // this will record relevant timestamps in the document's performance timing.
2005 // Some consumers (document.open is the only one right now, actually) don't
2006 // want to do that, though.
2007 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2008 ReadyState GetReadyStateEnum() { return mReadyState; }
2010 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2011 ReadyState aNewState);
2013 void NotifyAbortedLoad();
2015 // Notify that an element changed state. This must happen under a
2016 // scriptblocker but NOT within a begin/end update.
2017 void ElementStateChanged(Element*, ElementState);
2019 // Update a set of document states that may have changed.
2020 // This should only be called by callers whose state is also reflected in the
2021 // implementation of Document::State.
2023 // aNotify controls whether we notify our DocumentStatesChanged observers.
2024 void UpdateDocumentStates(DocumentState aMaybeChangedStates, bool aNotify);
2026 void ResetDocumentDirection();
2028 // Observation hooks for style data to propagate notifications
2029 // to document observers
2030 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2031 void RuleAdded(StyleSheet&, css::Rule&);
2032 void RuleRemoved(StyleSheet&, css::Rule&);
2033 void SheetCloned(StyleSheet&) {}
2034 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2037 * Flush notifications for this document and its parent documents
2038 * (since those may affect the layout of this one).
2040 void FlushPendingNotifications(FlushType aType);
2043 * Another variant of the above FlushPendingNotifications. This function
2044 * takes a ChangesToFlush to specify whether throttled animations are flushed
2045 * or not.
2046 * If in doubt, use the above FlushPendingNotifications.
2048 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2049 void FlushPendingNotifications(ChangesToFlush aFlush);
2052 * Calls FlushPendingNotifications on any external resources this document
2053 * has. If this document has no external resources or is an external resource
2054 * itself this does nothing. This should only be called with
2055 * aType >= FlushType::Style.
2057 void FlushExternalResources(FlushType aType);
2059 void AddWorkerDocumentListener(WorkerDocumentListener* aListener);
2060 void RemoveWorkerDocumentListener(WorkerDocumentListener* aListener);
2062 // Triggers an update of <svg:use> element shadow trees.
2063 void UpdateSVGUseElementShadowTrees() {
2064 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2065 return;
2067 DoUpdateSVGUseElementShadowTrees();
2071 * Only to be used inside Gecko, you can't really do anything with the
2072 * pointer outside Gecko anyway.
2074 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2077 * Reset the document using the given channel and loadgroup. This works
2078 * like ResetToURI, but also sets the document's channel to aChannel.
2079 * The principal of the document will be set from the channel.
2081 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2084 * Reset this document to aURI, aLoadGroup, aPrincipal and
2085 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2086 * content principal based on aURI will be used.
2088 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2089 nsIPrincipal* aPrincipal,
2090 nsIPrincipal* aPartitionedPrincipal);
2093 * Set the container (docshell) for this document. Virtual so that
2094 * docshell can call it.
2096 virtual void SetContainer(nsDocShell* aContainer);
2099 * Get the container (docshell) for this document.
2101 nsISupports* GetContainer() const;
2104 * Get the container's load context for this document.
2106 nsILoadContext* GetLoadContext() const;
2109 * Get docshell the for this document.
2111 nsIDocShell* GetDocShell() const;
2114 * Set and get XML declaration. If aVersion is null there is no declaration.
2115 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2116 * was no standalone parameter in the declaration, that it was given as no,
2117 * or that it was given as yes.
2119 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2120 const int32_t aStandalone);
2121 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2122 nsAString& Standalone);
2125 * Returns the bits for the color-scheme specified by the
2126 * <meta name="color-scheme">.
2128 uint8_t GetColorSchemeBits() const { return mColorSchemeBits; }
2131 * Traverses the DOM and computes the supported color schemes as per
2132 * https://html.spec.whatwg.org/#meta-color-scheme
2134 void RecomputeColorScheme();
2135 void AddColorSchemeMeta(HTMLMetaElement&);
2136 void RemoveColorSchemeMeta(HTMLMetaElement&);
2139 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2140 * regular HTML document with Content-Type "text/html", image documents and
2141 * media documents). Returns false for XHTML and any other documents parsed
2142 * by the XML parser.
2144 bool IsHTMLDocument() const { return mType == eHTML; }
2145 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2146 bool IsImageDocument() const {
2147 return MediaDocumentKind() == MediaDocumentKind::Image;
2149 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2150 bool IsSVGDocument() const { return mType == eSVG; }
2151 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2152 bool LoadsFullXULStyleSheetUpFront() {
2153 if (IsSVGDocument()) {
2154 return false;
2156 return AllowXULXBL();
2159 bool IsScriptEnabled() const;
2162 * Returns true if this document was created from a nsXULPrototypeDocument.
2164 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2166 * Returns the prototype the document was created from, or null if it was not
2167 * created from a prototype.
2169 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2171 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2172 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2173 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2176 bool IsContentDocument() const { return mIsContentDocument; }
2177 void SetIsContentDocument(bool aIsContentDocument) {
2178 mIsContentDocument = aIsContentDocument;
2181 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2183 * Create an element with the specified name, prefix and namespace ID.
2184 * Returns null if element name parsing failed.
2186 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2187 int32_t aNamespaceID,
2188 const nsAString* aIs = nullptr);
2191 * Get the security info (i.e. SSL state etc) that the document got
2192 * from the channel/document that created the content of the
2193 * document.
2195 * @see nsIChannel
2197 nsITransportSecurityInfo* GetSecurityInfo() { return mSecurityInfo; }
2200 * Get the channel that failed to load and resulted in an error page, if it
2201 * exists. This is only relevant to error pages.
2203 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2206 * This function checks if the document that is trying to access
2207 * GetNetErrorInfo is a trusted about net error page or not.
2209 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2212 * This function checks if the document that is trying to access
2213 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2215 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext* aCx,
2216 JSObject* aObject);
2219 * Get security info like error code for a failed channel. This
2220 * property is only exposed to about:neterror documents.
2222 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2225 * This function checks if the document that is trying to access
2226 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2228 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2231 * This function checks if the privilege storage access api is available for
2232 * the caller. We only allow privilege SSA to be called by system principal
2233 * and webcompat extension.
2235 static bool CallerCanAccessPrivilegeSSA(JSContext* aCx, JSObject* aObject);
2238 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2239 * failed Channel. This property is only exposed for about:certerror
2240 * documents.
2242 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2243 ErrorResult& aRv);
2246 * Set the channel that failed to load and resulted in an error page.
2247 * This is only relevant to error pages.
2249 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2252 * Returns the default namespace ID used for elements created in this
2253 * document.
2255 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2257 void RemoveAllProperties();
2258 void RemoveAllPropertiesFor(nsINode* aNode);
2260 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2263 * Sets the ID used to identify this part of the multipart document
2265 void SetPartID(uint32_t aID) { mPartID = aID; }
2268 * Return the ID used to identify this part of the multipart document
2270 uint32_t GetPartID() const { return mPartID; }
2273 * Sanitize the document by resetting all input elements and forms that have
2274 * autocomplete=off to their default values.
2275 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2277 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Sanitize();
2280 * Enumerate all subdocuments.
2281 * The enumerator callback should return CallState::Continue to continue
2282 * enumerating, or CallState::Stop to stop. This will never get passed a null
2283 * aDocument.
2285 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2286 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2289 * Collect all the descendant documents for which |aCalback| returns true.
2290 * The callback function must not mutate any state for the given document.
2292 using nsDocTestFunc = bool (*)(const Document* aDocument);
2293 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2294 nsDocTestFunc aCallback) const;
2297 * Check whether it is safe to cache the presentation of this document
2298 * and all of its subdocuments (depending on the 3rd param). This method
2299 * checks the following conditions recursively:
2300 * - Some document types, such as plugin documents, cannot be safely cached.
2301 * - If there are any pending requests, we don't allow the presentation
2302 * to be cached. Ideally these requests would be suspended and resumed,
2303 * but that is difficult in some cases, such as XMLHttpRequest.
2304 * - If there are any beforeunload or unload listeners, we must fire them
2305 * for correctness, but this likely puts the document into a state where
2306 * it would not function correctly if restored.
2308 * |aNewRequest| should be the request for a new document which will
2309 * replace this document in the docshell. The new document's request
2310 * will be ignored when checking for active requests. If there is no
2311 * request associated with the new document, this parameter may be null.
2313 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2314 * combination is when we try to BFCache aNewRequest
2316 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2317 uint32_t& aBFCacheCombo,
2318 bool aIncludeSubdocuments,
2319 bool aAllowUnloadListeners = true);
2322 * Pass principals if the correct ones are known when calling Init. That way
2323 * NodeInfoManager doesn't need to create a temporary null principal.
2325 virtual nsresult Init(nsIPrincipal* aPrincipal,
2326 nsIPrincipal* aPartitionedPrincipal);
2329 * Notify the document that its associated ContentViewer is being destroyed.
2330 * This releases circular references so that the document can go away.
2331 * Destroy() is only called on documents that have a content viewer.
2333 virtual void Destroy();
2336 * Notify the document that its associated ContentViewer is no longer
2337 * the current viewer for the docshell. The document might still
2338 * be rendered in "zombie state" until the next document is ready.
2339 * The document should save form control state.
2341 void RemovedFromDocShell();
2344 * Get the layout history state that should be used to save and restore state
2345 * for nodes in this document. This may return null; if that happens state
2346 * saving and restoration is not possible.
2348 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2351 * Methods that can be used to prevent onload firing while an event that
2352 * should block onload is posted. onload is guaranteed to not fire until
2353 * either all calls to BlockOnload() have been matched by calls to
2354 * UnblockOnload() or the load has been stopped altogether (by the user
2355 * pressing the Stop button, say).
2357 void BlockOnload();
2359 * @param aFireSync whether to fire onload synchronously. If false,
2360 * onload will fire asynchronously after all onload blocks have been
2361 * removed. It will NOT fire from inside UnblockOnload. If true,
2362 * onload may fire from inside UnblockOnload.
2364 void UnblockOnload(bool aFireSync);
2366 // Only BlockOnload should call this!
2367 void AsyncBlockOnload();
2369 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2371 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnblockDOMContentLoaded();
2374 * Notification that the page has been shown, for documents which are loaded
2375 * into a DOM window. This corresponds to the completion of document load,
2376 * or to the page's presentation being restored into an existing DOM window.
2377 * This notification fires applicable DOM events to the content window. See
2378 * PageTransitionEvent.webidl for a description of the |aPersisted|
2379 * parameter. If aDispatchStartTarget is null, the pageshow event is
2380 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2381 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2382 * event is only dispatched to listeners in the system group.
2383 * Note: if aDispatchStartTarget isn't null, the showing state of the
2384 * document won't be altered.
2386 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2387 bool aOnlySystemGroup = false);
2390 * Notification that the page has been hidden, for documents which are loaded
2391 * into a DOM window. This corresponds to the unloading of the document, or
2392 * to the document's presentation being saved but removed from an existing
2393 * DOM window. This notification fires applicable DOM events to the content
2394 * window. See PageTransitionEvent.webidl for a description of the
2395 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2396 * event is dispatched on the ScriptGlobalObject for this document,
2397 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2398 * true, the event is only dispatched to listeners in the system group.
2399 * Note: if aDispatchStartTarget isn't null, the showing state of the
2400 * document won't be altered.
2402 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2403 bool aOnlySystemGroup = false);
2406 * We record the set of links in the document that are relevant to
2407 * style.
2410 * Notification that an element is a link that is relevant to style.
2412 void AddStyleRelevantLink(Link* aLink) {
2413 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2414 #ifdef DEBUG
2415 NS_ASSERTION(!mStyledLinks.Contains(aLink),
2416 "Document already knows about this Link!");
2417 mStyledLinksCleared = false;
2418 #endif
2419 mStyledLinks.Insert(aLink);
2423 * Notification that an element is a link and its URI might have been
2424 * changed or the element removed. If the element is still a link relevant
2425 * to style, then someone must ensure that AddStyleRelevantLink is
2426 * (eventually) called on it again.
2428 void ForgetLink(Link* aLink) {
2429 MOZ_ASSERT(aLink, "Passing in a null link. Expect crashes RSN!");
2430 MOZ_ASSERT(mStyledLinks.Contains(aLink) || mStyledLinksCleared,
2431 "Document knows nothing about this Link!");
2432 mStyledLinks.Remove(aLink);
2435 // Refreshes the hrefs of all the links in the document.
2436 void RefreshLinkHrefs();
2439 * Support for window.matchMedia()
2442 already_AddRefed<MediaQueryList> MatchMedia(const nsACString& aMediaQueryList,
2443 CallerType aCallerType);
2445 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2447 nsTHashtable<LCPEntryHashEntry>& ContentIdentifiersForLCP() {
2448 return mContentIdentifiersForLCP;
2452 * Get the compatibility mode for this document
2454 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2457 * Check whether we've ever fired a DOMTitleChanged event for this
2458 * document.
2460 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2463 * To batch DOMSubtreeModified, document needs to be informed when
2464 * a mutation event might be dispatched, even if the event isn't actually
2465 * created because there are no listeners for it.
2467 * @param aTarget is the target for the mutation event.
2469 void MayDispatchMutationEvent(nsINode* aTarget) {
2470 if (mSubtreeModifiedDepth > 0) {
2471 mSubtreeModifiedTargets.AppendObject(aTarget);
2476 * Marks as not-going-to-be-collected for the given generation of
2477 * cycle collection.
2479 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2480 mMarkedCCGeneration = aGeneration;
2484 * Gets the cycle collector generation this document is marked for.
2486 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2489 * Returns whether this document is cookie averse. See
2490 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2492 bool IsCookieAverse() const {
2493 // If we are a document that "has no browsing context."
2494 if (!GetInnerWindow()) {
2495 return true;
2498 // If we are a document "whose URL's scheme is not a network scheme."
2499 // NB: Explicitly allow file: URIs to store cookies.
2501 return !NodePrincipal()->SchemeIs("http") &&
2502 !NodePrincipal()->SchemeIs("https") &&
2503 !NodePrincipal()->SchemeIs("file");
2506 bool IsLoadedAsData() { return mLoadedAsData; }
2508 void SetAddedToMemoryReportAsDataDocument() {
2509 mAddedToMemoryReportingAsDataDocument = true;
2512 void UnregisterFromMemoryReportingForDataDocument();
2514 bool MayStartLayout() { return mMayStartLayout; }
2516 void SetMayStartLayout(bool aMayStartLayout);
2518 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2520 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2522 // In case of failure, the document really can't initialize the frame loader.
2523 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2524 // In case of failure, the caller must handle the error, for example by
2525 // finalizing frame loader asynchronously.
2526 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2527 // Removes the frame loader of aShell from the initialization list.
2528 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2531 * Check whether this document is a root document that is not an
2532 * external resource.
2534 bool IsRootDisplayDocument() const {
2535 return !mParentDocument && !mDisplayDocument;
2538 bool ChromeRulesEnabled() const { return mChromeRulesEnabled; }
2540 bool IsInChromeDocShell() const {
2541 const Document* root = this;
2542 while (const Document* displayDoc = root->GetDisplayDocument()) {
2543 root = displayDoc;
2545 return root->mInChromeDocShell;
2548 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2550 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2552 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2554 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2556 bool IsResourceDoc() const {
2557 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2558 mHasDisplayDocument; // Are we an external resource doc?
2562 * Get the document for which this document is an external resource. This
2563 * will be null if this document is not an external resource. Otherwise,
2564 * GetDisplayDocument() will return a non-null document, and
2565 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2567 Document* GetDisplayDocument() const { return mDisplayDocument; }
2570 * Set the display document for this document. aDisplayDocument must not be
2571 * null.
2573 void SetDisplayDocument(Document* aDisplayDocument) {
2574 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2575 "Shouldn't set mDisplayDocument on documents that already "
2576 "have a presentation or a docshell or a window");
2577 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2578 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2579 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2580 "Display documents should not nest");
2581 mDisplayDocument = aDisplayDocument;
2582 mHasDisplayDocument = !!aDisplayDocument;
2586 * Request an external resource document for aURI. This will return the
2587 * resource document if available. If one is not available yet, it will
2588 * start loading as needed, and the pending load object will be returned in
2589 * aPendingLoad so that the caller can register an observer to wait for the
2590 * load. If this function returns null and doesn't return a pending load,
2591 * that means that there is no resource document for this URI and won't be
2592 * one in the future.
2594 * @param aURI the URI to get
2595 * @param aReferrerInfo the referrerInfo of the request
2596 * @param aRequestingNode the node making the request
2597 * @param aPendingLoad the pending load for this request, if any
2599 Document* RequestExternalResource(nsIURI* aURI,
2600 nsIReferrerInfo* aReferrerInfo,
2601 nsINode* aRequestingNode,
2602 ExternalResourceLoad** aPendingLoad);
2605 * Enumerate the external resource documents associated with this document.
2606 * The enumerator callback should return CallState::Continue to continue
2607 * enumerating, or CallState::Stop to stop. This callback will never get
2608 * passed a null aDocument.
2610 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2612 dom::ExternalResourceMap& ExternalResourceMap() {
2613 return mExternalResourceMap;
2617 * Return whether the document is currently showing (in the sense of
2618 * OnPageShow() having been called already and OnPageHide() not having been
2619 * called yet.
2621 bool IsShowing() const { return mIsShowing; }
2623 * Return whether the document is currently visible (in the sense of
2624 * OnPageHide having been called and OnPageShow not yet having been called)
2626 bool IsVisible() const { return mVisible; }
2628 void SetSuppressedEventListener(EventListener* aListener);
2630 EventListener* GetSuppressedEventListener() {
2631 return mSuppressedEventListener;
2635 * Return true when this document is active, i.e., an active document
2636 * in a content viewer and not in the bfcache.
2637 * This does NOT match the "active document" concept in the WHATWG spec -
2638 * see IsCurrentActiveDocument.
2640 bool IsActive() const;
2643 * Return true if this is the current active document for its
2644 * docshell. Note that a docshell may have multiple active documents
2645 * due to the bfcache -- this should be used when you need to
2646 * differentiate the *current* active document from any active
2647 * documents.
2649 bool IsCurrentActiveDocument() const {
2650 nsPIDOMWindowInner* inner = GetInnerWindow();
2651 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2655 * Returns whether this document should perform image loads.
2657 bool ShouldLoadImages() const {
2658 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2659 // images can themselves have data: URL image references.
2660 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2661 IsStaticDocument();
2664 void SetHasPrintCallbacks() {
2665 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2666 mHasPrintCallbacks = true;
2669 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2672 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2673 * the document's activity changes such as OnPageHide, visibility, activity.
2674 * The ActivityObserver objects can be nsIObjectLoadingContent or
2675 * nsIDocumentActivity or HTMLMEdiaElement.
2677 void RegisterActivityObserver(nsISupports* aSupports);
2678 bool UnregisterActivityObserver(nsISupports* aSupports);
2679 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2680 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2681 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2683 void NotifyActivityChanged();
2685 // Indicates whether mAnimationController has been (lazily) initialized.
2686 // If this returns true, we're promising that GetAnimationController()
2687 // will have a non-null return value.
2688 bool HasAnimationController() { return !!mAnimationController; }
2690 // Getter for this document's SMIL Animation Controller. Performs lazy
2691 // initialization, if this document supports animation and if
2692 // mAnimationController isn't yet initialized.
2694 // If HasAnimationController is true, this is guaranteed to return non-null.
2695 SMILAnimationController* GetAnimationController();
2697 // Gets the tracker for scroll-driven animations that are waiting to start.
2698 // Returns nullptr if there is no scroll-driven animation tracker for this
2699 // document which will be the case if there have never been any scroll-driven
2700 // animations in the document.
2701 ScrollTimelineAnimationTracker* GetScrollTimelineAnimationTracker() {
2702 return mScrollTimelineAnimationTracker;
2705 // Gets the tracker for scroll-driven animations that are waiting to start and
2706 // creates it if it doesn't already exist. As a result, the return value
2707 // will never be nullptr.
2708 ScrollTimelineAnimationTracker* GetOrCreateScrollTimelineAnimationTracker();
2711 * Prevents user initiated events from being dispatched to the document and
2712 * subdocuments.
2714 void SuppressEventHandling(uint32_t aIncrease = 1);
2717 * Unsuppress event handling.
2718 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2719 * asynchronously.
2721 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnsuppressEventHandlingAndFireEvents(
2722 bool aFireEvents);
2724 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2726 bool IsEventHandlingEnabled() const {
2727 return !EventHandlingSuppressed() && mScriptGlobalObject;
2730 bool WouldScheduleFrameRequestCallbacks() const {
2731 // If this function changes to depend on some other variable, make sure to
2732 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2733 // where that variable can change.
2734 return mPresShell && IsEventHandlingEnabled();
2737 void DecreaseEventSuppression() {
2738 MOZ_ASSERT(mEventsSuppressed);
2739 --mEventsSuppressed;
2740 UpdateFrameRequestCallbackSchedulingState();
2744 * Some clipboard commands are unconditionally enabled on some documents, so
2745 * as to always dispatch copy / paste events even though you'd normally not be
2746 * able to copy.
2748 bool AreClipboardCommandsUnconditionallyEnabled() const;
2751 * Note a ChannelEventQueue which has been suspended on the document's behalf
2752 * to prevent XHRs from running content scripts while event handling is
2753 * suppressed. The document is responsible for resuming the queue after
2754 * event handling is unsuppressed.
2756 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2759 * Returns true if a postMessage event should be suspended instead of running.
2760 * The document is responsible for running the event later, in the order they
2761 * were received.
2763 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2766 * Run any suspended postMessage events, or clear them.
2768 void FireOrClearPostMessageEvents(bool aFireEvents);
2770 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2773 * Flag whether we're about to fire the window's load event for this document.
2775 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2778 * Test whether we should be firing a load event for this document after a
2779 * document.close(). This is public and on Document, instead of being private
2780 * to Document, because we need to go through the normal docloader logic
2781 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2782 * semantics of firing the load event; we just don't want to fire the load
2783 * event if this tests true. So we need the docloader to be able to access
2784 * this state.
2786 * This method should only be called at the point when the load event is about
2787 * to be fired. It resets the "skip" flag, so it is not idempotent.
2789 bool SkipLoadEventAfterClose() {
2790 bool skip = mSkipLoadEventAfterClose;
2791 mSkipLoadEventAfterClose = false;
2792 return skip;
2796 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2798 void IncrementIgnoreDestructiveWritesCounter() {
2799 ++mIgnoreDestructiveWritesCounter;
2803 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2805 void DecrementIgnoreDestructiveWritesCounter() {
2806 --mIgnoreDestructiveWritesCounter;
2809 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2812 * Returns true if this document is allowed to contain XUL element and
2813 * use non-builtin XBL bindings.
2815 bool AllowXULXBL() {
2816 return mAllowXULXBL == eTriTrue ? true
2817 : mAllowXULXBL == eTriFalse ? false
2818 : InternalAllowXULXBL();
2822 * Returns true if this document is allowed to load DTDs from UI resources
2823 * no matter what.
2825 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2827 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2829 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2832 * Returns the template content owner document that owns the content of
2833 * HTMLTemplateElement.
2835 Document* GetTemplateContentsOwner();
2837 Document* GetTemplateContentsOwnerIfExists() const {
2838 return mTemplateContentsOwner.get();
2841 bool IsTemplateContentsOwner() const {
2842 // Template contents owner documents are the template contents owner of
2843 // themselves.
2844 return mTemplateContentsOwner == this;
2848 * Returns true if this document is a static clone of a normal document.
2850 * We create static clones for print preview and printing (possibly other
2851 * things in future).
2853 * Note that static documents are also "loaded as data" (if this method
2854 * returns true, IsLoadedAsData() will also return true).
2856 bool IsStaticDocument() const { return mIsStaticDocument; }
2859 * Clones the document along with any subdocuments, stylesheet, etc.
2861 * The resulting document and everything it contains (including any
2862 * sub-documents) are created purely via cloning. The returned documents and
2863 * any sub-documents are "loaded as data" documents to preserve the state as
2864 * it was during the clone process (we don't want external resources to load
2865 * and replace the cloned resources).
2867 * @param aCloneContainer The container for the clone document.
2868 * @param aDocumentViewer The viewer for the clone document. Must be the
2869 * viewer of aCloneContainer, but callers must have a
2870 * reference to it already and ensure it's not null.
2871 * @param aPrintSettings The print settings for this clone.
2872 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2874 already_AddRefed<Document> CreateStaticClone(
2875 nsIDocShell* aCloneContainer, nsIDocumentViewer* aDocumentViewer,
2876 nsIPrintSettings* aPrintSettings, bool* aOutHasInProcessPrintCallbacks);
2879 * If this document is a static clone, this returns the original
2880 * document.
2882 Document* GetOriginalDocument() const {
2883 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2884 return mOriginalDocument;
2888 * If this document is a static clone, let the original document know that
2889 * we're going away and then release our reference to it.
2891 void UnlinkOriginalDocumentIfStatic();
2894 * These are called by the parser as it encounters <picture> tags, the end of
2895 * said tags, and possible picture <source srcset> sources respectively. These
2896 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2897 * expected to be marked void.
2899 * NOTE that the parser does not attempt to track the current picture nesting
2900 * level or whether the given <source> tag is within a picture -- it is only
2901 * guaranteed to order these calls properly with respect to
2902 * ResolvePreLoadImage.
2905 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2907 void PreloadPictureClosed();
2909 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2910 const nsAString& aSizesAttr,
2911 const nsAString& aTypeAttr,
2912 const nsAString& aMediaAttr);
2915 * Called by the parser to resolve an image for preloading. The parser will
2916 * call the PreloadPicture* functions to inform us of possible <picture>
2917 * nesting and possible sources, which are used to inform URL selection
2918 * responsive <picture> or <img srcset> images. Unset attributes are expected
2919 * to be marked void.
2920 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2921 * true, false otherwise.
2923 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2924 const nsAString& aSrcAttr,
2925 const nsAString& aSrcsetAttr,
2926 const nsAString& aSizesAttr,
2927 bool* aIsImgSet);
2929 * Called by nsParser to preload images. Can be removed and code moved
2930 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2931 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2932 * be a void string if the attr is not present.
2933 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2934 * when this image is for loading <picture> or <img srcset> images.
2936 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2937 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2938 bool aLinkPreload);
2939 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2940 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2941 bool aLinkPreload, uint64_t aEarlyHintPreloaderId);
2944 * Called by images to forget an image preload when they start doing
2945 * the real load.
2947 void ForgetImagePreload(nsIURI* aURI);
2950 * Called by the parser or the preload service to preload style sheets.
2951 * aCrossOriginAttr should be a void string if the attr is not present.
2953 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2954 const nsAString& aCrossOriginAttr,
2955 ReferrerPolicyEnum aReferrerPolicy,
2956 const nsAString& aNonce,
2957 const nsAString& aIntegrity,
2958 css::StylePreloadKind,
2959 uint64_t aEarlyHintPreloaderId,
2960 const nsAString& aFetchPriority);
2963 * Called by the chrome registry to load style sheets.
2965 * This always does a synchronous load, and parses as a normal document sheet.
2967 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2970 * Returns true if the locale used for the document specifies a direction of
2971 * right to left. For chrome documents, this comes from the chrome registry.
2972 * This is used to determine the current state for the :-moz-locale-dir
2973 * pseudoclass so once can know whether a document is expected to be rendered
2974 * left-to-right or right-to-left.
2976 bool IsDocumentRightToLeft();
2979 * Called by Parser for link rel=preconnect
2981 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2984 * Set the document's pending state object (as serialized using structured
2985 * clone).
2987 void SetStateObject(nsIStructuredCloneContainer* scContainer);
2990 * Set the document's pending state object to the same state object as
2991 * aDocument.
2993 void SetStateObjectFrom(Document* aDocument) {
2994 SetStateObject(aDocument->mStateObjectContainer);
2998 * Returns true if there is a lightweight theme specified. This is used to
2999 * determine the state of the :-moz-lwtheme pseudo-class.
3001 bool ComputeDocumentLWTheme() const;
3002 void ResetDocumentLWTheme() {
3003 UpdateDocumentStates(DocumentState::LWTHEME, true);
3006 // Whether we're a media document or not.
3007 enum class MediaDocumentKind {
3008 NotMedia,
3009 Video,
3010 Image,
3011 Plugin,
3014 virtual enum MediaDocumentKind MediaDocumentKind() const {
3015 return MediaDocumentKind::NotMedia;
3018 DocumentState State() const { return mState; }
3020 nsISupports* GetCurrentContentSink();
3022 void ElementWithAutoFocusInserted(Element* aAutoFocusCandidate);
3023 MOZ_CAN_RUN_SCRIPT void FlushAutoFocusCandidates();
3024 void ScheduleFlushAutoFocusCandidates();
3025 bool HasAutoFocusCandidates() const {
3026 return !mAutoFocusCandidates.IsEmpty();
3029 void SetAutoFocusFired();
3031 void SetScrollToRef(nsIURI* aDocumentURI);
3032 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3033 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3035 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3036 mChangeScrollPosWhenScrollingToRef = aValue;
3039 using DocumentOrShadowRoot::GetElementById;
3040 using DocumentOrShadowRoot::GetElementsByClassName;
3041 using DocumentOrShadowRoot::GetElementsByTagName;
3042 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3044 DocumentTimeline* Timeline();
3045 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3046 void UpdateHiddenByContentVisibilityForAnimations();
3048 SVGSVGElement* GetSVGRootElement() const;
3050 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3051 int32_t* aHandle);
3052 void CancelFrameRequestCallback(int32_t aHandle);
3055 * Returns true if the handle refers to a callback that was canceled that
3056 * we did not find in our list of callbacks (e.g. because it is one of those
3057 * in the set of callbacks currently queued to be run).
3059 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3062 * Put this document's frame request callbacks into the provided
3063 * list, and forget about them.
3065 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3068 * @return true if this document's frame request callbacks should be
3069 * throttled. We throttle requestAnimationFrame for documents which aren't
3070 * visible (e.g. scrolled out of the viewport).
3072 bool ShouldThrottleFrameRequests() const;
3074 // This returns true when the document tree is being teared down.
3075 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3077 dom::ImageTracker* ImageTracker();
3079 // Adds an element to mResponsiveContent when the element is
3080 // added to the tree.
3081 void AddResponsiveContent(HTMLImageElement* aContent) {
3082 MOZ_ASSERT(aContent);
3083 mResponsiveContent.Insert(aContent);
3086 // Removes an element from mResponsiveContent when the element is
3087 // removed from the tree.
3088 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3089 MOZ_ASSERT(aContent);
3090 mResponsiveContent.Remove(aContent);
3093 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3094 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3095 mSVGUseElementsNeedingShadowTreeUpdate.Remove(&aElement);
3098 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3099 return mSVGUseElementsNeedingShadowTreeUpdate.Contains(&aElement);
3102 using ShadowRootSet = nsTHashSet<ShadowRoot*>;
3104 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3105 mComposedShadowRoots.Insert(&aShadowRoot);
3108 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3109 mComposedShadowRoots.Remove(&aShadowRoot);
3112 // If you're considering using this, you probably want to use
3113 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3114 // sanity-checking.
3115 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3116 return mComposedShadowRoots.Contains(&aShadowRoot);
3119 const ShadowRootSet& ComposedShadowRoots() const {
3120 return mComposedShadowRoots;
3123 // WebIDL method for chrome code.
3124 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3126 // Notifies any responsive content added by AddResponsiveContent upon media
3127 // features values changing.
3128 void NotifyMediaFeatureValuesChanged();
3130 nsresult GetStateObject(JS::MutableHandle<JS::Value> aState);
3132 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3134 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3136 nsContentList* ImageMapList();
3138 // Add aLink to the set of links that need their status resolved.
3139 void RegisterPendingLinkUpdate(Link* aLink);
3141 // Update state on links in mLinksToUpdate.
3142 void FlushPendingLinkUpdates();
3144 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3145 void WarnOnceAbout(
3146 DeprecatedOperations aOperation, bool asError = false,
3147 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3149 #define DOCUMENT_WARNING(_op) e##_op,
3150 enum DocumentWarnings {
3151 #include "nsDocumentWarningList.h"
3152 eDocumentWarningCount
3154 #undef DOCUMENT_WARNING
3155 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3156 void WarnOnceAbout(
3157 DocumentWarnings aWarning, bool asError = false,
3158 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3160 // This method may fire a DOM event; if it does so it will happen
3161 // synchronously.
3163 // Whether the event fires is controlled by the argument.
3164 enum class DispatchVisibilityChange { No, Yes };
3165 void UpdateVisibilityState(
3166 DispatchVisibilityChange = DispatchVisibilityChange::Yes);
3168 // Posts an event to call UpdateVisibilityState.
3169 void PostVisibilityUpdateEvent();
3171 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3173 // Adds the size of a given node, which must not be a document node, to the
3174 // window sizes passed-in.
3175 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3177 // Note: Document is a sub-class of nsINode, which has a
3178 // SizeOfExcludingThis function. However, because Document objects can
3179 // only appear at the top of the DOM tree, we have a specialized measurement
3180 // function which returns multiple sizes.
3181 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3182 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3183 // because Document inherits from nsINode; see the comment above the
3184 // declaration of nsINode::SizeOfIncludingThis.
3185 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3187 void ConstructUbiNode(void* storage) override;
3189 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3191 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3193 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3195 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3197 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3199 void SetIsInSyncOperation(bool aSync);
3201 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3204 * Creates a new element in the HTML namespace with a local name given by
3205 * aTag.
3207 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3209 // WebIDL API
3210 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3211 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3212 ErrorResult& rv);
3213 DOMImplementation* GetImplementation(ErrorResult& rv);
3214 [[nodiscard]] nsresult GetURL(nsString& retval) const;
3215 [[nodiscard]] nsresult GetDocumentURI(nsString& retval) const;
3216 // Return the URI for the document.
3217 // The returned value may differ if the document is loaded via XHR, and
3218 // when accessed from chrome privileged script and
3219 // from content privileged script for compatibility.
3220 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3221 ErrorResult& aRv) const;
3222 void GetCompatMode(nsString& retval) const;
3223 void GetCharacterSet(nsAString& retval) const;
3224 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3225 // GetDoctype defined above
3226 Element* GetDocumentElement() const { return GetRootElement(); }
3228 WindowContext* GetTopLevelWindowContext() const;
3230 // If the top-level ancestor content document for this document is in the same
3231 // process, returns it. Otherwise, returns null. This function is not
3232 // Fission-compatible, and should not be used in new code.
3233 Document* GetTopLevelContentDocumentIfSameProcess();
3234 const Document* GetTopLevelContentDocumentIfSameProcess() const;
3236 // Returns the associated app window if this is a top-level chrome document,
3237 // null otherwise.
3238 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3240 already_AddRefed<Element> CreateElement(
3241 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3242 ErrorResult& rv);
3243 already_AddRefed<Element> CreateElementNS(
3244 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3245 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3246 already_AddRefed<Element> CreateXULElement(
3247 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3248 ErrorResult& aRv);
3249 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3250 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3251 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3252 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3253 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3254 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3255 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3256 ErrorResult& rv) const;
3257 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3258 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* AdoptNode(
3259 nsINode& aAdoptedNode, ErrorResult& rv, bool aAcceptShadowRoot = false);
3260 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3261 CallerType aCallerType,
3262 ErrorResult& rv) const;
3263 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3264 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3265 uint32_t aWhatToShow,
3266 NodeFilter* aFilter,
3267 ErrorResult& rv) const;
3268 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3269 uint32_t aWhatToShow,
3270 NodeFilter* aFilter,
3271 ErrorResult& rv) const;
3272 // Deprecated WebIDL bits
3273 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3274 ErrorResult& rv);
3275 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3276 ErrorResult& rv);
3277 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3278 const nsAString& aQualifiedName,
3279 ErrorResult& rv);
3280 void GetInputEncoding(nsAString& aInputEncoding) const;
3281 already_AddRefed<Location> GetLocation() const;
3282 void GetDomain(nsAString& aDomain);
3283 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3284 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3285 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3286 void GetReferrer(nsAString& aReferrer) const;
3287 void GetLastModified(nsAString& aLastModified) const;
3288 void GetReadyState(nsAString& aReadyState) const;
3290 void GetTitle(nsAString& aTitle);
3291 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3292 void GetDir(nsAString& aDirection) const;
3293 void SetDir(const nsAString& aDirection);
3294 nsIHTMLCollection* Images();
3295 nsIHTMLCollection* Embeds();
3296 nsIHTMLCollection* Plugins() { return Embeds(); }
3297 nsIHTMLCollection* Links();
3298 nsIHTMLCollection* Forms();
3299 nsIHTMLCollection* Scripts();
3300 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3301 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3302 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3304 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3305 const mozilla::dom::Optional<nsAString>& /* unused */,
3306 mozilla::ErrorResult& aError);
3307 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3308 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3309 mozilla::ErrorResult& rv);
3310 void Close(mozilla::ErrorResult& rv);
3311 void Write(const mozilla::dom::Sequence<nsString>& aText,
3312 mozilla::ErrorResult& rv);
3313 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3314 mozilla::ErrorResult& rv);
3315 Nullable<WindowProxyHolder> GetDefaultView() const;
3316 Element* GetActiveElement();
3317 enum class IncludeChromeOnly : bool { No, Yes };
3318 // TODO(emilio): Audit callers and remove the default argument, some seem like
3319 // they could want the IncludeChromeOnly::Yes version.
3320 nsIContent* GetUnretargetedFocusedContent(
3321 IncludeChromeOnly = IncludeChromeOnly::No) const;
3323 * Return true if this document or a subdocument has focus.
3325 bool HasFocus(ErrorResult& rv) const;
3328 * Return true if this document itself has focus.
3330 bool ThisDocumentHasFocus() const;
3332 void GetDesignMode(nsAString& aDesignMode);
3333 void SetDesignMode(const nsAString& aDesignMode,
3334 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3335 void SetDesignMode(const nsAString& aDesignMode,
3336 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3337 mozilla::ErrorResult& rv);
3338 MOZ_CAN_RUN_SCRIPT
3339 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3340 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3341 mozilla::ErrorResult& aRv);
3342 MOZ_CAN_RUN_SCRIPT bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3343 nsIPrincipal& aSubjectPrincipal,
3344 mozilla::ErrorResult& aRv);
3345 MOZ_CAN_RUN_SCRIPT bool QueryCommandIndeterm(
3346 const nsAString& aHTMLCommandName, mozilla::ErrorResult& aRv);
3347 MOZ_CAN_RUN_SCRIPT bool QueryCommandState(const nsAString& aHTMLCommandName,
3348 mozilla::ErrorResult& aRv);
3349 MOZ_CAN_RUN_SCRIPT bool QueryCommandSupported(
3350 const nsAString& aHTMLCommandName, mozilla::dom::CallerType aCallerType,
3351 mozilla::ErrorResult& aRv);
3352 MOZ_CAN_RUN_SCRIPT void QueryCommandValue(const nsAString& aHTMLCommandName,
3353 nsAString& aValue,
3354 mozilla::ErrorResult& aRv);
3355 nsIHTMLCollection* Applets();
3356 nsIHTMLCollection* Anchors();
3357 TimeStamp LastFocusTime() const;
3358 void SetLastFocusTime(const TimeStamp& aFocusTime);
3359 // Event handlers are all on nsINode already
3360 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3361 Element* GetCurrentScript();
3362 void ReleaseCapture() const;
3363 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3364 nsIURI* GetDocumentURIObject() const;
3365 // Not const because all the fullscreen goop is not const
3366 const char* GetFullscreenError(CallerType);
3367 bool FullscreenEnabled(CallerType aCallerType) {
3368 return !GetFullscreenError(aCallerType);
3371 void GetWireframeWithoutFlushing(bool aIncludeNodes, Nullable<Wireframe>&);
3373 MOZ_CAN_RUN_SCRIPT void GetWireframe(bool aIncludeNodes,
3374 Nullable<Wireframe>&);
3376 // Hides all popovers until the given end point, see
3377 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3378 MOZ_CAN_RUN_SCRIPT void HideAllPopoversUntil(nsINode& aEndpoint,
3379 bool aFocusPreviousElement,
3380 bool aFireEvents);
3382 MOZ_CAN_RUN_SCRIPT_BOUNDARY void HideAllPopoversWithoutRunningScript();
3383 // Hides the given popover element, see
3384 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3385 MOZ_CAN_RUN_SCRIPT void HidePopover(Element& popover,
3386 bool aFocusPreviousElement,
3387 bool aFireEvents, ErrorResult& aRv);
3389 // Returns a list of all the elements in the Document's top layer whose
3390 // popover attribute is in the auto state.
3391 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3392 nsTArray<Element*> AutoPopoverList() const;
3394 // Return document's auto popover list's last element.
3395 // See
3396 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3397 Element* GetTopmostAutoPopover() const;
3399 // Adds/removes an element to/from the auto popover list.
3400 void AddToAutoPopoverList(Element&);
3401 void RemoveFromAutoPopoverList(Element&);
3403 void AddPopoverToTopLayer(Element&);
3404 void RemovePopoverFromTopLayer(Element&);
3406 Element* GetTopLayerTop();
3407 // Return the fullscreen element in the top layer
3408 Element* GetUnretargetedFullscreenElement() const;
3409 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3410 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3411 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3412 void GetFgColor(nsAString& aFgColor);
3413 void SetFgColor(const nsAString& aFgColor);
3414 void GetLinkColor(nsAString& aLinkColor);
3415 void SetLinkColor(const nsAString& aLinkColor);
3416 void GetVlinkColor(nsAString& aAvlinkColor);
3417 void SetVlinkColor(const nsAString& aVlinkColor);
3418 void GetAlinkColor(nsAString& aAlinkColor);
3419 void SetAlinkColor(const nsAString& aAlinkColor);
3420 void GetBgColor(nsAString& aBgColor);
3421 void SetBgColor(const nsAString& aBgColor);
3422 void Clear() const {
3423 // Deprecated
3425 void CaptureEvents();
3426 void ReleaseEvents();
3428 mozilla::dom::HTMLAllCollection* All();
3430 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3431 static bool IsWebAnimationsGetAnimationsEnabled(JSContext* aCx,
3432 JSObject* aObject);
3433 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3434 JSObject* aObject);
3435 // Checks that the caller is either chrome or some addon.
3436 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3438 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3439 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3441 public:
3442 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3443 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3444 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3445 aSheetSet = mLastStyleSheetSet;
3447 const nsString& GetCurrentStyleSheetSet() const {
3448 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3449 : mLastStyleSheetSet;
3451 void SetPreferredStyleSheetSet(const nsAString&);
3452 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3453 aSheetSet = mPreferredStyleSheetSet;
3455 DOMStringList* StyleSheetSets();
3456 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3459 * Retrieve the location of the caret position (DOM node and character
3460 * offset within that node), given a point.
3462 * @param aX Horizontal point at which to determine the caret position, in
3463 * page coordinates.
3464 * @param aY Vertical point at which to determine the caret position, in
3465 * page coordinates.
3467 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3468 float aY);
3470 Element* GetScrollingElement();
3471 // A way to check whether a given element is what would get returned from
3472 // GetScrollingElement. It can be faster than comparing to the return value
3473 // of GetScrollingElement() due to being able to avoid flushes in various
3474 // cases. This method assumes that null is NOT passed.
3475 bool IsScrollingElement(Element* aElement);
3477 // QuerySelector and QuerySelectorAll already defined on nsINode
3479 UniquePtr<XPathExpression> CreateExpression(const nsAString& aExpression,
3480 XPathNSResolver* aResolver,
3481 ErrorResult& rv);
3482 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3483 already_AddRefed<XPathResult> Evaluate(
3484 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3485 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3486 ErrorResult& rv);
3487 // Touch event handlers already on nsINode
3488 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3489 EventTarget* aTarget, int32_t aIdentifier,
3490 int32_t aPageX, int32_t aPageY,
3491 int32_t aScreenX, int32_t aScreenY,
3492 int32_t aClientX, int32_t aClientY,
3493 int32_t aRadiusX, int32_t aRadiusY,
3494 float aRotationAngle, float aForce);
3495 already_AddRefed<TouchList> CreateTouchList();
3496 already_AddRefed<TouchList> CreateTouchList(
3497 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3498 already_AddRefed<TouchList> CreateTouchList(
3499 const Sequence<OwningNonNull<Touch>>& aTouches);
3501 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3502 mStyleSheetChangeEventsEnabled = aValue;
3505 bool StyleSheetChangeEventsEnabled() const {
3506 return mStyleSheetChangeEventsEnabled;
3509 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue) {
3510 mDevToolsAnonymousAndShadowEventsEnabled = aValue;
3512 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3513 return mDevToolsAnonymousAndShadowEventsEnabled;
3516 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3517 const BlockParsingOptions& aOptions,
3518 ErrorResult& aRv);
3520 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3522 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3524 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock) {
3525 if (aBlock) {
3526 BlockOnload();
3527 } else {
3528 UnblockOnload(/* aFireSync = */ false);
3532 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3533 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3534 void InitializeXULBroadcastManager();
3535 XULBroadcastManager* GetXULBroadcastManager() const {
3536 return mXULBroadcastManager;
3538 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3539 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3541 bool DevToolsWatchingDOMMutations() const {
3542 return mDevToolsWatchingDOMMutations;
3544 void SetDevToolsWatchingDOMMutations(bool aValue);
3546 void MaybeWarnAboutZoom();
3548 // https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
3549 void EvaluateMediaQueriesAndReportChanges(bool aRecurse);
3551 nsTHashSet<RefPtr<WakeLockSentinel>>& ActiveWakeLocks(WakeLockType aType);
3553 void UnlockAllWakeLocks(WakeLockType aType);
3555 // ParentNode
3556 nsIHTMLCollection* Children();
3557 uint32_t ChildElementCount();
3560 * Asserts IsHTMLOrXHTML, and can't return null.
3561 * Defined inline in nsHTMLDocument.h
3563 inline nsHTMLDocument* AsHTMLDocument();
3564 inline const nsHTMLDocument* AsHTMLDocument() const;
3567 * Asserts IsSVGDocument, and can't return null.
3568 * Defined inline in SVGDocument.h
3570 inline SVGDocument* AsSVGDocument();
3571 inline const SVGDocument* AsSVGDocument() const;
3574 * Asserts IsImageDocument, and can't return null.
3575 * Defined inline in ImageDocument.h
3577 inline ImageDocument* AsImageDocument();
3578 inline const ImageDocument* AsImageDocument() const;
3580 gfxUserFontSet* GetUserFontSet();
3581 void FlushUserFontSet();
3582 void MarkUserFontSetDirty();
3583 FontFaceSet* GetFonts() { return mFontFaceSet; }
3585 // FontFaceSource
3586 FontFaceSet* GetFonts(ErrorResult&) { return Fonts(); }
3587 FontFaceSet* Fonts();
3589 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3591 bool IsSynthesized();
3593 // Records whether we will track use counters for this document, and if so,
3594 // which top-level document that page counters will be accumulated to.
3596 // Informs the parent process that page use counters will be sent once the
3597 // document goes away.
3598 void InitUseCounters();
3600 // Reports document use counters via telemetry. This method only has an
3601 // effect once per document, and so is called during document destruction.
3602 void ReportDocumentUseCounters();
3604 // Reports largest contentful paint via telemetry. We want the most up to
3605 // date value for LCP and so this is called during document destruction.
3606 void ReportLCP();
3608 // Report how lazyload performs for this document.
3609 void ReportDocumentLazyLoadCounters();
3611 // Sends page use counters to the parent process to accumulate against the
3612 // top-level document. Must be called while we still have access to our
3613 // WindowContext. This method has an effect each time it is called, and we
3614 // call it just before the document loses its window.
3615 void SendPageUseCounters();
3617 void SetUseCounter(UseCounter aUseCounter) {
3618 mUseCounters[aUseCounter] = true;
3621 const StyleUseCounters* GetStyleUseCounters() {
3622 return mStyleUseCounters.get();
3625 // Propagate our use counters explicitly into the specified referencing
3626 // document.
3628 // This is used for SVG image documents, which cannot be enumerated in the
3629 // referencing document's ReportUseCounters() like external resource documents
3630 // can.
3631 void PropagateImageUseCounters(Document* aReferencingDocument);
3633 // Called to track whether this document has had any interaction.
3634 // This is used to track whether we should permit "beforeunload".
3635 void SetUserHasInteracted();
3636 bool UserHasInteracted() { return mUserHasInteracted; }
3637 void ResetUserInteractionTimer();
3639 // Whether we're cloning the contents of an SVG use element.
3640 bool CloningForSVGUse() const { return mCloningForSVGUse; }
3642 // This should be called when this document receives events which are likely
3643 // to be user interaction with the document, rather than the byproduct of
3644 // interaction with the browser (i.e. a keypress to scroll the view port,
3645 // keyboard shortcuts, etc). This is used to decide whether we should
3646 // permit autoplay audible media. This also gesture activates all other
3647 // content documents in this tab.
3648 void NotifyUserGestureActivation(
3649 UserActivation::Modifiers aModifiers = UserActivation::Modifiers::None());
3651 // This function is used for mochitest only.
3652 void ClearUserGestureActivation();
3654 // Return true if NotifyUserGestureActivation() has been called on any
3655 // document in the document tree.
3656 bool HasBeenUserGestureActivated();
3658 // Reture timestamp of last user gesture in milliseconds relative to
3659 // navigation start timestamp.
3660 DOMHighResTimeStamp LastUserGestureTimeStamp();
3662 // Return true if there is transient user gesture activation and it hasn't yet
3663 // timed out or hasn't been consumed.
3664 bool HasValidTransientUserGestureActivation() const;
3666 // Return true if HasValidTransientUserGestureActivation() would return true,
3667 // and consume the activation.
3668 bool ConsumeTransientUserGestureActivation();
3670 bool GetTransientUserGestureActivationModifiers(
3671 UserActivation::Modifiers* aModifiers);
3673 BrowsingContext* GetBrowsingContext() const;
3675 // This document is a WebExtension page, it might be a background page, a
3676 // popup, a visible tab, a visible iframe ...e.t.c.
3677 bool IsExtensionPage() const;
3679 bool HasScriptsBlockedBySandbox() const;
3681 void ReportHasScrollLinkedEffect(const TimeStamp& aTimeStamp);
3682 bool HasScrollLinkedEffect() const;
3684 #ifdef DEBUG
3685 void AssertDocGroupMatchesKey() const;
3686 #endif
3688 DocGroup* GetDocGroup() const {
3689 #ifdef DEBUG
3690 AssertDocGroupMatchesKey();
3691 #endif
3692 return mDocGroup;
3695 DocGroup* GetDocGroupOrCreate();
3698 * If we're a sub-document, the parent document's layout can affect our style
3699 * and layout (due to the viewport size, viewport units, media queries...).
3701 * This function returns true if our parent document and our child document
3702 * can observe each other. If they cannot, then we don't need to synchronously
3703 * update the parent document layout every time the child document may need
3704 * up-to-date layout information.
3706 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3707 return GetInProcessParentDocument() &&
3708 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3711 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3712 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3713 "Intersection observer already in the list");
3714 mIntersectionObservers.Insert(aObserver);
3717 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3718 mIntersectionObservers.Remove(aObserver);
3721 bool HasIntersectionObservers() const {
3722 return !mIntersectionObservers.IsEmpty();
3725 void UpdateIntersectionObservations(TimeStamp aNowTime);
3726 void ScheduleIntersectionObserverNotification();
3727 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3729 DOMIntersectionObserver* GetLazyLoadObserver() { return mLazyLoadObserver; }
3730 DOMIntersectionObserver& EnsureLazyLoadObserver();
3732 ResizeObserver* GetLastRememberedSizeObserver() {
3733 return mLastRememberedSizeObserver;
3735 ResizeObserver& EnsureLastRememberedSizeObserver();
3736 void ObserveForLastRememberedSize(Element&);
3737 void UnobserveForLastRememberedSize(Element&);
3739 // Dispatch a runnable related to the document.
3740 nsresult Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) const;
3742 // The URLs passed to this function should match what
3743 // JS::DescribeScriptedCaller() returns, since this API is used to
3744 // determine whether some code is being called from a tracking script.
3745 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3746 // The JSContext passed to this method represents the context that we want to
3747 // determine if it belongs to a tracker.
3748 bool IsScriptTracking(JSContext* aCx) const;
3750 // ResizeObserver usage.
3751 void AddResizeObserver(ResizeObserver&);
3752 void RemoveResizeObserver(ResizeObserver&);
3753 void ScheduleResizeObserversNotification() const;
3754 bool HasResizeObservers() const { return !mResizeObservers.IsEmpty(); }
3756 * Calls GatherActiveObservations(aDepth) for all ResizeObservers.
3757 * All observations in each ResizeObserver with element's depth more than
3758 * aDepth will be gathered.
3760 void GatherAllActiveResizeObservations(uint32_t aDepth);
3762 * Calls BroadcastActiveObservations() for all ResizeObservers.
3763 * It also returns the shallowest depth of observed target elements with
3764 * active observations from all ResizeObservers or
3765 * numeric_limits<uint32_t>::max() if there aren't any active observations
3766 * at all.
3768 MOZ_CAN_RUN_SCRIPT uint32_t BroadcastAllActiveResizeObservations();
3770 * Returns whether there is any ResizeObserver that has active
3771 * observations.
3773 bool HasAnyActiveResizeObservations() const;
3775 * Returns whether there is any ResizeObserver that has skipped observations.
3777 bool HasAnySkippedResizeObservations() const;
3779 * Determine proximity to viewport for content-visibility: auto elements and
3780 * notify resize observers.
3782 MOZ_CAN_RUN_SCRIPT void
3783 DetermineProximityToViewportAndNotifyResizeObservers();
3785 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3786 PermissionDelegateHandler* GetPermissionDelegateHandler();
3788 // Notify the document that a fetch or a XHR request has completed
3789 // succesfully in this document. This is used by the password manager to infer
3790 // whether a form is submitted.
3791 void NotifyFetchOrXHRSuccess();
3793 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3794 void SetNotifyFetchSuccess(bool aShouldNotify);
3796 // When this is set, removing a form or a password field from DOM
3797 // sends a Chrome-only event. This is now only used by the password manager
3798 // and formautofill.
3799 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify);
3801 // This function is used by HTMLFormElement and HTMLInputElement to determin
3802 // whether to send an event when it is removed from DOM.
3803 bool ShouldNotifyFormOrPasswordRemoved() const {
3804 return mShouldNotifyFormOrPasswordRemoved;
3807 HTMLEditor* GetHTMLEditor() const;
3810 * Localization
3812 * For more information on DocumentL10n see
3813 * intl/l10n/docs/fluent/tutorial.rst
3816 public:
3818 * This is a public method exposed on Document WebIDL
3819 * to chrome only documents.
3821 DocumentL10n* GetL10n() const { return mDocumentL10n.get(); }
3824 * Whether there's any async l10n mutation work pending.
3826 * When this turns false, we fire the L10nMutationsFinished event.
3828 bool HasPendingL10nMutations() const;
3831 * This method should be called when the container
3832 * of l10n resources parsing is completed.
3834 * It triggers initial async fetch of the resources
3835 * as early as possible.
3837 * In HTML case this is </head>.
3838 * In XUL case this is </linkset>.
3840 void OnL10nResourceContainerParsed();
3843 * This method should be called when a link element
3844 * with rel="localization" is being added to the
3845 * l10n resource container element.
3847 void LocalizationLinkAdded(Element* aLinkElement);
3850 * This method should be called when a link element
3851 * with rel="localization" is being removed.
3853 void LocalizationLinkRemoved(Element* aLinkElement);
3856 * This method should be called as soon as the
3857 * parsing of the document is completed.
3859 * In HTML/XHTML this happens when we finish parsing
3860 * the document element.
3861 * In XUL it happens at `DoneWalking`, during
3862 * `MozBeforeInitialXULLayout`.
3864 void OnParsingCompleted();
3867 * This method is called when the initial translation
3868 * of the document is completed.
3870 * It unblocks the load event if translation was blocking it.
3872 * If the `aL10nCached` is set to `true`, and the document has
3873 * a prototype, it will set the `isL10nCached` flag on it.
3875 void InitialTranslationCompleted(bool aL10nCached);
3878 * Returns whether the document allows localization.
3880 bool AllowsL10n() const;
3882 void SetAllowDeclarativeShadowRoots(bool aAllowDeclarativeShadowRoots);
3883 bool AllowsDeclarativeShadowRoots() const;
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 // The fingerprinting protections overrides for this document. The value will
4877 // override the default enabled fingerprinting protections for this document.
4878 // This will only get populated if these is one that comes from the local
4879 // fingerprinting protection override pref or WebCompat. Otherwise, a value of
4880 // Nothing() indicates no overrides are present for this document.
4881 Maybe<RFPTarget> mOverriddenFingerprintingSettings;
4883 uint8_t mXMLDeclarationBits;
4885 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4886 // use uint8_t to avoid having to include a bunch of style system headers
4887 // everywhere.
4888 uint8_t mColorSchemeBits = 0;
4890 // Currently active onload blockers.
4891 uint32_t mOnloadBlockCount;
4893 // Tracks if we are currently processing any document.write calls (either
4894 // implicit or explicit). Note that if a write call writes out something which
4895 // would block the parser, then mWriteLevel will be incorrect until the parser
4896 // finishes processing that script.
4897 uint32_t mWriteLevel;
4899 uint32_t mContentEditableCount;
4900 EditingState mEditingState;
4902 // Compatibility mode
4903 nsCompatibility mCompatMode;
4905 // Our readyState
4906 ReadyState mReadyState;
4908 // Ancestor's loading state
4909 bool mAncestorIsLoading;
4911 // Our visibility state
4912 dom::VisibilityState mVisibilityState;
4914 enum Type {
4915 eUnknown, // should never be used
4916 eHTML,
4917 eXHTML,
4918 eGenericXML,
4919 eSVG
4922 Type mType;
4924 uint8_t mDefaultElementType;
4926 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4928 Tri mAllowXULXBL;
4930 bool mSkipDTDSecurityChecks;
4932 // The document's script global object, the object from which the
4933 // document can get its script context and scope. This is the
4934 // *inner* window object.
4935 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4937 // If mIsStaticDocument is true, mOriginalDocument points to the original
4938 // document.
4939 RefPtr<Document> mOriginalDocument;
4941 // The bidi options for this document. What this bitfield means is
4942 // defined in nsBidiUtils.h
4943 uint32_t mBidiOptions;
4945 // The sandbox flags on the document. These reflect the value of the sandbox
4946 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4947 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4948 // possible flags.
4949 uint32_t mSandboxFlags;
4951 // The embedder policy obtained from parsing the HTTP response header or from
4952 // our opener if this is the initial about:blank document.
4953 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4955 RefPtr<nsAtom> mContentLanguage;
4957 // The channel that got passed to Document::StartDocumentLoad(), if any.
4958 nsCOMPtr<nsIChannel> mChannel;
4960 // The CSP for every load lives in the Client within the LoadInfo. For all
4961 // document-initiated subresource loads we can use that cached version of the
4962 // CSP so we do not have to deserialize the CSP from the Client all the time.
4963 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4964 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4966 private:
4967 nsCString mContentType;
4969 protected:
4970 // The document's security info
4971 nsCOMPtr<nsITransportSecurityInfo> mSecurityInfo;
4973 // The channel that failed to load and resulted in an error page.
4974 // This only applies to error pages. Might be null.
4975 nsCOMPtr<nsIChannel> mFailedChannel;
4977 // if this document is part of a multipart document,
4978 // the ID can be used to distinguish it from the other parts.
4979 uint32_t mPartID;
4981 // Cycle collector generation in which we're certain that this document
4982 // won't be collected
4983 uint32_t mMarkedCCGeneration;
4985 PresShell* mPresShell;
4987 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4988 uint32_t mSubtreeModifiedDepth;
4990 // All images in process of being preloaded. This is a hashtable so
4991 // we can remove them as the real image loads start; that way we
4992 // make sure to not keep the image load going when no one cares
4993 // about it anymore.
4994 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4996 // A list of preconnects initiated by the preloader. This prevents
4997 // the same uri from being used more than once, and allows the dom
4998 // builder to not repeat the work of the preloader.
4999 nsTHashMap<nsURIHashKey, bool> mPreloadedPreconnects;
5001 // Current depth of picture elements from parser
5002 uint32_t mPreloadPictureDepth;
5004 // Set if we've found a URL for the current picture
5005 nsString mPreloadPictureFoundSource;
5007 // If we're an external resource document, this will be non-null and will
5008 // point to our "display document": the one that all resource lookups should
5009 // go to.
5010 RefPtr<Document> mDisplayDocument;
5012 uint32_t mEventsSuppressed;
5014 // Any XHR ChannelEventQueues that were suspended on this document while
5015 // events were suppressed.
5016 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
5018 // Any postMessage events that were suspended on this document while events
5019 // were suppressed.
5020 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
5022 RefPtr<EventListener> mSuppressedEventListener;
5025 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5027 uint32_t mIgnoreDestructiveWritesCounter;
5029 // Count of live static clones of this document.
5030 uint32_t mStaticCloneCount;
5032 // If the document is currently printing (or in print preview) this will point
5033 // to the current static clone of this document. This is weak since the clone
5034 // also has a reference to this document.
5035 WeakPtr<Document> mLatestStaticClone;
5037 // Array of nodes that have been blocked to prevent user tracking.
5038 // They most likely have had their nsIChannel canceled by the URL
5039 // classifier. (Safebrowsing)
5041 // Weak nsINode pointers are used to allow nodes to disappear.
5042 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
5044 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5045 // updated on every set of mScriptGlobalObject.
5046 nsPIDOMWindowInner* mWindow;
5048 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
5050 FrameRequestManager mFrameRequestManager;
5052 // This object allows us to evict ourself from the back/forward cache. The
5053 // pointer is non-null iff we're currently in the bfcache.
5054 nsIBFCacheEntry* mBFCacheEntry;
5056 // Our base target.
5057 nsString mBaseTarget;
5059 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
5060 JS::Heap<JS::Value> mCachedStateObject;
5062 uint32_t mInSyncOperationCount;
5064 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
5066 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
5068 uint32_t mBlockDOMContentLoaded;
5070 // Our live MediaQueryLists
5071 LinkedList<MediaQueryList> mDOMMediaQueryLists;
5073 // A hashset to keep track of which {element, imgRequestProxy}
5074 // combination has been processed to avoid considering the same
5075 // element twice for LargestContentfulPaint.
5076 nsTHashtable<LCPEntryHashEntry> mContentIdentifiersForLCP;
5078 // Array of observers
5079 nsTObserverArray<nsIDocumentObserver*> mObservers;
5081 // Flags for use counters used directly by this document.
5082 UseCounters mUseCounters;
5083 // Flags for use counters from resource documents, static clones,
5084 // and SVG images referenced by this document. Those documents propagate
5085 // their use counters up to here, which then count towards the top-level
5086 // document's page use counters.
5087 UseCounters mChildDocumentUseCounters;
5089 // The CSS property use counters.
5090 UniquePtr<StyleUseCounters> mStyleUseCounters;
5092 TimeStamp mPageUnloadingEventTimeStamp;
5094 RefPtr<DocGroup> mDocGroup;
5096 RefPtr<nsCommandManager> mMidasCommandManager;
5098 // The set of all the tracking script URLs. URLs are added to this set by
5099 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5100 // existing in the set means the corresponding script isn't a tracking script.
5101 nsTHashSet<nsCString> mTrackingScripts;
5103 // Pointer to our parser if we're currently in the process of being
5104 // parsed into.
5105 nsCOMPtr<nsIParser> mParser;
5107 // If the document was created from the the prototype cache there will be a
5108 // reference to the prototype document to allow tracing.
5109 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
5111 // Weak reference to our sink for in case we no longer have a parser. This
5112 // will allow us to flush out any pending stuff from the sink even if
5113 // EndLoad() has already happened.
5114 nsWeakPtr mWeakSink;
5116 // Our update nesting level
5117 uint32_t mUpdateNestLevel;
5119 // HTTPS-Only Mode Status
5120 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5121 uint32_t mHttpsOnlyStatus;
5123 enum ViewportType : uint8_t {
5124 DisplayWidthHeight,
5125 Specified,
5126 Unknown,
5129 ViewportType mViewportType;
5131 // viewport-fit described by
5132 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5133 ViewportFitType mViewportFit;
5135 PLDHashTable* mSubDocuments;
5137 class HeaderData;
5138 UniquePtr<HeaderData> mHeaderData;
5140 nsTArray<net::EarlyHintConnectArgs> mEarlyHints;
5142 class TitleChangeEvent;
5143 nsRevocableEventPtr<TitleChangeEvent> mPendingTitleChangeEvent;
5145 RefPtr<nsDOMNavigationTiming> mTiming;
5147 // Recorded time of change to 'loading' state
5148 // or time of the page gets restored from BFCache.
5149 TimeStamp mLoadingOrRestoredFromBFCacheTimeStamp;
5151 // Decided to use nsTObserverArray because it allows us to
5152 // remove candidates while iterating them and this is what
5153 // the spec defines. We could implement the spec without
5154 // using nsTObserverArray, however using nsTObserverArray is more clear.
5155 nsTObserverArray<nsWeakPtr> mAutoFocusCandidates;
5157 nsCString mScrollToRef;
5159 // Weak reference to the scope object (aka the script global object)
5160 // that, unlike mScriptGlobalObject, is never unset once set. This
5161 // is a weak reference to avoid leaks due to circular references.
5162 nsWeakPtr mScopeObject;
5164 // Array of intersection observers
5165 nsTHashSet<DOMIntersectionObserver*> mIntersectionObservers;
5167 // Array of resize observers
5168 nsTArray<ResizeObserver*> mResizeObservers;
5170 RefPtr<DOMIntersectionObserver> mLazyLoadObserver;
5172 // ResizeObserver for storing and removing the last remembered size.
5173 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5174 RefPtr<ResizeObserver> mLastRememberedSizeObserver;
5176 // Stack of top layer elements.
5177 nsTArray<nsWeakPtr> mTopLayer;
5179 // The root of the doc tree in which this document is in. This is only
5180 // non-null when this document is in fullscreen mode.
5181 WeakPtr<Document> mFullscreenRoot;
5183 RefPtr<DOMImplementation> mDOMImplementation;
5185 RefPtr<nsContentList> mImageMaps;
5187 // A set of responsive images keyed by address pointer.
5188 nsTHashSet<HTMLImageElement*> mResponsiveContent;
5190 RefPtr<DocumentTimeline> mDocumentTimeline;
5191 LinkedList<DocumentTimeline> mTimelines;
5193 RefPtr<dom::ScriptLoader> mScriptLoader;
5195 // Tracker for scroll-driven animations that are waiting to start.
5196 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5197 RefPtr<ScrollTimelineAnimationTracker> mScrollTimelineAnimationTracker;
5199 // A document "without a browsing context" that owns the content of
5200 // HTMLTemplateElement.
5201 RefPtr<Document> mTemplateContentsOwner;
5203 dom::ExternalResourceMap mExternalResourceMap;
5205 // ScreenOrientation "pending promise" as described by
5206 // http://www.w3.org/TR/screen-orientation/
5207 RefPtr<Promise> mOrientationPendingPromise;
5209 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
5210 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
5211 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
5213 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
5215 // The layout history state that should be used by nodes in this
5216 // document. We only actually store a pointer to it when:
5217 // 1) We have no script global object.
5218 // 2) We haven't had Destroy() called on us yet.
5219 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
5221 // Mapping of wake lock types to sets of wake locks sentinels
5222 // https://w3c.github.io/screen-wake-lock/#internal-slots
5223 nsTHashMap<WakeLockType, nsTHashSet<RefPtr<WakeLockSentinel>>> mActiveLocks;
5225 // The parsed viewport metadata of the last modified <meta name=viewport>
5226 // element.
5227 UniquePtr<ViewportMetaData> mLastModifiedViewportMetaData;
5229 // A tree ordered list of all color-scheme meta tags in this document.
5231 // TODO(emilio): There are other meta tags in the spec that have a similar
5232 // processing model to color-scheme. We could store all in-document meta tags
5233 // here to get sane and fast <meta> element processing.
5234 TreeOrderedArray<HTMLMetaElement> mColorSchemeMetaTags;
5236 // These member variables cache information about the viewport so we don't
5237 // have to recalculate it each time.
5238 LayoutDeviceToScreenScale mScaleMinFloat;
5239 LayoutDeviceToScreenScale mScaleMaxFloat;
5240 LayoutDeviceToScreenScale mScaleFloat;
5241 CSSToLayoutDeviceScale mPixelRatio;
5243 CSSCoord mMinWidth;
5244 CSSCoord mMaxWidth;
5245 CSSCoord mMinHeight;
5246 CSSCoord mMaxHeight;
5248 RefPtr<EventListenerManager> mListenerManager;
5250 nsCOMPtr<nsIRequest> mOnloadBlocker;
5252 // Gecko-internal sheets used for extensions and such.
5253 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5254 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5256 // Member to store out last-selected stylesheet set.
5257 nsString mLastStyleSheetSet;
5258 nsString mPreferredStyleSheetSet;
5260 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5262 // We lazily calculate declaration blocks for elements with mapped
5263 // attributes. This set contains all elements which need lazy resolution.
5264 nsTHashSet<Element*> mLazyPresElements;
5266 nsTHashSet<RefPtr<nsAtom>> mLanguagesUsed;
5268 // TODO(emilio): Is this hot enough to warrant to be cached?
5269 RefPtr<nsAtom> mLanguageFromCharset;
5271 // Restyle root for servo's style system.
5273 // We store this as an nsINode, rather than as an Element, so that we can
5274 // store the Document node as the restyle root if the entire document (along
5275 // with all document-level native-anonymous content) needs to be restyled.
5277 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5278 // root corresponds to.
5279 nsCOMPtr<nsINode> mServoRestyleRoot;
5280 uint32_t mServoRestyleRootDirtyBits;
5282 // Used in conjunction with the create-an-element-for-the-token algorithm to
5283 // prevent custom element constructors from being able to use document.open(),
5284 // document.close(), and document.write() when they are invoked by the parser.
5285 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5287 // Count of unload/beforeunload/pagehide operations in progress.
5288 uint32_t mIgnoreOpensDuringUnloadCounter;
5290 nsCOMPtr<nsIDOMXULCommandDispatcher>
5291 mCommandDispatcher; // [OWNER] of the focus tracker
5293 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5294 RefPtr<XULPersist> mXULPersist;
5295 RefPtr<ChromeObserver> mChromeObserver;
5297 RefPtr<HTMLAllCollection> mAll;
5299 nsTHashSet<RefPtr<WorkerDocumentListener>> mWorkerListeners;
5301 // Pres shell resolution saved before entering fullscreen mode.
5302 float mSavedResolution;
5304 // Pres shell resolution saved before creating a MobileViewportManager.
5305 float mSavedResolutionBeforeMVM;
5307 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5309 bool mHasStoragePermission;
5311 // Document generation. Gets incremented everytime it changes.
5312 int32_t mGeneration;
5314 // Cached TabSizes values for the document.
5315 int32_t mCachedTabSizeGeneration;
5316 nsTabSizes mCachedTabSizes;
5318 // This is equal to document's principal but with an isolation key. See
5319 // StoragePrincipalHelper.h to know more.
5320 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5322 // The cached storage principal for this document.
5323 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5324 // which is required due to its CloneDocHelper() call site. :-(
5325 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5327 // The cached cookie principal for this document.
5328 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5329 // which is required due to its CloneDocHelper() call site. :-(
5330 mutable nsCOMPtr<nsIPrincipal> mActiveCookiePrincipal;
5332 // See GetNextFormNumber and GetNextControlNumber.
5333 int32_t mNextFormNumber;
5334 int32_t mNextControlNumber;
5336 uint32_t mMediaElementWithMSECount = 0;
5338 // Scope preloads per document. This is used by speculative loading as well.
5339 PreloadService mPreloadService;
5341 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5342 bool mShouldNotifyFetchSuccess;
5344 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5345 bool mShouldNotifyFormOrPasswordRemoved;
5347 // Record page load telemetry
5348 void RecordPageLoadEventTelemetry(
5349 glean::perf::PageLoadExtra& aEventTelemetryData);
5351 // Accumulate JS telemetry collected
5352 void AccumulateJSTelemetry(
5353 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5355 // Accumulate page load metrics
5356 void AccumulatePageLoadTelemetry(
5357 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5359 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5360 // Not holding strong refs here since we don't actually use the BBCs.
5361 nsTArray<const BrowserBridgeChild*> mOOPChildrenLoading;
5363 // Registry of custom highlight definitions associated with this document.
5364 RefPtr<class HighlightRegistry> mHighlightRegistry;
5366 // Used for tracking a number of recent canvas extractions (e.g. toDataURL),
5367 // this is used for a canvas fingerprinter detection heuristic.
5368 nsTArray<CanvasUsage> mCanvasUsage;
5369 uint64_t mLastCanvasUsage = 0;
5371 UniquePtr<RadioGroupContainer> mRadioGroupContainer;
5373 public:
5374 // Needs to be public because the bindings code pokes at it.
5375 JS::ExpandoAndGeneration mExpandoAndGeneration;
5377 bool HasPendingInitialTranslation();
5379 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5380 mL10nProtoElements;
5382 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5383 void SetSavedResolutionBeforeMVM(float aResolution) {
5384 mSavedResolutionBeforeMVM = aResolution;
5387 void LoadEventFired();
5389 RadioGroupContainer& OwnedRadioGroupContainer();
5391 static already_AddRefed<Document> ParseHTMLUnsafe(GlobalObject& aGlobal,
5392 const nsAString& aHTML);
5395 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5398 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5399 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5400 * object is deleted.
5402 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5403 public:
5405 * @param aSubTreeOwner The document in which a subtree will be modified.
5406 * @param aTarget The target of the possible DOMSubtreeModified event.
5407 * Can be nullptr, in which case mozAutoSubtreeModified
5408 * is just used to batch DOM mutations.
5410 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5411 UpdateTarget(aSubtreeOwner, aTarget);
5414 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5416 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5417 if (mSubtreeOwner) {
5418 mSubtreeOwner->MutationEventDispatched(mTarget);
5421 mTarget = aTarget;
5422 mSubtreeOwner = aSubtreeOwner;
5423 if (mSubtreeOwner) {
5424 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5428 private:
5429 nsCOMPtr<nsINode> mTarget;
5430 RefPtr<Document> mSubtreeOwner;
5433 enum class SyncOperationBehavior { eSuspendInput, eAllowInput };
5435 class AutoWalkBrowsingContextGroup {
5436 public:
5437 virtual ~AutoWalkBrowsingContextGroup() = default;
5439 protected:
5440 void SuppressBrowsingContext(BrowsingContext* aContext);
5441 void SuppressBrowsingContextGroup(BrowsingContextGroup* aGroup);
5442 void UnsuppressDocuments() {
5443 for (const auto& doc : mDocuments) {
5444 UnsuppressDocument(doc);
5447 virtual void SuppressDocument(Document* aDocument) = 0;
5448 virtual void UnsuppressDocument(Document* aDocument) = 0;
5449 AutoTArray<RefPtr<Document>, 16> mDocuments;
5452 class MOZ_RAII nsAutoSyncOperation : private AutoWalkBrowsingContextGroup {
5453 public:
5454 explicit nsAutoSyncOperation(Document* aDocument,
5455 SyncOperationBehavior aSyncBehavior);
5456 ~nsAutoSyncOperation();
5458 protected:
5459 void SuppressDocument(Document* aDocument) override;
5460 void UnsuppressDocument(Document* aDocument) override;
5462 private:
5463 uint32_t mMicroTaskLevel;
5464 const SyncOperationBehavior mSyncBehavior;
5465 RefPtr<BrowsingContext> mBrowsingContext;
5468 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5469 public:
5470 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5471 : mDocument(aDocument) {
5472 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5475 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5476 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5479 private:
5480 Document* mDocument;
5483 class MOZ_RAII IgnoreOpensDuringUnload final {
5484 public:
5485 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5486 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5489 ~IgnoreOpensDuringUnload() {
5490 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5493 private:
5494 Document* mDoc;
5497 bool IsInFocusedTab(Document* aDoc);
5499 // This covers all cases covered by IsInFocusedTab, but also ensures that
5500 // focused tab is "active" meaning not occluded.
5501 bool IsInActiveTab(Document* aDoc);
5503 } // namespace mozilla::dom
5505 NON_VIRTUAL_ADDREF_RELEASE(mozilla::dom::Document)
5507 // XXX These belong somewhere else
5508 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5509 nsIPrincipal* aPrincipal,
5510 nsIPrincipal* aPartitionedPrincipal,
5511 bool aLoadedAsData = false);
5513 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5514 nsIPrincipal* aPrincipal,
5515 nsIPrincipal* aPartitionedPrincipal,
5516 bool aLoadedAsData = false,
5517 bool aIsPlainDocument = false);
5519 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult,
5520 nsIPrincipal* aPrincipal,
5521 nsIPrincipal* aPartitionedPrincipal);
5523 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult,
5524 nsIPrincipal* aPrincipal,
5525 nsIPrincipal* aPartitionedPrincipal);
5527 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult,
5528 nsIPrincipal* aPrincipal,
5529 nsIPrincipal* aPartitionedPrincipal);
5531 // Enum for requesting a particular type of document when creating a doc
5532 enum DocumentFlavor {
5533 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5534 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5535 DocumentFlavorSVG, // SVGDocument
5536 DocumentFlavorXML, // XMLDocument
5537 DocumentFlavorPlain, // Just a Document
5540 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5541 // -- this method will not attempt to get a principal based on aDocumentURI.
5542 // Also, both aDocumentURI and aBaseURI must not be null.
5543 nsresult NS_NewDOMDocument(
5544 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5545 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5546 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5547 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5549 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5550 mozilla::dom::Document* ownerDoc = OwnerDoc();
5552 return ownerDoc != this ? ownerDoc : nullptr;
5555 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5557 inline mozilla::dom::Document* nsINode::AsDocument() {
5558 MOZ_ASSERT(IsDocument());
5559 return static_cast<mozilla::dom::Document*>(this);
5562 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5563 MOZ_ASSERT(IsDocument());
5564 return static_cast<const mozilla::dom::Document*>(this);
5567 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5568 return static_cast<nsINode*>(aDoc);
5571 #endif /* mozilla_dom_Document_h___ */