Bug 1838484 - Don't create module loader for template contents owner document r=smaug
[gecko.git] / dom / base / Document.h
blob3b12b31b65408500e081527662edc77f3fd64207
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/StorageAccessAPIHelper.h"
43 #include "mozilla/TaskCategory.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/DispatcherTrait.h"
51 #include "mozilla/dom/DocumentOrShadowRoot.h"
52 #include "mozilla/dom/Element.h"
53 #include "mozilla/dom/EventTarget.h"
54 #include "mozilla/dom/Nullable.h"
55 #include "mozilla/dom/TreeOrderedArray.h"
56 #include "mozilla/dom/ViewportMetaData.h"
57 #include "mozilla/glean/GleanMetrics.h"
58 #include "nsAtom.h"
59 #include "nsCOMArray.h"
60 #include "nsCOMPtr.h"
61 #include "nsClassHashtable.h"
62 #include "nsCompatibility.h"
63 #include "nsContentListDeclarations.h"
64 #include "nsCycleCollectionParticipant.h"
65 #include "nsTHashMap.h"
66 #include "nsDebug.h"
67 #include "nsExpirationTracker.h"
68 #include "nsGkAtoms.h"
69 #include "nsHashKeys.h"
70 #include "nsIChannel.h"
71 #include "nsIChannelEventSink.h"
72 #include "nsIContentViewer.h"
73 #include "nsID.h"
74 #include "nsIInterfaceRequestor.h"
75 #include "nsILoadContext.h"
76 #include "nsILoadGroup.h"
77 #include "nsILoadInfo.h"
78 #include "nsINode.h"
79 #include "nsIObserver.h"
80 #include "nsIParser.h"
81 #include "nsIPrincipal.h"
82 #include "nsIProgressEventSink.h"
83 #include "nsIRadioGroupContainer.h"
84 #include "nsIReferrerInfo.h"
85 #include "nsIRequestObserver.h"
86 #include "nsIScriptObjectPrincipal.h"
87 #include "nsIStreamListener.h"
88 #include "nsISupports.h"
89 #include "nsISupportsUtils.h"
90 #include "nsITransportSecurityInfo.h"
91 #include "nsIURI.h"
92 #include "nsIWeakReferenceUtils.h"
93 #include "nsLiteralString.h"
94 #include "nsPIDOMWindow.h"
95 #include "nsPropertyTable.h"
96 #include "nsRefPtrHashtable.h"
97 #include "nsString.h"
98 #include "nsTArray.h"
99 #include "nsTHashSet.h"
100 #include "nsTLiteralString.h"
101 #include "nsTObserverArray.h"
102 #include "nsThreadUtils.h"
103 #include "nsURIHashKey.h"
104 #include "nsViewportInfo.h"
105 #include "nsWeakReference.h"
106 #include "nsWindowSizes.h"
107 #include "nsXULElement.h"
108 #include "nscore.h"
110 // XXX We need to include this here to ensure that DefaultDeleter for Servo
111 // types is specialized before the template is instantiated. Probably, this
112 // should be included at some other place already that's generated by cbindgen.
113 #include "mozilla/ServoBindingTypes.h"
115 // windows.h #defines CreateEvent
116 #ifdef CreateEvent
117 # undef CreateEvent
118 #endif
120 #ifdef MOZILLA_INTERNAL_API
121 # include "mozilla/dom/DocumentBinding.h"
122 #else
123 namespace mozilla {
124 namespace dom {
125 class ElementCreationOptionsOrString;
126 } // namespace dom
127 } // namespace mozilla
128 #endif // MOZILLA_INTERNAL_API
130 class InfallibleAllocPolicy;
131 class JSObject;
132 class JSTracer;
133 class PLDHashTable;
134 class gfxUserFontSet;
135 class mozIDOMWindowProxy;
136 class nsCachableElementsByNameNodeList;
137 class nsCommandManager;
138 class nsContentList;
139 class nsCycleCollectionTraversalCallback;
140 class nsDOMCaretPosition;
141 class nsDOMNavigationTiming;
142 class nsDocShell;
143 class nsFrameLoader;
144 class nsFrameLoaderOwner;
145 class nsGenericHTMLElement;
146 class nsGlobalWindowInner;
147 class nsHTMLCSSStyleSheet;
148 class nsHTMLDocument;
149 class nsHTMLStyleSheet;
150 class nsHtml5TreeOpExecutor;
151 class nsIAppWindow;
152 class nsIAsyncVerifyRedirectCallback;
153 class nsIBFCacheEntry;
154 class nsIContent;
155 class nsIContentSecurityPolicy;
156 class nsIContentSink;
157 class nsICookieJarSettings;
158 class nsIDOMXULCommandDispatcher;
159 class nsIDocShell;
160 class nsIDocShellTreeItem;
161 class nsIDocumentEncoder;
162 class nsIDocumentObserver;
163 class nsIEventTarget;
164 class nsIFrame;
165 class nsIGlobalObject;
166 class nsIHTMLCollection;
167 class nsIInputStream;
168 class nsILayoutHistoryState;
169 class nsIObjectLoadingContent;
170 class nsIPermissionDelegateHandler;
171 class nsIRadioVisitor;
172 class nsIRequest;
173 class nsIRunnable;
174 class nsIScriptGlobalObject;
175 class nsISecurityConsoleMessage;
176 class nsISerialEventTarget;
177 class nsIStructuredCloneContainer;
178 class nsIVariant;
179 class nsNodeInfoManager;
180 class nsPIWindowRoot;
181 class nsPresContext;
182 class nsRange;
183 class nsSimpleContentList;
184 class nsTextNode;
185 class nsViewManager;
186 class nsXULPrototypeDocument;
187 struct JSContext;
188 struct nsFont;
190 namespace mozilla {
191 class AbstractThread;
192 class StyleSheet;
193 class EditorBase;
194 class EditorCommand;
195 class Encoding;
196 class ErrorResult;
197 class EventListenerManager;
198 class FullscreenExit;
199 class FullscreenRequest;
200 class HTMLEditor;
201 struct LangGroupFontPrefs;
202 class PendingAnimationTracker;
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 StyleSelectorList;
214 struct StyleUseCounters;
215 template <typename>
216 class OwningNonNull;
217 struct URLExtraData;
219 namespace css {
220 class Loader;
221 class ImageLoader;
222 class Rule;
223 } // namespace css
225 namespace dom {
226 class AnonymousContent;
227 class Attr;
228 class XULBroadcastManager;
229 class XULPersist;
230 class BrowserBridgeChild;
231 class ChromeObserver;
232 class ClientInfo;
233 class ClientState;
234 class CDATASection;
235 class Comment;
236 class CSSImportRule;
237 class DocumentL10n;
238 class DocumentFragment;
239 class DocumentTimeline;
240 class DocumentType;
241 class DOMImplementation;
242 class DOMIntersectionObserver;
243 class DOMStringList;
244 class Event;
245 class EventListener;
246 struct FailedCertSecurityInfo;
247 class FeaturePolicy;
248 class FontFaceSet;
249 class FrameRequestCallback;
250 class ImageTracker;
251 class HighlightRegistry;
252 class HTMLAllCollection;
253 class HTMLBodyElement;
254 class HTMLInputElement;
255 class HTMLMetaElement;
256 class HTMLDialogElement;
257 class HTMLSharedElement;
258 class HTMLImageElement;
259 struct LifecycleCallbackArgs;
260 class Link;
261 class Location;
262 class MediaQueryList;
263 struct NetErrorInfo;
264 class NodeFilter;
265 class NodeInfo;
266 class NodeIterator;
267 enum class OrientationType : uint8_t;
268 class ProcessingInstruction;
269 class Promise;
270 class ScriptLoader;
271 class Selection;
272 class ServiceWorkerDescriptor;
273 class ShadowRoot;
274 class SVGDocument;
275 class SVGElement;
276 class SVGSVGElement;
277 class SVGUseElement;
278 class ImageDocument;
279 class Touch;
280 class TouchList;
281 class TreeWalker;
282 enum class ViewportFitType : uint8_t;
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<nsIContentViewer> 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 nsIContentViewer based on aRequest. This is guaranteed to
450 * put null in *aViewer and *aLoadGroup on all failures.
452 nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** 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, nsIContentViewer* 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 nsIRadioGroupContainer,
539 public nsIScriptObjectPrincipal,
540 public DispatcherTrait,
541 public SupportsWeakPtr {
542 friend class DocumentOrShadowRoot;
544 protected:
545 explicit Document(const char* aContentType);
546 virtual ~Document();
548 Document(const Document&) = delete;
549 Document& operator=(const Document&) = delete;
551 public:
552 using ExternalResourceLoad = dom::ExternalResourceMap::ExternalResourceLoad;
553 using ReferrerPolicyEnum = dom::ReferrerPolicy;
554 using AdoptedStyleSheetCloneCache =
555 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
557 // nsINode overrides the new operator for DOM Arena allocation.
558 // to use the default one, we need to bring it back again
559 void* operator new(size_t aSize) { return ::operator new(aSize); }
562 * Called when XPCOM shutdown.
564 static void Shutdown();
566 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
568 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
570 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
572 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
573 nsINode)
575 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
576 do { \
577 for (RefPtr obs : mObservers.ForwardRange()) { \
578 if (obs->IsCallbackEnabled(nsIMutationObserver::k##func_)) { \
579 obs->func_ params_; \
582 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
583 looks bogus. */ \
584 if (PresShell* presShell = GetObservingPresShell()) { \
585 presShell->func_ params_; \
587 } while (0)
589 // nsIRadioGroupContainer
590 NS_IMETHOD WalkRadioGroup(const nsAString& aName,
591 nsIRadioVisitor* aVisitor) final {
592 return DocumentOrShadowRoot::WalkRadioGroup(aName, aVisitor);
595 void SetCurrentRadioButton(const nsAString& aName,
596 HTMLInputElement* aRadio) final {
597 DocumentOrShadowRoot::SetCurrentRadioButton(aName, aRadio);
600 HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) final {
601 return DocumentOrShadowRoot::GetCurrentRadioButton(aName);
604 NS_IMETHOD
605 GetNextRadioButton(const nsAString& aName, const bool aPrevious,
606 HTMLInputElement* aFocusedRadio,
607 HTMLInputElement** aRadioOut) final {
608 return DocumentOrShadowRoot::GetNextRadioButton(aName, aPrevious,
609 aFocusedRadio, aRadioOut);
611 void AddToRadioGroup(const nsAString& aName, HTMLInputElement* aRadio) final {
612 DocumentOrShadowRoot::AddToRadioGroup(aName, aRadio);
614 void RemoveFromRadioGroup(const nsAString& aName,
615 HTMLInputElement* aRadio) final {
616 DocumentOrShadowRoot::RemoveFromRadioGroup(aName, aRadio);
618 uint32_t GetRequiredRadioCount(const nsAString& aName) const final {
619 return DocumentOrShadowRoot::GetRequiredRadioCount(aName);
621 void RadioRequiredWillChange(const nsAString& aName,
622 bool aRequiredAdded) final {
623 DocumentOrShadowRoot::RadioRequiredWillChange(aName, aRequiredAdded);
625 bool GetValueMissingState(const nsAString& aName) const final {
626 return DocumentOrShadowRoot::GetValueMissingState(aName);
628 void SetValueMissingState(const nsAString& aName, bool aValue) final {
629 return DocumentOrShadowRoot::SetValueMissingState(aName, aValue);
632 nsIPrincipal* EffectiveCookiePrincipal() const;
634 nsIPrincipal* EffectiveStoragePrincipal() const;
636 // nsIScriptObjectPrincipal
637 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
639 nsIPrincipal* GetEffectiveCookiePrincipal() final {
640 return EffectiveCookiePrincipal();
643 nsIPrincipal* GetEffectiveStoragePrincipal() final {
644 return EffectiveStoragePrincipal();
647 // You should probably not be using this function, since it performs no checks
648 // to ensure that the partitioned principal should really be used here. It is
649 // only designed to be used in very specific circumstances, such as when
650 // inheriting the document/storage principal.
651 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
653 // Gets the appropriate principal to check the URI against a blocklist /
654 // allowlist.
655 nsIPrincipal* GetPrincipalForPrefBasedHacks() const;
657 void ClearActiveCookieAndStoragePrincipals() {
658 mActiveStoragePrincipal = nullptr;
659 mActiveCookiePrincipal = nullptr;
662 // EventTarget
663 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
664 EventListenerManager* GetOrCreateListenerManager() override;
665 EventListenerManager* GetExistingListenerManager() const override;
667 // This helper class must be set when we dispatch beforeunload and unload
668 // events in order to avoid unterminate sync XHRs.
669 class MOZ_RAII PageUnloadingEventTimeStamp {
670 RefPtr<Document> mDocument;
671 bool mSet;
673 public:
674 explicit PageUnloadingEventTimeStamp(Document* aDocument)
675 : mDocument(aDocument), mSet(false) {
676 MOZ_ASSERT(aDocument);
677 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
678 mDocument->SetPageUnloadingEventTimeStamp();
679 mSet = true;
683 ~PageUnloadingEventTimeStamp() {
684 if (mSet) {
685 mDocument->CleanUnloadEventsTimeStamp();
691 * Let the document know that we're starting to load data into it.
692 * @param aCommand The parser command. Must not be null.
693 * XXXbz It's odd to have that here.
694 * @param aChannel The channel the data will come from. The channel must be
695 * able to report its Content-Type.
696 * @param aLoadGroup The loadgroup this document should use from now on.
697 * Note that the document might not be the only thing using
698 * this loadgroup.
699 * @param aContainer The container this document is in. This may be null.
700 * XXXbz maybe we should make it more explicit (eg make the
701 * container an nsIWebNavigation or nsIDocShell or
702 * something)?
703 * @param [out] aDocListener the listener to pump data from the channel into.
704 * Generally this will be the parser this document
705 * sets up, or some sort of data-handler for media
706 * documents.
707 * @param aReset whether the document should call Reset() on itself. If this
708 * is false, the document will NOT set its principal to the
709 * channel's owner, will not clear any event listeners that are
710 * already set on it, etc.
712 * Once this has been called, the document will return false for
713 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
714 * sure this happens is the responsibility of the caller of
715 * StartDocumentLoad().
717 * This function has an implementation, and does some setup, but does NOT set
718 * *aDocListener; this is the job of subclasses.
720 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
721 nsILoadGroup* aLoadGroup,
722 nsISupports* aContainer,
723 nsIStreamListener** aDocListener,
724 bool aReset) = 0;
725 void StopDocumentLoad();
727 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
728 virtual bool SuppressParserErrorElement() { return false; }
730 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
731 virtual bool SuppressParserErrorConsoleMessages() { return false; }
733 // nsINode
734 void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
735 bool aNotify, ErrorResult& aRv) override;
736 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
737 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
738 return NS_ERROR_NOT_IMPLEMENTED;
740 nsresult CloneDocHelper(Document* clone) const;
742 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
745 * Signal that the document title may have changed
746 * (see Document::GetTitle).
747 * @param aBoundTitleElement true if an HTML or SVG <title> element
748 * has just been bound to the document.
750 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
753 * Return the URI for the document. May return null. If it ever stops being
754 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
755 * also never return null.
757 * The value returned corresponds to the "document's address" in
758 * HTML5. As such, it may change over the lifetime of the document, for
759 * instance as a result of the user navigating to a fragment identifier on
760 * the page, or as a result to a call to pushState() or replaceState().
762 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
764 nsIURI* GetDocumentURI() const { return mDocumentURI; }
767 * Return the original URI of the document. This is the same as the
768 * document's URI unless that has changed from its original value (for
769 * example, due to history.pushState() or replaceState() being invoked on the
770 * document).
772 * This method corresponds to the "creation URL" in HTML5 and, once set,
773 * doesn't change over the lifetime of the document.
775 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
777 nsIURI* GetOriginalURI() const { return mOriginalURI; }
780 * Return the base domain of the document. This has been computed using
781 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
782 * checks. When the URI of the document changes, this value is recomputed.
784 nsCString GetBaseDomain() const { return mBaseDomain; }
787 * Set the URI for the document. This also sets the document's original URI,
788 * if it's null.
790 void SetDocumentURI(nsIURI* aURI);
793 * Set the URI for the document loaded via XHR, when accessed from
794 * chrome privileged script.
796 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
799 * Set the base URI for the document loaded via XHR, when accessed from
800 * chrome privileged script.
802 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
805 * The CSP in general is stored in the ClientInfo, but we also cache
806 * the CSP on the document so subresources loaded within a document
807 * can query that cached CSP instead of having to deserialize the CSP
808 * from the Client.
810 * Please note that at the time of CSP parsing the Client is not
811 * available yet, hence we sync CSP of document and Client when the
812 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
814 nsIContentSecurityPolicy* GetCsp() const;
815 void SetCsp(nsIContentSecurityPolicy* aCSP);
817 nsIContentSecurityPolicy* GetPreloadCsp() const;
818 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
820 void GetCspJSON(nsString& aJSON);
823 * Set referrer policy and upgrade-insecure-requests flags
825 void ApplySettingsFromCSP(bool aSpeculative);
827 already_AddRefed<nsIParser> CreatorParserOrNull() {
828 nsCOMPtr<nsIParser> parser = mParser;
829 return parser.forget();
833 * ReferrerInfo getter for Document.webidl.
835 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
837 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
839 nsIReferrerInfo* GetPreloadReferrerInfo() const {
840 return mPreloadReferrerInfo;
843 * Return the referrer policy of the document. Return "default" if there's no
844 * valid meta referrer tag found in the document.
845 * Referrer policy should be inherited from parent if the iframe is srcdoc
847 ReferrerPolicyEnum GetReferrerPolicy() const;
850 * GetReferrerPolicy() for Document.webidl.
852 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
855 * If true, this flag indicates that all mixed content subresource
856 * loads for this document (and also embeded browsing contexts) will
857 * be blocked.
859 bool GetBlockAllMixedContent(bool aPreload) const {
860 if (aPreload) {
861 return mBlockAllMixedContentPreloads;
863 return mBlockAllMixedContent;
867 * If true, this flag indicates that all subresource loads for this
868 * document need to be upgraded from http to https.
869 * This flag becomes true if the CSP of the document itself, or any
870 * of the document's ancestors up to the toplevel document makes use
871 * of the CSP directive 'upgrade-insecure-requests'.
873 bool GetUpgradeInsecureRequests(bool aPreload) const {
874 if (aPreload) {
875 return mUpgradeInsecurePreloads;
877 return mUpgradeInsecureRequests;
880 void SetReferrerInfo(nsIReferrerInfo*);
883 * Referrer policy from <meta name="referrer" content=`policy`>
884 * will have higher priority than referrer policy from Referrer-Policy
885 * header. So override the old ReferrerInfo if we get one from meta
887 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
888 bool aPreload);
891 * Set the principals responsible for this document. Chances are, you do not
892 * want to be using this.
894 void SetPrincipals(nsIPrincipal* aPrincipal,
895 nsIPrincipal* aPartitionedPrincipal);
898 * Returns true if exempt from HTTPS-Only Mode upgrade.
900 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
903 * Return the LoadGroup for the document. May return null.
905 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
906 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
907 return group.forget();
911 * Return the fallback base URL for this document, as defined in the HTML
912 * specification. Note that this can return null if there is no document URI.
914 * XXXbz: This doesn't implement the bits for about:blank yet.
916 nsIURI* GetFallbackBaseURI() const {
917 if (mIsSrcdocDocument && mParentDocument) {
918 return mParentDocument->GetDocBaseURI();
920 return mDocumentURI;
924 * Return the referrer from document URI as defined in the Referrer Policy
925 * specification.
926 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
927 * While document is an iframe srcdoc document, let document be document's
928 * browsing context's browsing context container's node document.
929 * Then referrer should be document's URL
932 nsIURI* GetDocumentURIAsReferrer() const {
933 if (mIsSrcdocDocument && mParentDocument) {
934 return mParentDocument->GetDocumentURIAsReferrer();
936 return mDocumentURI;
940 * Return the base URI for relative URIs in the document (the document uri
941 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
942 * returned URI could be null if there is no document URI. If the document is
943 * a srcdoc document and has no explicit base URL, return the parent
944 * document's base URL.
946 nsIURI* GetDocBaseURI() const {
947 if (mDocumentBaseURI) {
948 return mDocumentBaseURI;
950 return GetFallbackBaseURI();
953 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
955 void SetBaseURI(nsIURI* aURI);
958 * Resolves a URI based on the document's base URI.
960 Result<OwningNonNull<nsIURI>, nsresult> ResolveWithBaseURI(
961 const nsAString& aURI);
964 * Return the URL data which style system needs for resolving url value.
965 * This method attempts to use the cached object in mCachedURLData, but
966 * if the base URI, document URI, or principal has changed since last
967 * call to this function, or the function is called the first time for
968 * the document, a new one is created.
970 URLExtraData* DefaultStyleAttrURLData();
971 nsIReferrerInfo* ReferrerInfoForInternalCSSAndSVGResources();
974 * Get/Set the base target of a link in a document.
976 void GetBaseTarget(nsAString& aBaseTarget) const {
977 aBaseTarget = mBaseTarget;
980 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
983 * Return a standard name for the document's character set.
985 NotNull<const Encoding*> GetDocumentCharacterSet() const {
986 return mCharacterSet;
990 * Set the document's character encoding.
992 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
994 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
996 // This method MUST be called before SetDocumentCharacterSet if
997 // you're planning to call both.
998 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
999 mCharacterSetSource = aCharsetSource;
1003 * Get the Content-Type of this document.
1005 void GetContentType(nsAString& aContentType);
1008 * Set the Content-Type of this document.
1010 void SetContentType(const nsACString& aContentType);
1013 * Return the language of this document.
1015 void GetContentLanguage(nsAString& aContentLanguage) const {
1016 CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
1019 // The states BidiEnabled and MathMLEnabled should persist across multiple
1020 // views (screen, print) of the same document.
1023 * Check if the document contains bidi data.
1024 * If so, we have to apply the Unicode Bidi Algorithm.
1026 bool GetBidiEnabled() const { return mBidiEnabled; }
1029 * Indicate the document contains bidi data.
1030 * Currently, we cannot disable bidi, because once bidi is enabled,
1031 * it affects a frame model irreversibly, and plays even though
1032 * the document no longer contains bidi data.
1034 void SetBidiEnabled() { mBidiEnabled = true; }
1036 void SetMathMLEnabled() { mMathMLEnabled = true; }
1039 * Ask this document whether it's the initial document in its window.
1041 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
1044 * Tell this document that it's the initial document in its window. See
1045 * comments on mIsInitialDocumentInWindow for when this should be called.
1047 void SetIsInitialDocument(bool aIsInitialDocument);
1049 void SetLoadedAsData(bool aLoadedAsData, bool aConsiderForMemoryReporting);
1052 * Normally we assert if a runnable labeled with one DocGroup touches data
1053 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1054 * means that we can touch that document from any DocGroup without asserting.
1056 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1059 * Get the bidi options for this document.
1060 * @see nsBidiUtils.h
1062 uint32_t GetBidiOptions() const { return mBidiOptions; }
1065 * Set the bidi options for this document. This just sets the bits;
1066 * callers are expected to take action as needed if they want this
1067 * change to actually change anything immediately.
1068 * @see nsBidiUtils.h
1070 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1073 * Set CSP flag for this document.
1075 void SetHasCSP(bool aHasCSP) { mHasCSP = aHasCSP; }
1078 * Set unsafe-inline CSP flag for this document.
1080 void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP) {
1081 mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
1085 * Set unsafe-eval CSP flag for this document.
1087 void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP) {
1088 mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
1092 * Returns true if the document holds a CSP
1093 * delivered through an HTTP Header.
1095 bool GetHasCSPDeliveredThroughHeader() {
1096 return mHasCSPDeliveredThroughHeader;
1100 * Return a promise which resolves to the content blocking events.
1102 using GetContentBlockingEventsPromise = MozPromise<uint32_t, bool, true>;
1103 [[nodiscard]] RefPtr<GetContentBlockingEventsPromise>
1104 GetContentBlockingEvents();
1107 * Get the sandbox flags for this document.
1108 * @see nsSandboxFlags.h for the possible flags
1110 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1112 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1113 return mEmbedderPolicy;
1116 void SetEmbedderPolicy(
1117 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1118 mEmbedderPolicy = aCOEP;
1122 * Get string representation of sandbox flags (null if no flags are set)
1124 void GetSandboxFlagsAsString(nsAString& aFlags);
1127 * Set the sandbox flags for this document.
1128 * @see nsSandboxFlags.h for the possible flags
1130 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1133 * Called when the document was decoded as UTF-8 and decoder encountered no
1134 * errors.
1136 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1139 * Called to disable client access to cookies through the document.cookie API
1140 * from user JavaScript code.
1142 void DisableCookieAccess() { mDisableCookieAccess = true; }
1144 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1145 bool LinkHandlingEnabled() { return mLinksEnabled; }
1148 * Set compatibility mode for this document
1150 void SetCompatibilityMode(nsCompatibility aMode);
1153 * Called to disable client access to document.write() API from user
1154 * JavaScript code.
1156 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1159 * Whether a document.write() call is in progress.
1161 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1164 * Access HTTP header data (this may also get set from other
1165 * sources, like HTML META tags).
1167 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1168 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1171 * Set Early Hint data, moves the arrays into the function, leaving the
1172 * passed variables empty
1174 void SetEarlyHints(nsTArray<net::EarlyHintConnectArgs>&& aEarlyHints);
1175 const nsTArray<net::EarlyHintConnectArgs>& GetEarlyHints() const {
1176 return mEarlyHints;
1180 * Create a new presentation shell that will use aContext for its
1181 * presentation context (presentation contexts <b>must not</b> be
1182 * shared among multiple presentation shells). The caller of this
1183 * method is responsible for calling BeginObservingDocument() on the
1184 * presshell if the presshell should observe document mutations.
1186 MOZ_CAN_RUN_SCRIPT already_AddRefed<PresShell> CreatePresShell(
1187 nsPresContext* aContext, nsViewManager* aViewManager);
1188 void DeletePresShell();
1190 PresShell* GetPresShell() const {
1191 return GetBFCacheEntry() ? nullptr : mPresShell;
1194 inline PresShell* GetObservingPresShell() const;
1196 // Return whether the presshell for this document is safe to flush.
1197 bool IsSafeToFlush() const;
1199 inline nsPresContext* GetPresContext() const;
1201 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1203 // Instead using this method, what you probably want is
1204 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1205 void DisallowBFCaching(uint32_t aStatus = BFCacheStatus::NOT_ALLOWED);
1207 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1209 // Accepts null to clear the BFCache entry too.
1210 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1212 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1214 // Removes this document from the BFCache, if it is cached, and returns
1215 // true if it was.
1216 bool RemoveFromBFCacheSync();
1219 * Return the parent document of this document. Will return null
1220 * unless this document is within a compound document and has a
1221 * parent. Note that this parent chain may cross chrome boundaries.
1223 Document* GetInProcessParentDocument() const { return mParentDocument; }
1226 * Set the parent document of this document.
1228 void SetParentDocument(Document* aParent) {
1229 mParentDocument = aParent;
1230 if (aParent) {
1231 RecomputeResistFingerprinting();
1232 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1233 if (!mIsDevToolsDocument) {
1234 mIsDevToolsDocument = mParentDocument->IsDevToolsDocument();
1239 void SetCurrentContextPaint(const SVGContextPaint* aContextPaint) {
1240 mCurrentContextPaint = aContextPaint;
1243 const SVGContextPaint* GetCurrentContextPaint() const {
1244 return mCurrentContextPaint;
1248 * Are plugins allowed in this document ?
1250 bool GetAllowPlugins();
1253 * Set the sub document for aContent to aSubDoc.
1255 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1258 * Get the sub document for aContent
1260 Document* GetSubDocumentFor(nsIContent* aContent) const;
1263 * Get the content node for which this document is a sub document.
1265 Element* GetEmbedderElement() const;
1268 * Return the doctype for this document.
1270 DocumentType* GetDoctype() const;
1273 * Return the root element for this document.
1275 Element* GetRootElement() const;
1277 Selection* GetSelection(ErrorResult& aRv);
1279 void MakeBrowsingContextNonSynthetic();
1280 nsresult HasStorageAccessSync(bool& aHasStorageAccess);
1281 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1283 StorageAccessAPIHelper::PerformPermissionGrant CreatePermissionGrantPromise(
1284 nsPIDOMWindowInner* aInnerWindow, nsIPrincipal* aPrincipal,
1285 bool aHasUserInteraction, const Maybe<nsCString>& aTopLevelBaseDomain);
1287 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1289 already_AddRefed<Promise> RequestStorageAccessForOrigin(
1290 const nsAString& aThirdPartyOrigin, const bool aRequireUserInteraction,
1291 ErrorResult& aRv);
1293 already_AddRefed<Promise> RequestStorageAccessUnderSite(
1294 const nsAString& aSerializedSite, ErrorResult& aRv);
1295 already_AddRefed<Promise> CompleteStorageAccessRequestFromSite(
1296 const nsAString& aSerializedOrigin, ErrorResult& aRv);
1298 bool UseRegularPrincipal() const;
1301 * Gets the event target to dispatch key events to if there is no focused
1302 * content in the document.
1304 virtual Element* GetUnfocusedKeyEventTarget();
1307 * Retrieve information about the viewport as a data structure.
1308 * This will return information in the viewport META data section
1309 * of the document. This can be used in lieu of ProcessViewportInfo(),
1310 * which places the viewport information in the document header instead
1311 * of returning it directly.
1313 * @param aDisplaySize size of the on-screen display area for this
1314 * document, in device pixels.
1316 * NOTE: If the site is optimized for mobile (via the doctype), this
1317 * will return viewport information that specifies default information.
1319 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1321 void SetMetaViewportData(UniquePtr<ViewportMetaData> aData);
1323 // Returns a ViewportMetaData for this document.
1324 ViewportMetaData GetViewportMetaData() const;
1327 * True iff this doc will ignore manual character encoding overrides.
1329 virtual bool WillIgnoreCharsetOverride() { return true; }
1332 * Return whether the document was created by a srcdoc iframe.
1334 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1337 * Sets whether the document was created by a srcdoc iframe.
1339 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1340 mIsSrcdocDocument = aIsSrcdocDocument;
1344 * Gets the srcdoc string from within the channel (assuming both exist).
1345 * Returns a void string if this isn't a srcdoc document or if
1346 * the channel has not been set.
1348 nsresult GetSrcdocData(nsAString& aSrcdocData);
1350 already_AddRefed<AnonymousContent> InsertAnonymousContent(
1351 Element& aElement, bool aForce, ErrorResult& aError);
1352 void RemoveAnonymousContent(AnonymousContent& aContent);
1354 * If aNode is a descendant of anonymous content inserted by
1355 * InsertAnonymousContent, this method returns the root element of the
1356 * inserted anonymous content (in other words, the clone of the aElement
1357 * that was passed to InsertAnonymousContent).
1359 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1360 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1361 return mAnonymousContents;
1364 TimeStamp GetPageUnloadingEventTimeStamp() const {
1365 if (!mParentDocument) {
1366 return mPageUnloadingEventTimeStamp;
1369 TimeStamp parentTimeStamp(
1370 mParentDocument->GetPageUnloadingEventTimeStamp());
1371 if (parentTimeStamp.IsNull()) {
1372 return mPageUnloadingEventTimeStamp;
1375 if (!mPageUnloadingEventTimeStamp ||
1376 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1377 return parentTimeStamp;
1380 return mPageUnloadingEventTimeStamp;
1383 void NotifyLayerManagerRecreated();
1386 * Add an SVG element to the list of elements that need
1387 * their mapped attributes resolved to a Servo declaration block.
1389 * These are weak pointers, please manually unschedule them when an element
1390 * is removed.
1392 void ScheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1393 mLazySVGPresElements.Insert(aSVG);
1396 // Unschedule an element scheduled by ScheduleFrameRequestCallback (e.g. for
1397 // when it is destroyed)
1398 void UnscheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1399 mLazySVGPresElements.Remove(aSVG);
1402 // Resolve all SVG pres attrs scheduled in ScheduleSVGForPresAttrEvaluation
1403 void ResolveScheduledSVGPresAttrs();
1405 Maybe<ClientInfo> GetClientInfo() const;
1406 Maybe<ClientState> GetClientState() const;
1407 Maybe<ServiceWorkerDescriptor> GetController() const;
1409 // Returns the size of the mBlockedNodesByClassifier array.
1411 // This array contains nodes that have been blocked to prevent user tracking,
1412 // fingerprinting, cryptomining, etc. They most likely have had their
1413 // nsIChannel canceled by the URL classifier (Safebrowsing).
1415 // A script can subsequently use GetBlockedNodesByClassifier()
1416 // to get a list of references to these nodes.
1418 // Note:
1419 // This expresses how many tracking nodes have been blocked for this document
1420 // since its beginning, not how many of them are still around in the DOM tree.
1421 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1422 // array but they are not removed when those nodes are removed from the tree
1423 // or even garbage collected.
1424 long BlockedNodeByClassifierCount() const {
1425 return mBlockedNodesByClassifier.Length();
1429 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1431 // This array contains nodes that have been blocked to prevent
1432 // user tracking. They most likely have had their nsIChannel
1433 // canceled by the URL classifier (Safebrowsing).
1435 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1437 // Helper method that returns true if the document has storage-access sandbox
1438 // flag.
1439 bool StorageAccessSandboxed() const;
1441 // Helper method that returns true if storage access API is enabled and
1442 // the passed flag has storage-access sandbox flag.
1443 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1445 // Returns the cookie jar settings for this and sub contexts.
1446 nsICookieJarSettings* CookieJarSettings();
1448 // Returns whether this document has the storage access permission.
1449 bool HasStorageAccessPermissionGranted();
1451 // Returns whether the storage access permission of the document is granted by
1452 // the allow list.
1453 bool HasStorageAccessPermissionGrantedByAllowList();
1455 // Increments the document generation.
1456 inline void Changed() { ++mGeneration; }
1458 // Returns the current generation.
1459 inline int32_t GetGeneration() const { return mGeneration; }
1461 // Adds cached sizes values to aSizes if there's any
1462 // cached value and if the document generation hasn't
1463 // changed since the cache was created.
1464 // Returns true if sizes were added.
1465 bool GetCachedSizes(nsTabSizes* aSizes);
1467 // Sets the cache sizes for the current generation.
1468 void SetCachedSizes(nsTabSizes* aSizes);
1471 * Should be called when an element's editable changes as a result of
1472 * changing its contentEditable attribute/property.
1474 * The change should be +1 if the contentEditable attribute/property was
1475 * changed to true, -1 if it was changed to false.
1477 void ChangeContentEditableCount(Element*, int32_t aChange);
1478 MOZ_CAN_RUN_SCRIPT void DeferredContentEditableCountChange(Element*);
1480 enum class EditingState : int8_t {
1481 eTearingDown = -2,
1482 eSettingUp = -1,
1483 eOff = 0,
1484 eDesignMode,
1485 eContentEditable
1489 * Returns the editing state of the document (not editable, contentEditable or
1490 * designMode).
1492 EditingState GetEditingState() const { return mEditingState; }
1495 * Returns whether the document is editable.
1497 bool IsEditingOn() const {
1498 return GetEditingState() == EditingState::eDesignMode ||
1499 GetEditingState() == EditingState::eContentEditable;
1502 class MOZ_STACK_CLASS nsAutoEditingState {
1503 public:
1504 nsAutoEditingState(Document* aDoc, EditingState aState)
1505 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1506 aDoc->mEditingState = aState;
1508 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1510 private:
1511 RefPtr<Document> mDoc;
1512 EditingState mSavedState;
1514 friend class nsAutoEditingState;
1517 * Set the editing state of the document. Don't use this if you want
1518 * to enable/disable editing, call EditingStateChanged() or
1519 * SetDesignMode().
1521 void SetEditingState(EditingState aState) { mEditingState = aState; }
1524 * Called when this Document's editor is destroyed.
1526 void TearingDownEditor();
1528 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1530 // Gets the next form number.
1532 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1533 // parser inserted form element.
1534 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1536 // Gets the next form control number.
1538 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1539 // parser inserted form control element.
1540 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1542 PreloadService& Preloads() { return mPreloadService; }
1544 bool HasThirdPartyChannel();
1546 bool ShouldIncludeInTelemetry(bool aAllowExtensionURIs);
1548 void AddMediaElementWithMSE();
1549 void RemoveMediaElementWithMSE();
1551 void DoNotifyPossibleTitleChange();
1553 void InitFeaturePolicy();
1554 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1556 void EnsureNotEnteringAndExitFullscreen();
1558 protected:
1559 friend class nsUnblockOnloadEvent;
1561 nsresult InitCSP(nsIChannel* aChannel);
1562 nsresult InitCOEP(nsIChannel* aChannel);
1564 nsresult InitReferrerInfo(nsIChannel* aChannel);
1566 void PostUnblockOnloadEvent();
1568 void DoUnblockOnload();
1570 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1572 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1573 NotNull<const Encoding*>& aEncoding,
1574 nsHtml5TreeOpExecutor* aExecutor);
1576 MOZ_CAN_RUN_SCRIPT void DispatchContentLoadedEvents();
1578 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1579 MOZ_CAN_RUN_SCRIPT_BOUNDARY void DispatchPageTransition(
1580 EventTarget* aDispatchTarget, const nsAString& aType, bool aInFrameSwap,
1581 bool aPersisted, bool aOnlySystemGroup);
1583 // Call this before the document does something that will unbind all content.
1584 // That will stop us from doing a lot of work as each element is removed.
1585 void DestroyElementMaps();
1587 Element* GetRootElementInternal() const;
1589 void SetPageUnloadingEventTimeStamp() {
1590 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1591 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1594 void CleanUnloadEventsTimeStamp() {
1595 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1596 mPageUnloadingEventTimeStamp = TimeStamp();
1600 * Clears any Servo element data stored on Elements in the document.
1602 void ClearStaleServoData();
1605 * Do the tree-disconnection that ResetToURI and document.open need to do.
1607 void DisconnectNodeTree();
1610 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1611 * "CheckKeyPressEventModel" event to check whether we should dispatch
1612 * keypress events in confluent model or split model. This should be
1613 * called only when mEditingState is changed to eDesignMode or
1614 * eConentEditable at first time.
1616 void MaybeDispatchCheckKeyPressEventModelEvent();
1618 /* Midas implementation */
1619 nsCommandManager* GetMidasCommandManager();
1621 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1623 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1624 // of places, and I'm pretty sure the exact ExecCommand call it
1625 // makes cannot actually run script.
1626 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1628 void MaybeEditingStateChanged();
1630 private:
1631 class SelectorCacheKey {
1632 public:
1633 explicit SelectorCacheKey(const nsACString& aString) : mKey(aString) {
1634 MOZ_COUNT_CTOR(SelectorCacheKey);
1637 nsCString mKey;
1638 nsExpirationState mState;
1640 nsExpirationState* GetExpirationState() { return &mState; }
1642 MOZ_COUNTED_DTOR(SelectorCacheKey)
1645 class SelectorCacheKeyDeleter;
1647 public:
1648 class SelectorCache final : public nsExpirationTracker<SelectorCacheKey, 4> {
1649 public:
1650 using SelectorList = UniquePtr<StyleSelectorList>;
1651 using Table = nsTHashMap<nsCStringHashKey, SelectorList>;
1653 explicit SelectorCache(nsIEventTarget* aEventTarget);
1654 void NotifyExpired(SelectorCacheKey*) final;
1656 // We do not call MarkUsed because it would just slow down lookups and
1657 // because we're OK expiring things after a few seconds even if they're
1658 // being used. Returns whether we actually had an entry for aSelector.
1660 // If we have an entry and the selector list returned has a null
1661 // StyleSelectorList*, that indicates that aSelector has already been
1662 // parsed and is not a syntactically valid selector.
1663 template <typename F>
1664 StyleSelectorList* GetListOrInsertFrom(const nsACString& aSelector,
1665 F&& aFrom) {
1666 MOZ_ASSERT(NS_IsMainThread());
1667 return mTable.LookupOrInsertWith(aSelector, std::forward<F>(aFrom)).get();
1670 ~SelectorCache();
1672 private:
1673 Table mTable;
1676 SelectorCache& GetSelectorCache() {
1677 if (!mSelectorCache) {
1678 mSelectorCache =
1679 MakeUnique<SelectorCache>(EventTargetFor(TaskCategory::Other));
1681 return *mSelectorCache;
1683 // Get the root <html> element, or return null if there isn't one (e.g.
1684 // if the root isn't <html>)
1685 Element* GetHtmlElement() const;
1686 // Returns the first child of GetHtmlContent which has the given tag,
1687 // or nullptr if that doesn't exist.
1688 Element* GetHtmlChildElement(nsAtom* aTag);
1689 // Get the canonical <body> element, or return null if there isn't one (e.g.
1690 // if the root isn't <html> or if the <body> isn't there)
1691 HTMLBodyElement* GetBodyElement();
1692 // Get the canonical <head> element, or return null if there isn't one (e.g.
1693 // if the root isn't <html> or if the <head> isn't there)
1694 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1695 // Get the "body" in the sense of document.body: The first <body> or
1696 // <frameset> that's a child of a root <html>
1697 nsGenericHTMLElement* GetBody();
1698 // Set the "body" in the sense of document.body.
1699 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1700 // Get the "head" element in the sense of document.head.
1701 HTMLSharedElement* GetHead();
1703 ServoStyleSet* StyleSetForPresShellOrMediaQueryEvaluation() const {
1704 return mStyleSet.get();
1707 // ShadowRoot has APIs that can change styles. This notifies the shell that
1708 // stlyes applicable in the shadow tree have potentially changed.
1709 void RecordShadowStyleChange(ShadowRoot&);
1711 // Needs to be called any time the applicable style can has changed, in order
1712 // to schedule a style flush and setup all the relevant state.
1713 void ApplicableStylesChanged();
1715 // Whether we filled the style set with any style sheet. Only meant to be used
1716 // from DocumentOrShadowRoot::Traverse.
1717 bool StyleSetFilled() const { return mStyleSetFilled; }
1720 * Accessors to the collection of stylesheets owned by this document.
1721 * Style sheets are ordered, most significant last.
1724 void InsertSheetAt(size_t aIndex, StyleSheet&);
1727 * Add a stylesheet to the document
1729 * TODO(emilio): This is only used by parts of editor that are no longer in
1730 * use by m-c or c-c, so remove.
1732 void AddStyleSheet(StyleSheet* aSheet) {
1733 MOZ_ASSERT(aSheet);
1734 InsertSheetAt(SheetCount(), *aSheet);
1738 * Notify the document that the applicable state of the sheet changed
1739 * and that observers should be notified and style sets updated
1741 void StyleSheetApplicableStateChanged(StyleSheet&);
1743 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1745 enum additionalSheetType {
1746 eAgentSheet,
1747 eUserSheet,
1748 eAuthorSheet,
1749 AdditionalSheetTypeCount
1752 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1753 nsIURI* aSheetURI);
1754 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1755 StyleSheet* aSheet);
1756 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1758 StyleSheet* GetFirstAdditionalAuthorSheet() {
1759 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1763 * Returns the index that aSheet should be inserted at to maintain document
1764 * ordering.
1766 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1769 * Get this document's CSSLoader. This is guaranteed to not return null.
1771 css::Loader* CSSLoader() const { return mCSSLoader; }
1774 * Get this document's StyleImageLoader. This is guaranteed to not return
1775 * null.
1777 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1780 * Get the channel that was passed to StartDocumentLoad or Reset for this
1781 * document. Note that this may be null in some cases (eg if
1782 * StartDocumentLoad or Reset were never called)
1784 nsIChannel* GetChannel() const { return mChannel; }
1787 * Get this document's attribute stylesheet. May return null if
1788 * there isn't one.
1790 nsHTMLStyleSheet* GetAttributeStyleSheet() const { return mAttrStyleSheet; }
1793 * Get this document's inline style sheet. May return null if there
1794 * isn't one
1796 nsHTMLCSSStyleSheet* GetInlineStyleSheet() const {
1797 return mStyleAttrStyleSheet;
1800 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1803 * Get/set the object from which the context for the event/script handling can
1804 * be got. Normally GetScriptHandlingObject() returns the same object as
1805 * GetScriptGlobalObject(), but if the document is loaded as data,
1806 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1807 * aHasHadScriptHandlingObject is set true if document has had the object
1808 * for event/script handling. Do not process any events/script if the method
1809 * returns null, but aHasHadScriptHandlingObject is true.
1811 nsIScriptGlobalObject* GetScriptHandlingObject(
1812 bool& aHasHadScriptHandlingObject) const {
1813 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1814 return mScriptGlobalObject ? mScriptGlobalObject.get()
1815 : GetScriptHandlingObjectInternal();
1817 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1820 * Get the object that is used as the scope for all of the content
1821 * wrappers whose owner document is this document. Unlike the script global
1822 * object, this will only return null when the global object for this
1823 * document is truly gone. Use this object when you're trying to find a
1824 * content wrapper in XPConnect.
1826 nsIGlobalObject* GetScopeObject() const;
1827 void SetScopeObject(nsIGlobalObject* aGlobal);
1830 * Return the window containing the document (the outer window).
1832 nsPIDOMWindowOuter* GetWindow() const {
1833 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1836 bool IsInBackgroundWindow() const {
1837 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1838 return outer && outer->IsBackground();
1842 * Return the inner window used as the script compilation scope for
1843 * this document. If you're not absolutely sure you need this, use
1844 * GetWindow().
1846 nsPIDOMWindowInner* GetInnerWindow() const {
1847 return mRemovedFromDocShell ? nullptr : mWindow;
1851 * Return the outer window ID.
1853 uint64_t OuterWindowID() const {
1854 nsPIDOMWindowOuter* window = GetWindow();
1855 return window ? window->WindowID() : 0;
1859 * Return the inner window ID.
1861 uint64_t InnerWindowID() const {
1862 nsPIDOMWindowInner* window = GetInnerWindow();
1863 return window ? window->WindowID() : 0;
1867 * Return WindowGlobalChild that is associated with the inner window.
1869 WindowGlobalChild* GetWindowGlobalChild() {
1870 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1871 : nullptr;
1875 * Return WindowContext associated with the inner window.
1877 WindowContext* GetWindowContext() const {
1878 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1881 bool IsTopLevelWindowInactive() const;
1884 * Get the script loader for this document
1886 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1889 * Add/Remove an element to the document's id and name hashes
1891 void AddToIdTable(Element* aElement, nsAtom* aId);
1892 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1893 void AddToNameTable(Element* aElement, nsAtom* aName);
1894 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1897 * Returns all elements in the top layer in the insertion order.
1899 nsTArray<Element*> GetTopLayer() const;
1901 bool TopLayerContains(Element&) const;
1903 // Do the "fullscreen element ready check" from the fullscreen spec.
1904 // It returns true if the given element is allowed to go into fullscreen.
1905 // It is responsive to dispatch "fullscreenerror" event when necessary.
1906 bool FullscreenElementReadyCheck(FullscreenRequest&);
1909 * When this is called on content process, this asynchronously requests that
1910 * the document make aElement the fullscreen element, and move into fullscreen
1911 * mode. The current fullscreen element (if any) is pushed onto the top layer,
1912 * and it can be returned to fullscreen status by calling
1913 * RestorePreviousFullscreenState().
1914 * If on chrome process, this is synchronously.
1916 * Note that requesting fullscreen in a document also makes the element which
1917 * contains this document in this document's parent document fullscreen. i.e.
1918 * the <iframe> or <browser> that contains this document is also mode
1919 * fullscreen. This happens recursively in all ancestor documents.
1921 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1922 bool aApplyFullscreenDirectly = false);
1924 private:
1925 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1926 bool aApplyFullscreenDirectly);
1927 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1928 bool aApplyFullscreenDirectly);
1930 // Pushes aElement onto the top layer
1931 void TopLayerPush(Element&);
1933 // Removes the topmost element for which aPredicate returns true from the top
1934 // layer. The removed element, if any, is returned.
1935 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicate);
1937 // Removes the given element from the top layer. The removed element, if any,
1938 // is returned.
1939 Element* TopLayerPop(Element&);
1941 MOZ_CAN_RUN_SCRIPT bool TryAutoFocusCandidate(Element& aElement);
1943 public:
1944 // Removes all the elements with fullscreen flag set from the top layer, and
1945 // clears their fullscreen flag.
1946 void CleanupFullscreenState();
1948 // Pops the fullscreen element from the top layer and clears its
1949 // fullscreen flag. Returns whether there was any fullscreen element.
1950 enum class UpdateViewport : bool { No, Yes };
1951 bool PopFullscreenElement(UpdateViewport = UpdateViewport::Yes);
1953 // Pushes the given element into the top of top layer and set fullscreen
1954 // flag.
1955 void SetFullscreenElement(Element&);
1957 // Whether we has pending fullscreen request.
1958 bool HasPendingFullscreenRequests();
1960 // Cancel the dialog element if the document is blocked by the dialog
1961 void TryCancelDialog();
1963 void AddModalDialog(HTMLDialogElement&);
1964 void RemoveModalDialog(HTMLDialogElement&);
1967 * Called when a frame in a child process has entered fullscreen or when a
1968 * fullscreen frame in a child process changes to another origin.
1969 * aFrameElement is the frame element which contains the child-process
1970 * fullscreen document.
1972 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1975 * Called when a frame in a remote child document has rolled back fullscreen
1976 * so that all its top layer are empty; we must continue the
1977 * rollback in this parent process' doc tree branch which is fullscreen.
1978 * Note that only one branch of the document tree can have its documents in
1979 * fullscreen state at one time. We're in inconsistent state if a
1980 * fullscreen document has a parent and that parent isn't fullscreen. We
1981 * preserve this property across process boundaries.
1983 void RemoteFrameFullscreenReverted();
1986 * Restores the previous fullscreen element to fullscreen status. If there
1987 * is no former fullscreen element, this exits fullscreen, moving the
1988 * top-level browser window out of fullscreen mode.
1990 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1993 * Returns true if this document is a fullscreen leaf document, i.e. it
1994 * is in fullscreen mode and has no fullscreen children.
1996 bool IsFullscreenLeaf();
1999 * Returns the document which is at the root of this document's branch
2000 * in the in-process document tree. Returns nullptr if the document isn't
2001 * fullscreen.
2003 Document* GetFullscreenRoot();
2005 size_t CountFullscreenElements() const;
2008 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
2009 * in this document.
2011 void SetFullscreenRoot(Document* aRoot);
2014 * Synchronously cleans up the fullscreen state on the given document.
2016 * Calling this without performing fullscreen transition could lead
2017 * to undesired effect (the transition happens after document state
2018 * flips), hence it should only be called either by nsGlobalWindow
2019 * when we have performed the transition, or when it is necessary to
2020 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
2021 * should be called instead.
2023 * aDocument must not be null.
2025 static void ExitFullscreenInDocTree(Document* aDocument);
2028 * Ask the document to exit fullscreen state asynchronously.
2030 * Different from ExitFullscreenInDocTree(), this allows the window
2031 * to perform fullscreen transition first if any.
2033 * If aDocument is null, it will exit fullscreen from all documents
2034 * in all windows.
2036 static void AsyncExitFullscreen(Document* aDocument);
2039 * Handles any pending fullscreen in aDocument or its subdocuments.
2041 * Returns whether there is any fullscreen request handled.
2043 static bool HandlePendingFullscreenRequests(Document* aDocument);
2046 * Clear pending fullscreen in aDocument.
2048 static void ClearPendingFullscreenRequests(Document* aDocument);
2050 // ScreenOrientation related APIs
2052 void ClearOrientationPendingPromise();
2053 bool SetOrientationPendingPromise(Promise* aPromise);
2054 Promise* GetOrientationPendingPromise() const {
2055 return mOrientationPendingPromise;
2058 //----------------------------------------------------------------------
2060 // Document notification API's
2063 * Add a new observer of document change notifications. Whenever
2064 * content is changed, appended, inserted or removed the observers are
2065 * informed. An observer that is already observing the document must
2066 * not be added without being removed first.
2068 void AddObserver(nsIDocumentObserver* aObserver);
2071 * Remove an observer of document change notifications. This will
2072 * return false if the observer cannot be found.
2074 bool RemoveObserver(nsIDocumentObserver* aObserver);
2076 // Observation hooks used to propagate notifications to document observers.
2077 // BeginUpdate must be called before any batch of modifications of the
2078 // content model or of style data, EndUpdate must be called afterward.
2079 // To make this easy and painless, use the mozAutoDocUpdate helper class.
2080 void BeginUpdate();
2081 void EndUpdate();
2082 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
2084 void BeginLoad();
2085 virtual void EndLoad();
2087 enum ReadyState {
2088 READYSTATE_UNINITIALIZED = 0,
2089 READYSTATE_LOADING = 1,
2090 READYSTATE_INTERACTIVE = 3,
2091 READYSTATE_COMPLETE = 4
2093 // Set the readystate of the document. If aUpdateTimingInformation is true,
2094 // this will record relevant timestamps in the document's performance timing.
2095 // Some consumers (document.open is the only one right now, actually) don't
2096 // want to do that, though.
2097 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2098 ReadyState GetReadyStateEnum() { return mReadyState; }
2100 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2101 ReadyState aNewState);
2103 void NotifyAbortedLoad();
2105 // Notify that an element changed state. This must happen under a
2106 // scriptblocker but NOT within a begin/end update.
2107 void ElementStateChanged(Element*, ElementState);
2109 // Update a set of document states that may have changed.
2110 // This should only be called by callers whose state is also reflected in the
2111 // implementation of Document::GetDocumentState.
2113 // aNotify controls whether we notify our DocumentStatesChanged observers.
2114 void UpdateDocumentStates(DocumentState aMaybeChangedStates, bool aNotify);
2116 void ResetDocumentDirection();
2118 // Observation hooks for style data to propagate notifications
2119 // to document observers
2120 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2121 void RuleAdded(StyleSheet&, css::Rule&);
2122 void RuleRemoved(StyleSheet&, css::Rule&);
2123 void SheetCloned(StyleSheet&) {}
2124 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2127 * Flush notifications for this document and its parent documents
2128 * (since those may affect the layout of this one).
2130 void FlushPendingNotifications(FlushType aType);
2133 * Another variant of the above FlushPendingNotifications. This function
2134 * takes a ChangesToFlush to specify whether throttled animations are flushed
2135 * or not.
2136 * If in doubt, use the above FlushPendingNotifications.
2138 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2139 void FlushPendingNotifications(ChangesToFlush aFlush);
2142 * Calls FlushPendingNotifications on any external resources this document
2143 * has. If this document has no external resources or is an external resource
2144 * itself this does nothing. This should only be called with
2145 * aType >= FlushType::Style.
2147 void FlushExternalResources(FlushType aType);
2149 void AddWorkerDocumentListener(WorkerDocumentListener* aListener);
2150 void RemoveWorkerDocumentListener(WorkerDocumentListener* aListener);
2152 // Triggers an update of <svg:use> element shadow trees.
2153 void UpdateSVGUseElementShadowTrees() {
2154 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2155 return;
2157 DoUpdateSVGUseElementShadowTrees();
2161 * Only to be used inside Gecko, you can't really do anything with the
2162 * pointer outside Gecko anyway.
2164 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2167 * Reset the document using the given channel and loadgroup. This works
2168 * like ResetToURI, but also sets the document's channel to aChannel.
2169 * The principal of the document will be set from the channel.
2171 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2174 * Reset this document to aURI, aLoadGroup, aPrincipal and
2175 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2176 * content principal based on aURI will be used.
2178 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2179 nsIPrincipal* aPrincipal,
2180 nsIPrincipal* aPartitionedPrincipal);
2183 * Set the container (docshell) for this document. Virtual so that
2184 * docshell can call it.
2186 virtual void SetContainer(nsDocShell* aContainer);
2189 * Get the container (docshell) for this document.
2191 nsISupports* GetContainer() const;
2194 * Get the container's load context for this document.
2196 nsILoadContext* GetLoadContext() const;
2199 * Get docshell the for this document.
2201 nsIDocShell* GetDocShell() const;
2204 * Set and get XML declaration. If aVersion is null there is no declaration.
2205 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2206 * was no standalone parameter in the declaration, that it was given as no,
2207 * or that it was given as yes.
2209 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2210 const int32_t aStandalone);
2211 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2212 nsAString& Standalone);
2215 * Returns the bits for the color-scheme specified by the
2216 * <meta name="color-scheme">.
2218 uint8_t GetColorSchemeBits() const { return mColorSchemeBits; }
2221 * Traverses the DOM and computes the supported color schemes as per
2222 * https://html.spec.whatwg.org/#meta-color-scheme
2224 void RecomputeColorScheme();
2225 void AddColorSchemeMeta(HTMLMetaElement&);
2226 void RemoveColorSchemeMeta(HTMLMetaElement&);
2229 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2230 * regular HTML document with Content-Type "text/html", image documents and
2231 * media documents). Returns false for XHTML and any other documents parsed
2232 * by the XML parser.
2234 bool IsHTMLDocument() const { return mType == eHTML; }
2235 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2236 bool IsImageDocument() const {
2237 return MediaDocumentKind() == MediaDocumentKind::Image;
2239 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2240 bool IsSVGDocument() const { return mType == eSVG; }
2241 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2242 bool LoadsFullXULStyleSheetUpFront() {
2243 if (IsSVGDocument()) {
2244 return false;
2246 return AllowXULXBL();
2249 bool IsScriptEnabled() const;
2252 * Returns true if this document was created from a nsXULPrototypeDocument.
2254 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2256 * Returns the prototype the document was created from, or null if it was not
2257 * created from a prototype.
2259 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2261 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2262 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2263 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2266 bool IsContentDocument() const { return mIsContentDocument; }
2267 void SetIsContentDocument(bool aIsContentDocument) {
2268 mIsContentDocument = aIsContentDocument;
2271 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2273 * Create an element with the specified name, prefix and namespace ID.
2274 * Returns null if element name parsing failed.
2276 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2277 int32_t aNamespaceID,
2278 const nsAString* aIs = nullptr);
2281 * Get the security info (i.e. SSL state etc) that the document got
2282 * from the channel/document that created the content of the
2283 * document.
2285 * @see nsIChannel
2287 nsITransportSecurityInfo* GetSecurityInfo() { return mSecurityInfo; }
2290 * Get the channel that failed to load and resulted in an error page, if it
2291 * exists. This is only relevant to error pages.
2293 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2296 * This function checks if the document that is trying to access
2297 * GetNetErrorInfo is a trusted about net error page or not.
2299 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2302 * This function checks if the document that is trying to access
2303 * ReloadWithHttpsOnlyException is a trusted HTTPS only error page.
2305 static bool CallerIsTrustedAboutHttpsOnlyError(JSContext* aCx,
2306 JSObject* aObject);
2309 * Get security info like error code for a failed channel. This
2310 * property is only exposed to about:neterror documents.
2312 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2315 * This function checks if the document that is trying to access
2316 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2318 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2321 * This function checks if the privilege storage access api is available for
2322 * the caller. We only allow privilege SSA to be called by system principal
2323 * and webcompat extension.
2325 static bool CallerCanAccessPrivilegeSSA(JSContext* aCx, JSObject* aObject);
2328 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2329 * failed Channel. This property is only exposed for about:certerror
2330 * documents.
2332 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2333 ErrorResult& aRv);
2336 * Set the channel that failed to load and resulted in an error page.
2337 * This is only relevant to error pages.
2339 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2342 * Returns the default namespace ID used for elements created in this
2343 * document.
2345 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2347 void RemoveAllProperties();
2348 void RemoveAllPropertiesFor(nsINode* aNode);
2350 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2353 * Sets the ID used to identify this part of the multipart document
2355 void SetPartID(uint32_t aID) { mPartID = aID; }
2358 * Return the ID used to identify this part of the multipart document
2360 uint32_t GetPartID() const { return mPartID; }
2363 * Sanitize the document by resetting all input elements and forms that have
2364 * autocomplete=off to their default values.
2365 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2367 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Sanitize();
2370 * Enumerate all subdocuments.
2371 * The enumerator callback should return CallState::Continue to continue
2372 * enumerating, or CallState::Stop to stop. This will never get passed a null
2373 * aDocument.
2375 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2376 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2379 * Collect all the descendant documents for which |aCalback| returns true.
2380 * The callback function must not mutate any state for the given document.
2382 using nsDocTestFunc = bool (*)(const Document* aDocument);
2383 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2384 nsDocTestFunc aCallback) const;
2387 * Check whether it is safe to cache the presentation of this document
2388 * and all of its subdocuments (depending on the 3rd param). This method
2389 * checks the following conditions recursively:
2390 * - Some document types, such as plugin documents, cannot be safely cached.
2391 * - If there are any pending requests, we don't allow the presentation
2392 * to be cached. Ideally these requests would be suspended and resumed,
2393 * but that is difficult in some cases, such as XMLHttpRequest.
2394 * - If there are any beforeunload or unload listeners, we must fire them
2395 * for correctness, but this likely puts the document into a state where
2396 * it would not function correctly if restored.
2398 * |aNewRequest| should be the request for a new document which will
2399 * replace this document in the docshell. The new document's request
2400 * will be ignored when checking for active requests. If there is no
2401 * request associated with the new document, this parameter may be null.
2403 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2404 * combination is when we try to BFCache aNewRequest
2406 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2407 uint32_t& aBFCacheCombo,
2408 bool aIncludeSubdocuments,
2409 bool aAllowUnloadListeners = true);
2411 virtual nsresult Init();
2414 * Notify the document that its associated ContentViewer is being destroyed.
2415 * This releases circular references so that the document can go away.
2416 * Destroy() is only called on documents that have a content viewer.
2418 virtual void Destroy();
2421 * Notify the document that its associated ContentViewer is no longer
2422 * the current viewer for the docshell. The document might still
2423 * be rendered in "zombie state" until the next document is ready.
2424 * The document should save form control state.
2426 void RemovedFromDocShell();
2429 * Get the layout history state that should be used to save and restore state
2430 * for nodes in this document. This may return null; if that happens state
2431 * saving and restoration is not possible.
2433 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2436 * Methods that can be used to prevent onload firing while an event that
2437 * should block onload is posted. onload is guaranteed to not fire until
2438 * either all calls to BlockOnload() have been matched by calls to
2439 * UnblockOnload() or the load has been stopped altogether (by the user
2440 * pressing the Stop button, say).
2442 void BlockOnload();
2444 * @param aFireSync whether to fire onload synchronously. If false,
2445 * onload will fire asynchronously after all onload blocks have been
2446 * removed. It will NOT fire from inside UnblockOnload. If true,
2447 * onload may fire from inside UnblockOnload.
2449 void UnblockOnload(bool aFireSync);
2451 // Only BlockOnload should call this!
2452 void AsyncBlockOnload();
2454 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2456 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnblockDOMContentLoaded();
2459 * Notification that the page has been shown, for documents which are loaded
2460 * into a DOM window. This corresponds to the completion of document load,
2461 * or to the page's presentation being restored into an existing DOM window.
2462 * This notification fires applicable DOM events to the content window. See
2463 * PageTransitionEvent.webidl for a description of the |aPersisted|
2464 * parameter. If aDispatchStartTarget is null, the pageshow event is
2465 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2466 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2467 * event is only dispatched to listeners in the system group.
2468 * Note: if aDispatchStartTarget isn't null, the showing state of the
2469 * document won't be altered.
2471 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2472 bool aOnlySystemGroup = false);
2475 * Notification that the page has been hidden, for documents which are loaded
2476 * into a DOM window. This corresponds to the unloading of the document, or
2477 * to the document's presentation being saved but removed from an existing
2478 * DOM window. This notification fires applicable DOM events to the content
2479 * window. See PageTransitionEvent.webidl for a description of the
2480 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2481 * event is dispatched on the ScriptGlobalObject for this document,
2482 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2483 * true, the event is only dispatched to listeners in the system group.
2484 * Note: if aDispatchStartTarget isn't null, the showing state of the
2485 * document won't be altered.
2487 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2488 bool aOnlySystemGroup = false);
2491 * We record the set of links in the document that are relevant to
2492 * style.
2495 * Notification that an element is a link that is relevant to style.
2497 void AddStyleRelevantLink(Link* aLink) {
2498 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2499 #ifdef DEBUG
2500 NS_ASSERTION(!mStyledLinks.Contains(aLink),
2501 "Document already knows about this Link!");
2502 mStyledLinksCleared = false;
2503 #endif
2504 mStyledLinks.Insert(aLink);
2508 * Notification that an element is a link and its URI might have been
2509 * changed or the element removed. If the element is still a link relevant
2510 * to style, then someone must ensure that AddStyleRelevantLink is
2511 * (eventually) called on it again.
2513 void ForgetLink(Link* aLink) {
2514 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2515 #ifdef DEBUG
2516 bool linkContained = mStyledLinks.Contains(aLink);
2517 NS_ASSERTION(linkContained || mStyledLinksCleared,
2518 "Document knows nothing about this Link!");
2519 #endif
2520 mStyledLinks.Remove(aLink);
2523 // Refreshes the hrefs of all the links in the document.
2524 void RefreshLinkHrefs();
2527 * Support for window.matchMedia()
2530 already_AddRefed<MediaQueryList> MatchMedia(const nsACString& aMediaQueryList,
2531 CallerType aCallerType);
2533 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2536 * Get the compatibility mode for this document
2538 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2541 * Check whether we've ever fired a DOMTitleChanged event for this
2542 * document.
2544 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2547 * To batch DOMSubtreeModified, document needs to be informed when
2548 * a mutation event might be dispatched, even if the event isn't actually
2549 * created because there are no listeners for it.
2551 * @param aTarget is the target for the mutation event.
2553 void MayDispatchMutationEvent(nsINode* aTarget) {
2554 if (mSubtreeModifiedDepth > 0) {
2555 mSubtreeModifiedTargets.AppendObject(aTarget);
2560 * Marks as not-going-to-be-collected for the given generation of
2561 * cycle collection.
2563 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2564 mMarkedCCGeneration = aGeneration;
2568 * Gets the cycle collector generation this document is marked for.
2570 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2573 * Returns whether this document is cookie averse. See
2574 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2576 bool IsCookieAverse() const {
2577 // If we are a document that "has no browsing context."
2578 if (!GetInnerWindow()) {
2579 return true;
2582 // If we are a document "whose URL's scheme is not a network scheme."
2583 // NB: Explicitly allow file: URIs to store cookies.
2585 return !NodePrincipal()->SchemeIs("http") &&
2586 !NodePrincipal()->SchemeIs("https") &&
2587 !NodePrincipal()->SchemeIs("file");
2590 bool IsLoadedAsData() { return mLoadedAsData; }
2592 void SetAddedToMemoryReportAsDataDocument() {
2593 mAddedToMemoryReportingAsDataDocument = true;
2596 void UnregisterFromMemoryReportingForDataDocument();
2598 bool MayStartLayout() { return mMayStartLayout; }
2600 void SetMayStartLayout(bool aMayStartLayout);
2602 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2604 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2606 // In case of failure, the document really can't initialize the frame loader.
2607 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2608 // In case of failure, the caller must handle the error, for example by
2609 // finalizing frame loader asynchronously.
2610 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2611 // Removes the frame loader of aShell from the initialization list.
2612 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2615 * Check whether this document is a root document that is not an
2616 * external resource.
2618 bool IsRootDisplayDocument() const {
2619 return !mParentDocument && !mDisplayDocument;
2622 bool ChromeRulesEnabled() const { return mChromeRulesEnabled; }
2624 bool IsInChromeDocShell() const {
2625 const Document* root = this;
2626 while (const Document* displayDoc = root->GetDisplayDocument()) {
2627 root = displayDoc;
2629 return root->mInChromeDocShell;
2632 bool IsDevToolsDocument() const { return mIsDevToolsDocument; }
2634 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2636 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2638 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2640 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2642 bool IsResourceDoc() const {
2643 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2644 mHasDisplayDocument; // Are we an external resource doc?
2648 * Get the document for which this document is an external resource. This
2649 * will be null if this document is not an external resource. Otherwise,
2650 * GetDisplayDocument() will return a non-null document, and
2651 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2653 Document* GetDisplayDocument() const { return mDisplayDocument; }
2656 * Set the display document for this document. aDisplayDocument must not be
2657 * null.
2659 void SetDisplayDocument(Document* aDisplayDocument) {
2660 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2661 "Shouldn't set mDisplayDocument on documents that already "
2662 "have a presentation or a docshell or a window");
2663 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2664 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2665 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2666 "Display documents should not nest");
2667 mDisplayDocument = aDisplayDocument;
2668 mHasDisplayDocument = !!aDisplayDocument;
2672 * Request an external resource document for aURI. This will return the
2673 * resource document if available. If one is not available yet, it will
2674 * start loading as needed, and the pending load object will be returned in
2675 * aPendingLoad so that the caller can register an observer to wait for the
2676 * load. If this function returns null and doesn't return a pending load,
2677 * that means that there is no resource document for this URI and won't be
2678 * one in the future.
2680 * @param aURI the URI to get
2681 * @param aReferrerInfo the referrerInfo of the request
2682 * @param aRequestingNode the node making the request
2683 * @param aPendingLoad the pending load for this request, if any
2685 Document* RequestExternalResource(nsIURI* aURI,
2686 nsIReferrerInfo* aReferrerInfo,
2687 nsINode* aRequestingNode,
2688 ExternalResourceLoad** aPendingLoad);
2691 * Enumerate the external resource documents associated with this document.
2692 * The enumerator callback should return CallState::Continue to continue
2693 * enumerating, or CallState::Stop to stop. This callback will never get
2694 * passed a null aDocument.
2696 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2698 dom::ExternalResourceMap& ExternalResourceMap() {
2699 return mExternalResourceMap;
2703 * Return whether the document is currently showing (in the sense of
2704 * OnPageShow() having been called already and OnPageHide() not having been
2705 * called yet.
2707 bool IsShowing() const { return mIsShowing; }
2709 * Return whether the document is currently visible (in the sense of
2710 * OnPageHide having been called and OnPageShow not yet having been called)
2712 bool IsVisible() const { return mVisible; }
2714 void SetSuppressedEventListener(EventListener* aListener);
2716 EventListener* GetSuppressedEventListener() {
2717 return mSuppressedEventListener;
2721 * Return true when this document is active, i.e., an active document
2722 * in a content viewer and not in the bfcache.
2723 * This does NOT match the "active document" concept in the WHATWG spec -
2724 * see IsCurrentActiveDocument.
2726 bool IsActive() const;
2729 * Return true if this is the current active document for its
2730 * docshell. Note that a docshell may have multiple active documents
2731 * due to the bfcache -- this should be used when you need to
2732 * differentiate the *current* active document from any active
2733 * documents.
2735 bool IsCurrentActiveDocument() const {
2736 nsPIDOMWindowInner* inner = GetInnerWindow();
2737 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2741 * Returns whether this document should perform image loads.
2743 bool ShouldLoadImages() const {
2744 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2745 // images can themselves have data: URL image references.
2746 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2747 IsStaticDocument();
2750 void SetHasPrintCallbacks() {
2751 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2752 mHasPrintCallbacks = true;
2755 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2758 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2759 * the document's activity changes such as OnPageHide, visibility, activity.
2760 * The ActivityObserver objects can be nsIObjectLoadingContent or
2761 * nsIDocumentActivity or HTMLMEdiaElement.
2763 void RegisterActivityObserver(nsISupports* aSupports);
2764 bool UnregisterActivityObserver(nsISupports* aSupports);
2765 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2766 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2767 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2769 void NotifyActivityChanged();
2771 // Indicates whether mAnimationController has been (lazily) initialized.
2772 // If this returns true, we're promising that GetAnimationController()
2773 // will have a non-null return value.
2774 bool HasAnimationController() { return !!mAnimationController; }
2776 // Getter for this document's SMIL Animation Controller. Performs lazy
2777 // initialization, if this document supports animation and if
2778 // mAnimationController isn't yet initialized.
2780 // If HasAnimationController is true, this is guaranteed to return non-null.
2781 SMILAnimationController* GetAnimationController();
2783 // Gets the tracker for animations that are waiting to start.
2784 // Returns nullptr if there is no pending animation tracker for this document
2785 // which will be the case if there have never been any CSS animations or
2786 // transitions on elements in the document.
2787 PendingAnimationTracker* GetPendingAnimationTracker() {
2788 return mPendingAnimationTracker;
2791 // Gets the tracker for animations that are waiting to start and
2792 // creates it if it doesn't already exist. As a result, the return value
2793 // will never be nullptr.
2794 PendingAnimationTracker* GetOrCreatePendingAnimationTracker();
2796 // Gets the tracker for scroll-driven animations that are waiting to start.
2797 // Returns nullptr if there is no scroll-driven animation tracker for this
2798 // document which will be the case if there have never been any scroll-driven
2799 // animations in the document.
2800 ScrollTimelineAnimationTracker* GetScrollTimelineAnimationTracker() {
2801 return mScrollTimelineAnimationTracker;
2804 // Gets the tracker for scroll-driven animations that are waiting to start and
2805 // creates it if it doesn't already exist. As a result, the return value
2806 // will never be nullptr.
2807 ScrollTimelineAnimationTracker* GetOrCreateScrollTimelineAnimationTracker();
2810 * Prevents user initiated events from being dispatched to the document and
2811 * subdocuments.
2813 void SuppressEventHandling(uint32_t aIncrease = 1);
2816 * Unsuppress event handling.
2817 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2818 * asynchronously.
2820 MOZ_CAN_RUN_SCRIPT_BOUNDARY void UnsuppressEventHandlingAndFireEvents(
2821 bool aFireEvents);
2823 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2825 bool IsEventHandlingEnabled() const {
2826 return !EventHandlingSuppressed() && mScriptGlobalObject;
2829 bool WouldScheduleFrameRequestCallbacks() const {
2830 // If this function changes to depend on some other variable, make sure to
2831 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2832 // where that variable can change.
2833 return mPresShell && IsEventHandlingEnabled();
2836 void DecreaseEventSuppression() {
2837 MOZ_ASSERT(mEventsSuppressed);
2838 --mEventsSuppressed;
2839 UpdateFrameRequestCallbackSchedulingState();
2843 * Some clipboard commands are unconditionally enabled on some documents, so
2844 * as to always dispatch copy / paste events even though you'd normally not be
2845 * able to copy.
2847 bool AreClipboardCommandsUnconditionallyEnabled() const;
2850 * Note a ChannelEventQueue which has been suspended on the document's behalf
2851 * to prevent XHRs from running content scripts while event handling is
2852 * suppressed. The document is responsible for resuming the queue after
2853 * event handling is unsuppressed.
2855 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2858 * Returns true if a postMessage event should be suspended instead of running.
2859 * The document is responsible for running the event later, in the order they
2860 * were received.
2862 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2865 * Run any suspended postMessage events, or clear them.
2867 void FireOrClearPostMessageEvents(bool aFireEvents);
2869 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2872 * Flag whether we're about to fire the window's load event for this document.
2874 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2877 * Test whether we should be firing a load event for this document after a
2878 * document.close(). This is public and on Document, instead of being private
2879 * to Document, because we need to go through the normal docloader logic
2880 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2881 * semantics of firing the load event; we just don't want to fire the load
2882 * event if this tests true. So we need the docloader to be able to access
2883 * this state.
2885 * This method should only be called at the point when the load event is about
2886 * to be fired. It resets the "skip" flag, so it is not idempotent.
2888 bool SkipLoadEventAfterClose() {
2889 bool skip = mSkipLoadEventAfterClose;
2890 mSkipLoadEventAfterClose = false;
2891 return skip;
2895 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2897 void IncrementIgnoreDestructiveWritesCounter() {
2898 ++mIgnoreDestructiveWritesCounter;
2902 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2904 void DecrementIgnoreDestructiveWritesCounter() {
2905 --mIgnoreDestructiveWritesCounter;
2908 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2911 * Returns true if this document is allowed to contain XUL element and
2912 * use non-builtin XBL bindings.
2914 bool AllowXULXBL() {
2915 return mAllowXULXBL == eTriTrue ? true
2916 : mAllowXULXBL == eTriFalse ? false
2917 : InternalAllowXULXBL();
2921 * Returns true if this document is allowed to load DTDs from UI resources
2922 * no matter what.
2924 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2926 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2928 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2931 * Returns the template content owner document that owns the content of
2932 * HTMLTemplateElement.
2934 Document* GetTemplateContentsOwner();
2936 Document* GetTemplateContentsOwnerIfExists() const {
2937 return mTemplateContentsOwner.get();
2940 bool IsTemplateContentsOwner() const {
2941 // Template contents owner documents are the template contents owner of
2942 // themselves.
2943 return mTemplateContentsOwner == this;
2947 * Returns true if this document is a static clone of a normal document.
2949 * We create static clones for print preview and printing (possibly other
2950 * things in future).
2952 * Note that static documents are also "loaded as data" (if this method
2953 * returns true, IsLoadedAsData() will also return true).
2955 bool IsStaticDocument() const { return mIsStaticDocument; }
2958 * Clones the document along with any subdocuments, stylesheet, etc.
2960 * The resulting document and everything it contains (including any
2961 * sub-documents) are created purely via cloning. The returned documents and
2962 * any sub-documents are "loaded as data" documents to preserve the state as
2963 * it was during the clone process (we don't want external resources to load
2964 * and replace the cloned resources).
2966 * @param aCloneContainer The container for the clone document.
2967 * @param aContentViewer The viewer for the clone document. Must be the viewer
2968 * of aCloneContainer, but callers must have a reference
2969 * to it already and ensure it's not null.
2970 * @param aPrintSettings The print settings for this clone.
2971 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2973 already_AddRefed<Document> CreateStaticClone(
2974 nsIDocShell* aCloneContainer, nsIContentViewer* aContentViewer,
2975 nsIPrintSettings* aPrintSettings, bool* aOutHasInProcessPrintCallbacks);
2978 * If this document is a static clone, this returns the original
2979 * document.
2981 Document* GetOriginalDocument() const {
2982 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2983 return mOriginalDocument;
2987 * If this document is a static clone, let the original document know that
2988 * we're going away and then release our reference to it.
2990 void UnlinkOriginalDocumentIfStatic();
2993 * These are called by the parser as it encounters <picture> tags, the end of
2994 * said tags, and possible picture <source srcset> sources respectively. These
2995 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2996 * expected to be marked void.
2998 * NOTE that the parser does not attempt to track the current picture nesting
2999 * level or whether the given <source> tag is within a picture -- it is only
3000 * guaranteed to order these calls properly with respect to
3001 * ResolvePreLoadImage.
3004 void PreloadPictureOpened() { mPreloadPictureDepth++; }
3006 void PreloadPictureClosed();
3008 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
3009 const nsAString& aSizesAttr,
3010 const nsAString& aTypeAttr,
3011 const nsAString& aMediaAttr);
3014 * Called by the parser to resolve an image for preloading. The parser will
3015 * call the PreloadPicture* functions to inform us of possible <picture>
3016 * nesting and possible sources, which are used to inform URL selection
3017 * responsive <picture> or <img srcset> images. Unset attributes are expected
3018 * to be marked void.
3019 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
3020 * true, false otherwise.
3022 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
3023 const nsAString& aSrcAttr,
3024 const nsAString& aSrcsetAttr,
3025 const nsAString& aSizesAttr,
3026 bool* aIsImgSet);
3028 * Called by nsParser to preload images. Can be removed and code moved
3029 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
3030 * parser-module is linked with gklayout-module. aCrossOriginAttr should
3031 * be a void string if the attr is not present.
3032 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
3033 * when this image is for loading <picture> or <img srcset> images.
3035 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
3036 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
3037 bool aLinkPreload, const TimeStamp& aInitTimestamp);
3038 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
3039 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
3040 bool aLinkPreload, uint64_t aEarlyHintPreloaderId);
3043 * Called by images to forget an image preload when they start doing
3044 * the real load.
3046 void ForgetImagePreload(nsIURI* aURI);
3049 * Called by the parser or the preload service to preload style sheets.
3050 * aCrossOriginAttr should be a void string if the attr is not present.
3052 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
3053 const nsAString& aCrossOriginAttr,
3054 ReferrerPolicyEnum aReferrerPolicy,
3055 const nsAString& aIntegrity,
3056 css::StylePreloadKind,
3057 uint64_t aEarlyHintPreloaderId);
3060 * Called by the chrome registry to load style sheets.
3062 * This always does a synchronous load, and parses as a normal document sheet.
3064 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
3067 * Returns true if the locale used for the document specifies a direction of
3068 * right to left. For chrome documents, this comes from the chrome registry.
3069 * This is used to determine the current state for the :-moz-locale-dir
3070 * pseudoclass so once can know whether a document is expected to be rendered
3071 * left-to-right or right-to-left.
3073 bool IsDocumentRightToLeft();
3076 * Called by Parser for link rel=preconnect
3078 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
3081 * Set the document's pending state object (as serialized using structured
3082 * clone).
3084 void SetStateObject(nsIStructuredCloneContainer* scContainer);
3087 * Set the document's pending state object to the same state object as
3088 * aDocument.
3090 void SetStateObjectFrom(Document* aDocument) {
3091 SetStateObject(aDocument->mStateObjectContainer);
3095 * Returns true if there is a lightweight theme specified. This is used to
3096 * determine the state of the :-moz-lwtheme pseudo-class.
3098 bool ComputeDocumentLWTheme() const;
3099 void ResetDocumentLWTheme() {
3100 UpdateDocumentStates(DocumentState::LWTHEME, true);
3103 // Whether we're a media document or not.
3104 enum class MediaDocumentKind {
3105 NotMedia,
3106 Video,
3107 Image,
3108 Plugin,
3111 virtual enum MediaDocumentKind MediaDocumentKind() const {
3112 return MediaDocumentKind::NotMedia;
3115 DocumentState GetDocumentState() const { return mDocumentState; }
3117 nsISupports* GetCurrentContentSink();
3119 void ElementWithAutoFocusInserted(Element* aAutoFocusCandidate);
3120 MOZ_CAN_RUN_SCRIPT void FlushAutoFocusCandidates();
3121 void ScheduleFlushAutoFocusCandidates();
3122 bool HasAutoFocusCandidates() const {
3123 return !mAutoFocusCandidates.IsEmpty();
3126 void SetAutoFocusFired();
3128 void SetScrollToRef(nsIURI* aDocumentURI);
3129 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3130 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3132 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3133 mChangeScrollPosWhenScrollingToRef = aValue;
3136 using DocumentOrShadowRoot::GetElementById;
3137 using DocumentOrShadowRoot::GetElementsByClassName;
3138 using DocumentOrShadowRoot::GetElementsByTagName;
3139 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3141 DocumentTimeline* Timeline();
3142 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3144 SVGSVGElement* GetSVGRootElement() const;
3146 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3147 int32_t* aHandle);
3148 void CancelFrameRequestCallback(int32_t aHandle);
3151 * Returns true if the handle refers to a callback that was canceled that
3152 * we did not find in our list of callbacks (e.g. because it is one of those
3153 * in the set of callbacks currently queued to be run).
3155 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3158 * Put this document's frame request callbacks into the provided
3159 * list, and forget about them.
3161 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3164 * @return true if this document's frame request callbacks should be
3165 * throttled. We throttle requestAnimationFrame for documents which aren't
3166 * visible (e.g. scrolled out of the viewport).
3168 bool ShouldThrottleFrameRequests() const;
3170 // This returns true when the document tree is being teared down.
3171 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3173 dom::ImageTracker* ImageTracker();
3175 // Adds an element to mResponsiveContent when the element is
3176 // added to the tree.
3177 void AddResponsiveContent(HTMLImageElement* aContent) {
3178 MOZ_ASSERT(aContent);
3179 mResponsiveContent.Insert(aContent);
3182 // Removes an element from mResponsiveContent when the element is
3183 // removed from the tree.
3184 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3185 MOZ_ASSERT(aContent);
3186 mResponsiveContent.Remove(aContent);
3189 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3190 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3191 mSVGUseElementsNeedingShadowTreeUpdate.Remove(&aElement);
3194 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3195 return mSVGUseElementsNeedingShadowTreeUpdate.Contains(&aElement);
3198 using ShadowRootSet = nsTHashSet<ShadowRoot*>;
3200 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3201 mComposedShadowRoots.Insert(&aShadowRoot);
3204 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3205 mComposedShadowRoots.Remove(&aShadowRoot);
3208 // If you're considering using this, you probably want to use
3209 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3210 // sanity-checking.
3211 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3212 return mComposedShadowRoots.Contains(&aShadowRoot);
3215 const ShadowRootSet& ComposedShadowRoots() const {
3216 return mComposedShadowRoots;
3219 // WebIDL method for chrome code.
3220 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3222 // Notifies any responsive content added by AddResponsiveContent upon media
3223 // features values changing.
3224 void NotifyMediaFeatureValuesChanged();
3226 nsresult GetStateObject(JS::MutableHandle<JS::Value> aState);
3228 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3230 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3232 nsContentList* ImageMapList();
3234 // Add aLink to the set of links that need their status resolved.
3235 void RegisterPendingLinkUpdate(Link* aLink);
3237 // Update state on links in mLinksToUpdate.
3238 void FlushPendingLinkUpdates();
3240 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3241 void WarnOnceAbout(
3242 DeprecatedOperations aOperation, bool asError = false,
3243 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3245 #define DOCUMENT_WARNING(_op) e##_op,
3246 enum DocumentWarnings {
3247 #include "nsDocumentWarningList.h"
3248 eDocumentWarningCount
3250 #undef DOCUMENT_WARNING
3251 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3252 void WarnOnceAbout(
3253 DocumentWarnings aWarning, bool asError = false,
3254 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3256 // This method may fire a DOM event; if it does so it will happen
3257 // synchronously.
3259 // Whether the event fires is controlled by the argument.
3260 enum class DispatchVisibilityChange { No, Yes };
3261 void UpdateVisibilityState(
3262 DispatchVisibilityChange = DispatchVisibilityChange::Yes);
3264 // Posts an event to call UpdateVisibilityState.
3265 void PostVisibilityUpdateEvent();
3267 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3269 // Adds the size of a given node, which must not be a document node, to the
3270 // window sizes passed-in.
3271 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3273 // Note: Document is a sub-class of nsINode, which has a
3274 // SizeOfExcludingThis function. However, because Document objects can
3275 // only appear at the top of the DOM tree, we have a specialized measurement
3276 // function which returns multiple sizes.
3277 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3278 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3279 // because Document inherits from nsINode; see the comment above the
3280 // declaration of nsINode::SizeOfIncludingThis.
3281 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3283 void ConstructUbiNode(void* storage) override;
3285 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3287 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3289 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3291 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3293 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3295 void SetIsInSyncOperation(bool aSync);
3297 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3300 * Creates a new element in the HTML namespace with a local name given by
3301 * aTag.
3303 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3305 // WebIDL API
3306 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3307 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3308 ErrorResult& rv);
3309 DOMImplementation* GetImplementation(ErrorResult& rv);
3310 [[nodiscard]] nsresult GetURL(nsString& retval) const;
3311 [[nodiscard]] nsresult GetDocumentURI(nsString& retval) const;
3312 // Return the URI for the document.
3313 // The returned value may differ if the document is loaded via XHR, and
3314 // when accessed from chrome privileged script and
3315 // from content privileged script for compatibility.
3316 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3317 ErrorResult& aRv) const;
3318 void GetCompatMode(nsString& retval) const;
3319 void GetCharacterSet(nsAString& retval) const;
3320 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3321 // GetDoctype defined above
3322 Element* GetDocumentElement() const { return GetRootElement(); }
3324 WindowContext* GetTopLevelWindowContext() const;
3326 // If the top-level ancestor content document for this document is in the same
3327 // process, returns it. Otherwise, returns null. This function is not
3328 // Fission-compatible, and should not be used in new code.
3329 Document* GetTopLevelContentDocumentIfSameProcess();
3330 const Document* GetTopLevelContentDocumentIfSameProcess() const;
3332 // Returns the associated app window if this is a top-level chrome document,
3333 // null otherwise.
3334 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3336 already_AddRefed<Element> CreateElement(
3337 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3338 ErrorResult& rv);
3339 already_AddRefed<Element> CreateElementNS(
3340 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3341 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3342 already_AddRefed<Element> CreateXULElement(
3343 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3344 ErrorResult& aRv);
3345 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3346 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3347 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3348 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3349 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3350 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3351 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3352 ErrorResult& rv) const;
3353 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3354 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* AdoptNode(nsINode& aNode,
3355 ErrorResult& rv);
3356 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3357 CallerType aCallerType,
3358 ErrorResult& rv) const;
3359 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3360 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3361 uint32_t aWhatToShow,
3362 NodeFilter* aFilter,
3363 ErrorResult& rv) const;
3364 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3365 uint32_t aWhatToShow,
3366 NodeFilter* aFilter,
3367 ErrorResult& rv) const;
3368 // Deprecated WebIDL bits
3369 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3370 ErrorResult& rv);
3371 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3372 ErrorResult& rv);
3373 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3374 const nsAString& aQualifiedName,
3375 ErrorResult& rv);
3376 void GetInputEncoding(nsAString& aInputEncoding) const;
3377 already_AddRefed<Location> GetLocation() const;
3378 void GetDomain(nsAString& aDomain);
3379 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3380 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3381 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3382 void GetReferrer(nsAString& aReferrer) const;
3383 void GetLastModified(nsAString& aLastModified) const;
3384 void GetReadyState(nsAString& aReadyState) const;
3386 void GetTitle(nsAString& aTitle);
3387 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3388 void GetDir(nsAString& aDirection) const;
3389 void SetDir(const nsAString& aDirection);
3390 nsIHTMLCollection* Images();
3391 nsIHTMLCollection* Embeds();
3392 nsIHTMLCollection* Plugins() { return Embeds(); }
3393 nsIHTMLCollection* Links();
3394 nsIHTMLCollection* Forms();
3395 nsIHTMLCollection* Scripts();
3396 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3397 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3398 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3400 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3401 const mozilla::dom::Optional<nsAString>& /* unused */,
3402 mozilla::ErrorResult& aError);
3403 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3404 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3405 mozilla::ErrorResult& rv);
3406 void Close(mozilla::ErrorResult& rv);
3407 void Write(const mozilla::dom::Sequence<nsString>& aText,
3408 mozilla::ErrorResult& rv);
3409 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3410 mozilla::ErrorResult& rv);
3411 Nullable<WindowProxyHolder> GetDefaultView() const;
3412 Element* GetActiveElement();
3413 enum class IncludeChromeOnly : bool { No, Yes };
3414 // TODO(emilio): Audit callers and remove the default argument, some seem like
3415 // they could want the IncludeChromeOnly::Yes version.
3416 nsIContent* GetUnretargetedFocusedContent(
3417 IncludeChromeOnly = IncludeChromeOnly::No) const;
3419 * Return true if this document or a subdocument has focus.
3421 bool HasFocus(ErrorResult& rv) const;
3424 * Return true if this document itself has focus.
3426 bool ThisDocumentHasFocus() const;
3428 void GetDesignMode(nsAString& aDesignMode);
3429 void SetDesignMode(const nsAString& aDesignMode,
3430 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3431 void SetDesignMode(const nsAString& aDesignMode,
3432 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3433 mozilla::ErrorResult& rv);
3434 MOZ_CAN_RUN_SCRIPT
3435 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3436 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3437 mozilla::ErrorResult& aRv);
3438 MOZ_CAN_RUN_SCRIPT bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3439 nsIPrincipal& aSubjectPrincipal,
3440 mozilla::ErrorResult& aRv);
3441 MOZ_CAN_RUN_SCRIPT bool QueryCommandIndeterm(
3442 const nsAString& aHTMLCommandName, mozilla::ErrorResult& aRv);
3443 MOZ_CAN_RUN_SCRIPT bool QueryCommandState(const nsAString& aHTMLCommandName,
3444 mozilla::ErrorResult& aRv);
3445 MOZ_CAN_RUN_SCRIPT bool QueryCommandSupported(
3446 const nsAString& aHTMLCommandName, mozilla::dom::CallerType aCallerType,
3447 mozilla::ErrorResult& aRv);
3448 MOZ_CAN_RUN_SCRIPT void QueryCommandValue(const nsAString& aHTMLCommandName,
3449 nsAString& aValue,
3450 mozilla::ErrorResult& aRv);
3451 nsIHTMLCollection* Applets();
3452 nsIHTMLCollection* Anchors();
3453 TimeStamp LastFocusTime() const;
3454 void SetLastFocusTime(const TimeStamp& aFocusTime);
3455 // Event handlers are all on nsINode already
3456 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3457 Element* GetCurrentScript();
3458 void ReleaseCapture() const;
3459 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3460 nsIURI* GetDocumentURIObject() const;
3461 // Not const because all the fullscreen goop is not const
3462 const char* GetFullscreenError(CallerType);
3463 bool FullscreenEnabled(CallerType aCallerType) {
3464 return !GetFullscreenError(aCallerType);
3467 void GetWireframeWithoutFlushing(bool aIncludeNodes, Nullable<Wireframe>&);
3469 MOZ_CAN_RUN_SCRIPT void GetWireframe(bool aIncludeNodes,
3470 Nullable<Wireframe>&);
3472 // Hides all popovers until the given end point, see
3473 // https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
3474 MOZ_CAN_RUN_SCRIPT void HideAllPopoversUntil(nsINode& aEndpoint,
3475 bool aFocusPreviousElement,
3476 bool aFireEvents);
3478 MOZ_CAN_RUN_SCRIPT_BOUNDARY void HideAllPopoversWithoutRunningScript();
3479 // Hides the given popover element, see
3480 // https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
3481 MOZ_CAN_RUN_SCRIPT void HidePopover(Element& popover,
3482 bool aFocusPreviousElement,
3483 bool aFireEvents, ErrorResult& aRv);
3485 // Returns a list of all the elements in the Document's top layer whose
3486 // popover attribute is in the auto state.
3487 // See https://html.spec.whatwg.org/multipage/popover.html#auto-popover-list
3488 nsTArray<Element*> AutoPopoverList() const;
3490 // Return document's auto popover list's last element.
3491 // See
3492 // https://html.spec.whatwg.org/multipage/popover.html#topmost-auto-popover
3493 Element* GetTopmostAutoPopover() const;
3495 // Adds/removes an element to/from the auto popover list.
3496 void AddToAutoPopoverList(Element&);
3497 void RemoveFromAutoPopoverList(Element&);
3499 void AddPopoverToTopLayer(Element&);
3500 void RemovePopoverFromTopLayer(Element&);
3502 Element* GetTopLayerTop();
3503 // Return the fullscreen element in the top layer
3504 Element* GetUnretargetedFullscreenElement() const;
3505 bool Fullscreen() const { return !!GetUnretargetedFullscreenElement(); }
3506 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3507 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3508 void GetFgColor(nsAString& aFgColor);
3509 void SetFgColor(const nsAString& aFgColor);
3510 void GetLinkColor(nsAString& aLinkColor);
3511 void SetLinkColor(const nsAString& aLinkColor);
3512 void GetVlinkColor(nsAString& aAvlinkColor);
3513 void SetVlinkColor(const nsAString& aVlinkColor);
3514 void GetAlinkColor(nsAString& aAlinkColor);
3515 void SetAlinkColor(const nsAString& aAlinkColor);
3516 void GetBgColor(nsAString& aBgColor);
3517 void SetBgColor(const nsAString& aBgColor);
3518 void Clear() const {
3519 // Deprecated
3521 void CaptureEvents();
3522 void ReleaseEvents();
3524 mozilla::dom::HTMLAllCollection* All();
3526 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3527 static bool IsWebAnimationsEnabled(JSContext* aCx, JSObject* aObject);
3528 static bool IsWebAnimationsEnabled(CallerType aCallerType);
3529 static bool IsWebAnimationsGetAnimationsEnabled(JSContext* aCx,
3530 JSObject* aObject);
3531 static bool AreWebAnimationsImplicitKeyframesEnabled(JSContext* aCx,
3532 JSObject* aObject);
3533 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3534 JSObject* aObject);
3535 // Checks that the caller is either chrome or some addon.
3536 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3538 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3539 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3541 private:
3542 int32_t mPictureInPictureChildElementCount = 0;
3544 public:
3545 void EnableChildElementInPictureInPictureMode();
3546 void DisableChildElementInPictureInPictureMode();
3548 // True if any child element is being used in picture in picture mode.
3549 bool HasPictureInPictureChildElement() const;
3551 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3552 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3553 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3554 aSheetSet = mLastStyleSheetSet;
3556 const nsString& GetCurrentStyleSheetSet() const {
3557 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3558 : mLastStyleSheetSet;
3560 void SetPreferredStyleSheetSet(const nsAString&);
3561 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3562 aSheetSet = mPreferredStyleSheetSet;
3564 DOMStringList* StyleSheetSets();
3565 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3568 * Retrieve the location of the caret position (DOM node and character
3569 * offset within that node), given a point.
3571 * @param aX Horizontal point at which to determine the caret position, in
3572 * page coordinates.
3573 * @param aY Vertical point at which to determine the caret position, in
3574 * page coordinates.
3576 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3577 float aY);
3579 Element* GetScrollingElement();
3580 // A way to check whether a given element is what would get returned from
3581 // GetScrollingElement. It can be faster than comparing to the return value
3582 // of GetScrollingElement() due to being able to avoid flushes in various
3583 // cases. This method assumes that null is NOT passed.
3584 bool IsScrollingElement(Element* aElement);
3586 // QuerySelector and QuerySelectorAll already defined on nsINode
3588 XPathExpression* CreateExpression(const nsAString& aExpression,
3589 XPathNSResolver* aResolver,
3590 ErrorResult& rv);
3591 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3592 already_AddRefed<XPathResult> Evaluate(
3593 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3594 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3595 ErrorResult& rv);
3596 // Touch event handlers already on nsINode
3597 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3598 EventTarget* aTarget, int32_t aIdentifier,
3599 int32_t aPageX, int32_t aPageY,
3600 int32_t aScreenX, int32_t aScreenY,
3601 int32_t aClientX, int32_t aClientY,
3602 int32_t aRadiusX, int32_t aRadiusY,
3603 float aRotationAngle, float aForce);
3604 already_AddRefed<TouchList> CreateTouchList();
3605 already_AddRefed<TouchList> CreateTouchList(
3606 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3607 already_AddRefed<TouchList> CreateTouchList(
3608 const Sequence<OwningNonNull<Touch>>& aTouches);
3610 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3611 mStyleSheetChangeEventsEnabled = aValue;
3614 bool StyleSheetChangeEventsEnabled() const {
3615 return mStyleSheetChangeEventsEnabled;
3618 void SetDevToolsAnonymousAndShadowEventsEnabled(bool aValue) {
3619 mDevToolsAnonymousAndShadowEventsEnabled = aValue;
3621 bool DevToolsAnonymousAndShadowEventsEnabled() const {
3622 return mDevToolsAnonymousAndShadowEventsEnabled;
3625 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3626 const BlockParsingOptions& aOptions,
3627 ErrorResult& aRv);
3629 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3631 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3633 void BlockUnblockOnloadForSystemOrPDFJS(bool aBlock) {
3634 if (aBlock) {
3635 BlockOnload();
3636 } else {
3637 UnblockOnload(/* aFireSync = */ false);
3641 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3642 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3643 void InitializeXULBroadcastManager();
3644 XULBroadcastManager* GetXULBroadcastManager() const {
3645 return mXULBroadcastManager;
3647 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3648 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3650 bool DevToolsWatchingDOMMutations() const {
3651 return mDevToolsWatchingDOMMutations;
3653 void SetDevToolsWatchingDOMMutations(bool aValue);
3655 void MaybeWarnAboutZoom();
3657 // ParentNode
3658 nsIHTMLCollection* Children();
3659 uint32_t ChildElementCount();
3662 * Asserts IsHTMLOrXHTML, and can't return null.
3663 * Defined inline in nsHTMLDocument.h
3665 inline nsHTMLDocument* AsHTMLDocument();
3666 inline const nsHTMLDocument* AsHTMLDocument() const;
3669 * Asserts IsSVGDocument, and can't return null.
3670 * Defined inline in SVGDocument.h
3672 inline SVGDocument* AsSVGDocument();
3673 inline const SVGDocument* AsSVGDocument() const;
3676 * Asserts IsImageDocument, and can't return null.
3677 * Defined inline in ImageDocument.h
3679 inline ImageDocument* AsImageDocument();
3680 inline const ImageDocument* AsImageDocument() const;
3683 * Given a node, get a weak reference to it and append that reference to
3684 * mBlockedNodesByClassifier. Can be used later on to look up a node in it.
3685 * (e.g., by the UI)
3687 void AddBlockedNodeByClassifier(nsINode* node) {
3688 if (!node) {
3689 return;
3692 nsWeakPtr weakNode = do_GetWeakReference(node);
3694 if (weakNode) {
3695 mBlockedNodesByClassifier.AppendElement(weakNode);
3699 gfxUserFontSet* GetUserFontSet();
3700 void FlushUserFontSet();
3701 void MarkUserFontSetDirty();
3702 FontFaceSet* GetFonts() { return mFontFaceSet; }
3704 // FontFaceSource
3705 FontFaceSet* GetFonts(ErrorResult&) { return Fonts(); }
3706 FontFaceSet* Fonts();
3708 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3710 bool IsSynthesized();
3712 // Records whether we will track use counters for this document, and if so,
3713 // which top-level document that page counters will be accumulated to.
3715 // Informs the parent process that page use counters will be sent once the
3716 // document goes away.
3717 void InitUseCounters();
3719 // Reports document use counters via telemetry. This method only has an
3720 // effect once per document, and so is called during document destruction.
3721 void ReportDocumentUseCounters();
3723 // Report how lazyload performs for this document.
3724 void ReportDocumentLazyLoadCounters();
3726 // Sends page use counters to the parent process to accumulate against the
3727 // top-level document. Must be called while we still have access to our
3728 // WindowContext. This method has an effect each time it is called, and we
3729 // call it just before the document loses its window.
3730 void SendPageUseCounters();
3732 void SetUseCounter(UseCounter aUseCounter) {
3733 mUseCounters[aUseCounter] = true;
3736 const StyleUseCounters* GetStyleUseCounters() {
3737 return mStyleUseCounters.get();
3740 // Propagate our use counters explicitly into the specified referencing
3741 // document.
3743 // This is used for SVG image documents, which cannot be enumerated in the
3744 // referencing document's ReportUseCounters() like external resource documents
3745 // can.
3746 void PropagateImageUseCounters(Document* aReferencingDocument);
3748 // Called to track whether this document has had any interaction.
3749 // This is used to track whether we should permit "beforeunload".
3750 void SetUserHasInteracted();
3751 bool UserHasInteracted() { return mUserHasInteracted; }
3752 void ResetUserInteractionTimer();
3754 // This should be called when this document receives events which are likely
3755 // to be user interaction with the document, rather than the byproduct of
3756 // interaction with the browser (i.e. a keypress to scroll the view port,
3757 // keyboard shortcuts, etc). This is used to decide whether we should
3758 // permit autoplay audible media. This also gesture activates all other
3759 // content documents in this tab.
3760 void NotifyUserGestureActivation();
3762 // This function is used for mochitest only.
3763 void ClearUserGestureActivation();
3765 // Return true if NotifyUserGestureActivation() has been called on any
3766 // document in the document tree.
3767 bool HasBeenUserGestureActivated();
3769 // Reture timestamp of last user gesture in milliseconds relative to
3770 // navigation start timestamp.
3771 DOMHighResTimeStamp LastUserGestureTimeStamp();
3773 // Return true if there is transient user gesture activation and it hasn't yet
3774 // timed out or hasn't been consumed.
3775 bool HasValidTransientUserGestureActivation() const;
3777 // Return true if HasValidTransientUserGestureActivation() would return true,
3778 // and consume the activation.
3779 bool ConsumeTransientUserGestureActivation();
3781 BrowsingContext* GetBrowsingContext() const;
3783 // This document is a WebExtension page, it might be a background page, a
3784 // popup, a visible tab, a visible iframe ...e.t.c.
3785 bool IsExtensionPage() const;
3787 bool HasScriptsBlockedBySandbox() const;
3789 void ReportHasScrollLinkedEffect(const TimeStamp& aTimeStamp);
3790 bool HasScrollLinkedEffect() const;
3792 #ifdef DEBUG
3793 void AssertDocGroupMatchesKey() const;
3794 #endif
3796 DocGroup* GetDocGroup() const {
3797 #ifdef DEBUG
3798 AssertDocGroupMatchesKey();
3799 #endif
3800 return mDocGroup;
3803 DocGroup* GetDocGroupOrCreate();
3806 * If we're a sub-document, the parent document's layout can affect our style
3807 * and layout (due to the viewport size, viewport units, media queries...).
3809 * This function returns true if our parent document and our child document
3810 * can observe each other. If they cannot, then we don't need to synchronously
3811 * update the parent document layout every time the child document may need
3812 * up-to-date layout information.
3814 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3815 return GetInProcessParentDocument() &&
3816 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3819 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3820 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3821 "Intersection observer already in the list");
3822 mIntersectionObservers.Insert(aObserver);
3825 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3826 mIntersectionObservers.Remove(aObserver);
3829 bool HasIntersectionObservers() const {
3830 return !mIntersectionObservers.IsEmpty();
3833 void UpdateIntersectionObservations(TimeStamp aNowTime);
3834 void ScheduleIntersectionObserverNotification();
3835 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3837 DOMIntersectionObserver* GetLazyLoadImageObserver() {
3838 return mLazyLoadImageObserver;
3840 DOMIntersectionObserver* GetLazyLoadImageObserverViewport() {
3841 return mLazyLoadImageObserverViewport;
3843 DOMIntersectionObserver& EnsureLazyLoadImageObserver();
3845 DOMIntersectionObserver* GetContentVisibilityObserver() const {
3846 return mContentVisibilityObserver;
3848 DOMIntersectionObserver& EnsureContentVisibilityObserver();
3849 void ObserveForContentVisibility(Element&);
3850 void UnobserveForContentVisibility(Element&);
3852 ResizeObserver* GetLastRememberedSizeObserver() {
3853 return mLastRememberedSizeObserver;
3855 ResizeObserver& EnsureLastRememberedSizeObserver();
3856 void ObserveForLastRememberedSize(Element&);
3857 void UnobserveForLastRememberedSize(Element&);
3859 // Dispatch a runnable related to the document.
3860 nsresult Dispatch(TaskCategory aCategory,
3861 already_AddRefed<nsIRunnable>&& aRunnable) final;
3863 nsISerialEventTarget* EventTargetFor(TaskCategory) const override;
3865 AbstractThread* AbstractMainThreadFor(TaskCategory) override;
3867 // The URLs passed to this function should match what
3868 // JS::DescribeScriptedCaller() returns, since this API is used to
3869 // determine whether some code is being called from a tracking script.
3870 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3871 // The JSContext passed to this method represents the context that we want to
3872 // determine if it belongs to a tracker.
3873 bool IsScriptTracking(JSContext* aCx) const;
3875 // ResizeObserver usage.
3876 void AddResizeObserver(ResizeObserver&);
3877 void RemoveResizeObserver(ResizeObserver&);
3878 void ScheduleResizeObserversNotification() const;
3880 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3881 PermissionDelegateHandler* GetPermissionDelegateHandler();
3883 // Notify the document that a fetch or a XHR request has completed
3884 // succesfully in this document. This is used by the password manager to infer
3885 // whether a form is submitted.
3886 void NotifyFetchOrXHRSuccess();
3888 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3889 void SetNotifyFetchSuccess(bool aShouldNotify);
3891 // When this is set, removing a form or a password field from DOM
3892 // sends a Chrome-only event. This is now only used by the password manager.
3893 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify);
3895 // This function is used by HTMLFormElement and HTMLInputElement to determin
3896 // whether to send an event when it is removed from DOM.
3897 bool ShouldNotifyFormOrPasswordRemoved() const {
3898 return mShouldNotifyFormOrPasswordRemoved;
3901 HTMLEditor* GetHTMLEditor() const;
3904 * Localization
3906 * For more information on DocumentL10n see
3907 * intl/l10n/docs/fluent/tutorial.rst
3910 public:
3912 * This is a public method exposed on Document WebIDL
3913 * to chrome only documents.
3915 DocumentL10n* GetL10n() const { return mDocumentL10n.get(); }
3918 * Whether there's any async l10n mutation work pending.
3920 * When this turns false, we fire the L10nMutationsFinished event.
3922 bool HasPendingL10nMutations() const;
3925 * This method should be called when the container
3926 * of l10n resources parsing is completed.
3928 * It triggers initial async fetch of the resources
3929 * as early as possible.
3931 * In HTML case this is </head>.
3932 * In XUL case this is </linkset>.
3934 void OnL10nResourceContainerParsed();
3937 * This method should be called when a link element
3938 * with rel="localization" is being added to the
3939 * l10n resource container element.
3941 void LocalizationLinkAdded(Element* aLinkElement);
3944 * This method should be called when a link element
3945 * with rel="localization" is being removed.
3947 void LocalizationLinkRemoved(Element* aLinkElement);
3950 * This method should be called as soon as the
3951 * parsing of the document is completed.
3953 * In HTML/XHTML this happens when we finish parsing
3954 * the document element.
3955 * In XUL it happens at `DoneWalking`, during
3956 * `MozBeforeInitialXULLayout`.
3958 void OnParsingCompleted();
3961 * This method is called when the initial translation
3962 * of the document is completed.
3964 * It unblocks the load event if translation was blocking it.
3966 * If the `aL10nCached` is set to `true`, and the document has
3967 * a prototype, it will set the `isL10nCached` flag on it.
3969 void InitialTranslationCompleted(bool aL10nCached);
3972 * Returns whether the document allows localization.
3974 bool AllowsL10n() const;
3976 protected:
3977 RefPtr<DocumentL10n> mDocumentL10n;
3980 * Return true when you want a document without explicitly specified viewport
3981 * dimensions/scale to be treated as if "width=device-width" had in fact been
3982 * specified.
3984 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3986 private:
3987 bool IsErrorPage() const;
3989 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3990 // mUseCounters.
3991 void SetCssUseCounterBits();
3993 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3994 const nsAString& aHeightString,
3995 bool aIsAutoScale);
3997 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3998 // represents the scale property and returns the scale value if it's valid.
3999 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
4001 // Parse scale values in |aViewportMetaData| and set the values in
4002 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
4003 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
4005 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
4006 // stored in parent iframe or container's browsingContext (cross process)
4007 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
4009 public:
4010 const OriginTrials& Trials() const { return mTrials; }
4012 private:
4013 void DoCacheAllKnownLangPrefs();
4014 void RecomputeLanguageFromCharset();
4015 bool GetSHEntryHasUserInteraction();
4017 void AppendAutoFocusCandidateToTopDocument(Element* aAutoFocusCandidate);
4019 public:
4020 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
4022 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
4024 void SetSHEntryHasUserInteraction(bool aHasInteraction);
4026 already_AddRefed<nsAtom> GetContentLanguageAsAtomForStyle() const;
4027 already_AddRefed<nsAtom> GetLanguageForStyle() const;
4030 * Fetch the user's font preferences for the given aLanguage's
4031 * language group.
4033 const LangGroupFontPrefs* GetFontPrefsForLang(
4034 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
4036 void ForceCacheLang(nsAtom* aLanguage) {
4037 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
4038 return;
4040 GetFontPrefsForLang(aLanguage);
4043 void CacheAllKnownLangPrefs() {
4044 if (!mMayNeedFontPrefsUpdate) {
4045 return;
4047 DoCacheAllKnownLangPrefs();
4050 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
4052 uint32_t GetServoRestyleRootDirtyBits() const {
4053 MOZ_ASSERT(mServoRestyleRoot);
4054 MOZ_ASSERT(mServoRestyleRootDirtyBits);
4055 return mServoRestyleRootDirtyBits;
4058 void ClearServoRestyleRoot() {
4059 mServoRestyleRoot = nullptr;
4060 mServoRestyleRootDirtyBits = 0;
4063 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
4064 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
4066 bool ShouldThrowOnDynamicMarkupInsertion() {
4067 return mThrowOnDynamicMarkupInsertionCounter;
4070 void IncrementThrowOnDynamicMarkupInsertionCounter() {
4071 ++mThrowOnDynamicMarkupInsertionCounter;
4074 void DecrementThrowOnDynamicMarkupInsertionCounter() {
4075 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
4076 --mThrowOnDynamicMarkupInsertionCounter;
4079 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
4081 void IncrementIgnoreOpensDuringUnloadCounter() {
4082 ++mIgnoreOpensDuringUnloadCounter;
4085 void DecrementIgnoreOpensDuringUnloadCounter() {
4086 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
4087 --mIgnoreOpensDuringUnloadCounter;
4090 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
4092 bool ModuleScriptsEnabled();
4094 bool ImportMapsEnabled();
4097 * Find the (non-anonymous) content in this document for aFrame. It will
4098 * be aFrame's content node if that content is in this document and not
4099 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
4100 * element containing the subdocument containing aFrame, and/or find the
4101 * nearest non-anonymous ancestor in this document.
4102 * Returns null if there is no such element.
4104 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
4106 void ReportShadowDOMUsage();
4108 // Sets flags for media telemetry.
4109 void SetDocTreeHadMedia();
4111 dom::XPathEvaluator* XPathEvaluator();
4113 void MaybeInitializeFinalizeFrameLoaders();
4115 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
4116 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
4119 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
4121 nsIPermissionDelegateHandler* PermDelegateHandler();
4123 // CSS prefers-color-scheme media feature for this document.
4124 enum class IgnoreRFP { No, Yes };
4125 ColorScheme PreferredColorScheme(IgnoreRFP = IgnoreRFP::No) const;
4126 // Returns the initial color-scheme used for this document based on the
4127 // color-scheme meta tag.
4128 ColorScheme DefaultColorScheme() const;
4130 static bool HasRecentlyStartedForegroundLoads();
4132 static bool AutomaticStorageAccessPermissionCanBeGranted(
4133 nsIPrincipal* aPrincipal);
4135 already_AddRefed<Promise> AddCertException(bool aIsTemporary,
4136 ErrorResult& aError);
4138 void ReloadWithHttpsOnlyException();
4140 // Subframes need to be static cloned after the main document has been
4141 // embedded within a script global. A `PendingFrameStaticClone` is a static
4142 // clone which has not yet been performed.
4144 // The getter returns a direct reference to an internal array which is
4145 // manipulated from within printing code.
4146 struct PendingFrameStaticClone {
4147 PendingFrameStaticClone() = default;
4148 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
4149 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
4150 ~PendingFrameStaticClone();
4152 RefPtr<nsFrameLoaderOwner> mElement;
4153 RefPtr<nsFrameLoader> mStaticCloneOf;
4155 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
4156 nsFrameLoader* aStaticCloneOf);
4158 bool ShouldAvoidNativeTheme() const;
4160 static bool IsValidDomain(nsIURI* aOrigHost, nsIURI* aNewURI);
4162 // Inform a parent document that a BrowserBridgeChild has been created for
4163 // an OOP sub-document.
4164 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4165 void OOPChildLoadStarted(BrowserBridgeChild* aChild);
4167 // Inform a parent document that the BrowserBridgeChild for one of its
4168 // OOP sub-documents is done calling its onload handler.
4169 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4170 void OOPChildLoadDone(BrowserBridgeChild* aChild);
4172 void ClearOOPChildrenLoading();
4174 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading.IsEmpty(); }
4176 void SetDidHitCompleteSheetCache() { mDidHitCompleteSheetCache = true; }
4178 bool DidHitCompleteSheetCache() const { return mDidHitCompleteSheetCache; }
4181 * Get the `HighlightRegistry` which contains all highlights associated
4182 * with this document.
4184 class HighlightRegistry& HighlightRegistry();
4186 bool ShouldResistFingerprinting(RFPTarget aTarget) const;
4188 // Recompute the current resist fingerprinting state. Returns true when
4189 // the state was changed.
4190 bool RecomputeResistFingerprinting();
4192 protected:
4193 // Returns the WindowContext for the document that we will contribute
4194 // page use counters to.
4195 WindowContext* GetWindowContextForPageUseCounters() const;
4197 void DoUpdateSVGUseElementShadowTrees();
4199 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
4200 nsIPrincipal* aPrincipal);
4202 void EnsureOnloadBlocker();
4204 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
4206 // Returns true if the scheme for the url for this document is "about".
4207 bool IsAboutPage() const;
4209 bool ContainsEMEContent();
4210 bool ContainsMSEContent();
4213 * Returns the title element of the document as defined by the HTML
4214 * specification, or null if there isn't one. For documents whose root
4215 * element is an <svg:svg>, this is the first <svg:title> element that's a
4216 * child of the root. For other documents, it's the first HTML title element
4217 * in the document.
4219 Element* GetTitleElement();
4221 void RecordNavigationTiming(ReadyState aReadyState);
4223 // Recomputes the visibility state but doesn't set the new value.
4224 dom::VisibilityState ComputeVisibilityState() const;
4226 // Since we wouldn't automatically play media from non-visited page, we need
4227 // to notify window when the page was first visited.
4228 void MaybeActiveMediaComponents();
4230 // Apply the fullscreen state to the document, and trigger related
4231 // events. It returns false if the fullscreen element ready check
4232 // fails and nothing gets changed.
4233 bool ApplyFullscreen(UniquePtr<FullscreenRequest>);
4235 void RemoveDocStyleSheetsFromStyleSets();
4236 void ResetStylesheetsToURI(nsIURI* aURI);
4237 void FillStyleSet();
4238 void FillStyleSetUserAndUASheets();
4239 void FillStyleSetDocumentSheets();
4240 void CompatibilityModeChanged();
4241 bool NeedsQuirksSheet() const {
4242 // SVG documents never load quirk.css.
4243 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4244 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
4246 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
4247 void RemoveContentEditableStyleSheets();
4248 void AddStyleSheetToStyleSets(StyleSheet&);
4249 void RemoveStyleSheetFromStyleSets(StyleSheet&);
4250 void NotifyStyleSheetApplicableStateChanged();
4251 // Just like EnableStyleSheetsForSet, but doesn't check whether
4252 // aSheetSet is null and allows the caller to control whether to set
4253 // aSheetSet as the preferred set in the CSSLoader.
4254 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
4255 bool aUpdateCSSLoader);
4257 already_AddRefed<nsIURI> GetDomainURI();
4258 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4259 const nsACString& aHostString);
4260 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4261 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4263 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4264 mozilla::ErrorResult& aRv);
4265 // A version of WriteCommon used by WebIDL bindings
4266 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4267 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4269 void* GenerateParserKey(void);
4271 private:
4272 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4273 // parameter.
4274 enum class ExecCommandParam : uint8_t {
4275 // Always ignore it.
4276 Ignore,
4277 // Treat the given parameter as-is. If the command requires it, use it.
4278 // Otherwise, ignore it.
4279 String,
4280 // Always treat it as boolean parameter.
4281 Boolean,
4282 // Always treat it as boolean, but inverted.
4283 InvertedBoolean,
4286 using GetEditorCommandFunc = mozilla::EditorCommand*();
4288 struct InternalCommandData {
4289 const char* mXULCommandName;
4290 mozilla::Command mCommand; // uint8_t
4291 // How ConvertToInternalCommand() to treats aValue.
4292 // Its callers don't need to check this.
4293 ExecCommandParam mExecCommandParam; // uint8_t
4294 GetEditorCommandFunc* mGetEditorCommandFunc;
4295 enum class CommandOnTextEditor : uint8_t {
4296 Disabled,
4297 Enabled,
4298 FallThrough, // Not disabled, but handled by HTMLEditor if there is one
4300 CommandOnTextEditor mCommandOnTextEditor;
4302 InternalCommandData()
4303 : mXULCommandName(nullptr),
4304 mCommand(mozilla::Command::DoNothing),
4305 mExecCommandParam(ExecCommandParam::Ignore),
4306 mGetEditorCommandFunc(nullptr),
4307 mCommandOnTextEditor(CommandOnTextEditor::Disabled) {}
4308 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4309 ExecCommandParam aExecCommandParam,
4310 GetEditorCommandFunc aGetEditorCommandFunc,
4311 CommandOnTextEditor aCommandOnTextEditor)
4312 : mXULCommandName(aXULCommandName),
4313 mCommand(aCommand),
4314 mExecCommandParam(aExecCommandParam),
4315 mGetEditorCommandFunc(aGetEditorCommandFunc),
4316 mCommandOnTextEditor(aCommandOnTextEditor) {}
4318 bool IsAvailableOnlyWhenEditable() const {
4319 return mCommand != mozilla::Command::Cut &&
4320 mCommand != mozilla::Command::Copy &&
4321 mCommand != mozilla::Command::Paste &&
4322 mCommand != mozilla::Command::SetDocumentReadOnly &&
4323 mCommand != mozilla::Command::SelectAll;
4325 bool IsCutOrCopyCommand() const {
4326 return mCommand == mozilla::Command::Cut ||
4327 mCommand == mozilla::Command::Copy;
4329 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4333 * AutoEditorCommandTarget considers which editor or global command manager
4334 * handles given command.
4336 class MOZ_RAII AutoEditorCommandTarget {
4337 public:
4338 MOZ_CAN_RUN_SCRIPT AutoEditorCommandTarget(
4339 Document& aDocument, const InternalCommandData& aCommandData);
4340 AutoEditorCommandTarget() = delete;
4341 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget& aOther) =
4342 delete;
4344 bool DoNothing() const { return mDoNothing; }
4345 MOZ_CAN_RUN_SCRIPT bool IsEditable(Document* aDocument) const;
4346 bool IsEditor() const {
4347 MOZ_ASSERT_IF(mEditorCommand, mActiveEditor || mHTMLEditor);
4348 return !!mEditorCommand;
4351 MOZ_CAN_RUN_SCRIPT bool IsCommandEnabled() const;
4352 MOZ_CAN_RUN_SCRIPT nsresult DoCommand(nsIPrincipal* aPrincipal) const;
4353 template <typename ParamType>
4354 MOZ_CAN_RUN_SCRIPT nsresult DoCommandParam(const ParamType& aParam,
4355 nsIPrincipal* aPrincipal) const;
4356 MOZ_CAN_RUN_SCRIPT nsresult
4357 GetCommandStateParams(nsCommandParams& aParams) const;
4359 private:
4360 // The returned editor's life is guaranteed while this instance is alive.
4361 EditorBase* GetTargetEditor() const;
4363 RefPtr<EditorBase> mActiveEditor;
4364 RefPtr<HTMLEditor> mHTMLEditor;
4365 RefPtr<EditorCommand> mEditorCommand;
4366 const InternalCommandData& mCommandData;
4367 bool mDoNothing = false;
4371 * Helper method to initialize sInternalCommandDataHashtable.
4373 static void EnsureInitializeInternalCommandDataHashtable();
4376 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4377 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4378 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4379 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4380 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4381 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4382 * returns a copy of instance created with default constructor. I.e., its
4383 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4384 * is unsupported in such case.
4386 * @param aHTMLCommandName Command name in HTML, e.g., used by
4387 * execCommand().
4388 * @param aValue The value which is set to the 3rd parameter
4389 * of execCommand().
4390 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4391 * Will be set to adjusted value for executing
4392 * the internal command.
4393 * @return Returns a copy of instance created with the
4394 * default constructor if there is no
4395 * corresponding internal command for
4396 * aHTMLCommandName or aValue is invalid for
4397 * found internal command when aAdjustedValue
4398 * is not nullptr. Otherwise, returns a copy of
4399 * instance registered in
4400 * sInternalCommandDataHashtable.
4402 static InternalCommandData ConvertToInternalCommand(
4403 const nsAString& aHTMLCommandName, const nsAString& aValue = u""_ns,
4404 nsAString* aAdjustedValue = nullptr);
4407 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4408 * Since it's a bit field, not a bool member, therefore, we cannot use
4409 * AutoRestorer for it.
4411 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4412 public:
4413 AutoRunningExecCommandMarker() = delete;
4414 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4415 delete;
4416 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4417 MOZ_CAN_RUN_SCRIPT explicit AutoRunningExecCommandMarker(
4418 Document& aDocument)
4419 : mDocument(aDocument),
4420 mHasBeenRunning(aDocument.mIsRunningExecCommand) {
4421 aDocument.mIsRunningExecCommand = true;
4423 ~AutoRunningExecCommandMarker() {
4424 if (!mHasBeenRunning) {
4425 mDocument.mIsRunningExecCommand = false;
4429 private:
4430 Document& mDocument;
4431 bool mHasBeenRunning;
4434 // Mapping table from HTML command name to internal command.
4435 using InternalCommandDataHashtable =
4436 nsTHashMap<nsStringCaseInsensitiveHashKey, InternalCommandData>;
4437 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4439 mutable std::bitset<static_cast<size_t>(
4440 DeprecatedOperations::eDeprecatedOperationCount)>
4441 mDeprecationWarnedAbout;
4442 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4444 // Lazy-initialization to have mDocGroup initialized in prior to the
4445 // SelectorCaches.
4446 UniquePtr<SelectorCache> mSelectorCache;
4447 UniquePtr<ServoStyleSet> mStyleSet;
4449 protected:
4450 // Never ever call this. Only call GetWindow!
4451 nsPIDOMWindowOuter* GetWindowInternal() const;
4453 // Never ever call this. Only call GetScriptHandlingObject!
4454 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4456 // Never ever call this. Only call AllowXULXBL!
4457 bool InternalAllowXULXBL();
4460 * These methods should be called before and after dispatching
4461 * a mutation event.
4462 * To make this easy and painless, use the mozAutoSubtreeModified helper
4463 * class.
4465 void WillDispatchMutationEvent(nsINode* aTarget);
4466 void MutationEventDispatched(nsINode* aTarget);
4467 friend class mozAutoSubtreeModified;
4469 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4471 nsCString GetContentTypeInternal() const { return mContentType; }
4473 // Update our frame request callback scheduling state, if needed. This will
4474 // schedule or unschedule them, if necessary, and update
4475 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4476 // mPresShell is becoming null; in that case it will be used to get hold of
4477 // the relevant refresh driver.
4478 void UpdateFrameRequestCallbackSchedulingState(
4479 PresShell* aOldPresShell = nullptr);
4481 // Helper for GetScrollingElement/IsScrollingElement.
4482 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4484 void MaybeAllowStorageForOpenerAfterUserInteraction();
4486 void MaybeStoreUserInteractionAsPermission();
4488 // Helpers for GetElementsByName.
4489 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4490 nsAtom* aAtom, void* aData);
4491 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4493 void MaybeResolveReadyForIdle();
4495 using AutomaticStorageAccessPermissionGrantPromise =
4496 MozPromise<bool, bool, true>;
4497 [[nodiscard]] RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4498 AutomaticStorageAccessPermissionCanBeGranted(bool hasUserActivation);
4500 static void AddToplevelLoadingDocument(Document* aDoc);
4501 static void RemoveToplevelLoadingDocument(Document* aDoc);
4502 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4503 friend class cycleCollection;
4505 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4506 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4508 nsString mLastModified;
4510 nsCOMPtr<nsIURI> mDocumentURI;
4511 nsCOMPtr<nsIURI> mOriginalURI;
4512 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4513 nsCOMPtr<nsIURI> mDocumentBaseURI;
4514 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4516 // The base domain of the document for third-party checks.
4517 nsCString mBaseDomain;
4519 // A lazily-constructed URL data for style system to resolve URL values.
4520 RefPtr<URLExtraData> mCachedURLData;
4521 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfoForInternalCSSAndSVGResources;
4523 nsWeakPtr mDocumentLoadGroup;
4525 WeakPtr<nsDocShell> mDocumentContainer;
4527 NotNull<const Encoding*> mCharacterSet;
4528 int32_t mCharacterSetSource;
4530 OriginTrials mTrials;
4532 // This is just a weak pointer; the parent document owns its children.
4533 Document* mParentDocument;
4535 // A reference to the element last returned from GetRootElement().
4536 Element* mCachedRootElement;
4538 // This is maintained by AutoSetRestoreSVGContextPaint.
4539 const SVGContextPaint* mCurrentContextPaint = nullptr;
4541 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4542 // which in turn holds a strong reference to this mNodeInfoManager.
4543 nsNodeInfoManager* mNodeInfoManager;
4544 RefPtr<css::Loader> mCSSLoader;
4545 RefPtr<css::ImageLoader> mStyleImageLoader;
4546 RefPtr<nsHTMLStyleSheet> mAttrStyleSheet;
4547 RefPtr<nsHTMLCSSStyleSheet> mStyleAttrStyleSheet;
4549 // Tracking for images in the document.
4550 RefPtr<dom::ImageTracker> mImageTracker;
4552 // A hashtable of ShadowRoots belonging to the composed doc.
4554 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4555 ShadowRootSet mComposedShadowRoots;
4557 using SVGUseElementSet = nsTHashSet<SVGUseElement*>;
4559 // The set of <svg:use> elements that need a shadow tree reclone because the
4560 // tree they map to has changed.
4561 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4563 // The set of all object, embed, video/audio elements or
4564 // nsIObjectLoadingContent or DocumentActivity for which this is
4565 // the owner document. (They might not be in the document.)
4567 // These are non-owning pointers, the elements are responsible for removing
4568 // themselves when they go away.
4569 UniquePtr<nsTHashSet<nsISupports*>> mActivityObservers;
4571 // A hashtable of styled links keyed by address pointer.
4572 nsTHashSet<Link*> mStyledLinks;
4573 #ifdef DEBUG
4574 // Indicates whether mStyledLinks was cleared or not. This is used to track
4575 // state so we can provide useful assertions to consumers of ForgetLink and
4576 // AddStyleRelevantLink.
4577 bool mStyledLinksCleared;
4578 #endif
4580 // The array of all links that need their status resolved. Links must add
4581 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4582 // document.
4583 static const size_t kSegmentSize = 128;
4585 using LinksToUpdateList =
4586 SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>;
4588 LinksToUpdateList mLinksToUpdate;
4590 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4591 RefPtr<SMILAnimationController> mAnimationController;
4593 // Table of element properties for this document.
4594 nsPropertyTable mPropertyTable;
4596 // Our cached .children collection
4597 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4599 // Various DOM lists
4600 RefPtr<nsContentList> mImages;
4601 RefPtr<nsContentList> mEmbeds;
4602 RefPtr<nsContentList> mLinks;
4603 RefPtr<nsContentList> mForms;
4604 RefPtr<nsContentList> mScripts;
4605 nsCOMPtr<nsIHTMLCollection> mApplets;
4606 RefPtr<nsContentList> mAnchors;
4608 // container for per-context fonts (downloadable, SVG, etc.)
4609 RefPtr<FontFaceSet> mFontFaceSet;
4611 // Last time this document or a one of its sub-documents was focused. If
4612 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4613 TimeStamp mLastFocusTime;
4615 // Last time we found any scroll linked effect in this document.
4616 TimeStamp mLastScrollLinkedEffectDetectionTime;
4618 DocumentState mDocumentState{DocumentState::LTR_LOCALE};
4620 RefPtr<Promise> mReadyForIdle;
4622 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4624 UniquePtr<ResizeObserverController> mResizeObserverController;
4626 // Permission Delegate Handler, lazily-initialized in
4627 // GetPermissionDelegateHandler
4628 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4630 bool mCachedStateObjectValid : 1;
4631 bool mBlockAllMixedContent : 1;
4632 bool mBlockAllMixedContentPreloads : 1;
4633 bool mUpgradeInsecureRequests : 1;
4634 bool mUpgradeInsecurePreloads : 1;
4635 bool mDevToolsWatchingDOMMutations : 1;
4637 // True if BIDI is enabled.
4638 bool mBidiEnabled : 1;
4639 // True if we may need to recompute the language prefs for this document.
4640 bool mMayNeedFontPrefsUpdate : 1;
4641 // True if a MathML element has ever been owned by this document.
4642 bool mMathMLEnabled : 1;
4644 // True if this document is the initial document for a window. This should
4645 // basically be true only for documents that exist in newly-opened windows or
4646 // documents created to satisfy a GetDocument() on a window when there's no
4647 // document in it.
4648 bool mIsInitialDocumentInWindow : 1;
4650 bool mIgnoreDocGroupMismatches : 1;
4652 // True if we're loaded as data and therefor has any dangerous stuff, such
4653 // as scripts and plugins, disabled.
4654 bool mLoadedAsData : 1;
4656 // True if the document is considered for memory reporting as a
4657 // data document
4658 bool mAddedToMemoryReportingAsDataDocument : 1;
4660 // If true, whoever is creating the document has gotten it to the
4661 // point where it's safe to start layout on it.
4662 bool mMayStartLayout : 1;
4664 // True iff we've ever fired a DOMTitleChanged event for this document
4665 bool mHaveFiredTitleChange : 1;
4667 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4668 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4669 // before the initial load completes and when we're in bfcache or unloaded,
4670 // true otherwise.
4671 bool mIsShowing : 1;
4673 // State for IsVisible(). mVisible starts off true. It becomes false when
4674 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4675 // it's false only when we're in bfcache or unloaded.
4676 bool mVisible : 1;
4678 // True if our content viewer has been removed from the docshell
4679 // (it may still be displayed, but in zombie state). Form control data
4680 // has been saved.
4681 bool mRemovedFromDocShell : 1;
4683 // True iff DNS prefetch is allowed for this document. Note that if the
4684 // document has no window, DNS prefetch won't be performed no matter what.
4685 bool mAllowDNSPrefetch : 1;
4687 // True when this document is a static clone of a normal document
4688 bool mIsStaticDocument : 1;
4690 // True while this document is being cloned to a static document.
4691 bool mCreatingStaticClone : 1;
4693 // True if this static document has any <canvas> element with a
4694 // mozPrintCallback property at the time of the clone.
4695 bool mHasPrintCallbacks : 1;
4697 // True iff the document is being unlinked or deleted.
4698 bool mInUnlinkOrDeletion : 1;
4700 // True if document has ever had script handling object.
4701 bool mHasHadScriptHandlingObject : 1;
4703 // True if we're an SVG document being used as an image.
4704 bool mIsBeingUsedAsImage : 1;
4706 // True if our current document URI's scheme enables privileged CSS rules.
4707 bool mChromeRulesEnabled : 1;
4709 // True if we're loaded in a chrome docshell.
4710 bool mInChromeDocShell : 1;
4712 // True if our current document is a DevTools document. Either the url is
4713 // about:devtools-toolbox or the parent document already has
4714 // mIsDevToolsDocument set to true.
4715 // This is used to avoid applying High Contrast mode to DevTools documents.
4716 // See Bug 1575766.
4717 bool mIsDevToolsDocument : 1;
4719 // True is this document is synthetic : stand alone image, video, audio
4720 // file, etc.
4721 bool mIsSyntheticDocument : 1;
4723 // True is there is a pending runnable which will call
4724 // FlushPendingLinkUpdates().
4725 bool mHasLinksToUpdateRunnable : 1;
4727 // True if we're flushing pending link updates.
4728 bool mFlushingPendingLinkUpdates : 1;
4730 // True if a DOMMutationObserver is perhaps attached to a node in the
4731 // document.
4732 bool mMayHaveDOMMutationObservers : 1;
4734 // True if an nsIAnimationObserver is perhaps attached to a node in the
4735 // document.
4736 bool mMayHaveAnimationObservers : 1;
4738 // True if a document load has a CSP attached.
4739 bool mHasCSP : 1;
4741 // True if a document load has a CSP with unsafe-eval attached.
4742 bool mHasUnsafeEvalCSP : 1;
4744 // True if a document load has a CSP with unsafe-inline attached.
4745 bool mHasUnsafeInlineCSP : 1;
4747 // True if the document has a CSP delivered throuh a header
4748 bool mHasCSPDeliveredThroughHeader : 1;
4750 // True if DisallowBFCaching has been called on this document.
4751 bool mBFCacheDisallowed : 1;
4753 bool mHasHadDefaultView : 1;
4755 // Whether style sheet change events will be dispatched for this document
4756 bool mStyleSheetChangeEventsEnabled : 1;
4758 // Whether shadowrootattached/anonymousnodecreated/anonymousnoderemoved events
4759 // will be dispatched for this document.
4760 bool mDevToolsAnonymousAndShadowEventsEnabled : 1;
4762 // Whether the document was created by a srcdoc iframe.
4763 bool mIsSrcdocDocument : 1;
4765 // Whether this document has a display document and thus is considered to
4766 // be a resource document. Normally this is the same as !!mDisplayDocument,
4767 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4768 // valid in the document's destructor.
4769 bool mHasDisplayDocument : 1;
4771 // Is the current mFontFaceSet valid?
4772 bool mFontFaceSetDirty : 1;
4774 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4775 // (e.g. we're not being parsed at all).
4776 bool mDidFireDOMContentLoaded : 1;
4778 // True if we have frame request callbacks scheduled with the refresh driver.
4779 // This should generally be updated only via
4780 // UpdateFrameRequestCallbackSchedulingState.
4781 bool mFrameRequestCallbacksScheduled : 1;
4783 bool mIsTopLevelContentDocument : 1;
4785 bool mIsContentDocument : 1;
4787 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4788 bool mDidCallBeginLoad : 1;
4790 // True if the encoding menu should be disabled.
4791 bool mEncodingMenuDisabled : 1;
4793 // False if we've disabled link handling for elements inside this document,
4794 // true otherwise.
4795 bool mLinksEnabled : 1;
4797 // True if this document is for an SVG-in-OpenType font.
4798 bool mIsSVGGlyphsDocument : 1;
4800 // True if the document is being destroyed.
4801 bool mInDestructor : 1;
4803 // True if the document has been detached from its content viewer.
4804 bool mIsGoingAway : 1;
4806 bool mInXBLUpdate : 1;
4808 // Whether we have filled our style set with all the stylesheets.
4809 bool mStyleSetFilled : 1;
4811 // Whether we have a quirks mode stylesheet in the style set.
4812 bool mQuirkSheetAdded : 1;
4814 // Whether we have a contenteditable.css stylesheet in the style set.
4815 bool mContentEditableSheetAdded : 1;
4817 // Whether we have a designmode.css stylesheet in the style set.
4818 bool mDesignModeSheetAdded : 1;
4820 // Keeps track of whether we have a pending
4821 // 'style-sheet-applicable-state-changed' notification.
4822 bool mSSApplicableStateNotificationPending : 1;
4824 // True if this document has ever had an HTML or SVG <title> element
4825 // bound to it
4826 bool mMayHaveTitleElement : 1;
4828 bool mDOMLoadingSet : 1;
4829 bool mDOMInteractiveSet : 1;
4830 bool mDOMCompleteSet : 1;
4831 bool mAutoFocusFired : 1;
4833 bool mScrolledToRefAlready : 1;
4834 bool mChangeScrollPosWhenScrollingToRef : 1;
4836 bool mDelayFrameLoaderInitialization : 1;
4838 bool mSynchronousDOMContentLoaded : 1;
4840 // Set to true when the document is possibly controlled by the ServiceWorker.
4841 // Used to prevent multiple requests to ServiceWorkerManager.
4842 bool mMaybeServiceWorkerControlled : 1;
4844 // These member variables cache information about the viewport so we don't
4845 // have to recalculate it each time.
4846 bool mAllowZoom : 1;
4847 bool mValidScaleFloat : 1;
4848 bool mValidMinScale : 1;
4849 bool mValidMaxScale : 1;
4850 bool mWidthStrEmpty : 1;
4852 // Parser aborted. True if the parser of this document was forcibly
4853 // terminated instead of letting it finish at its own pace.
4854 bool mParserAborted : 1;
4856 // Whether we have reported document use counters for this document with
4857 // Telemetry yet. Normally this is only done at document destruction time,
4858 // but for image documents (SVG documents) that are not guaranteed to be
4859 // destroyed, we report use counters when the image cache no longer has any
4860 // imgRequestProxys pointing to them. We track whether we ever reported use
4861 // counters so that we only report them once for the document.
4862 bool mReportedDocumentUseCounters : 1;
4864 bool mHasReportedShadowDOMUsage : 1;
4866 // Whether an event triggered by the refresh driver was delayed because this
4867 // document has suppressed events.
4868 bool mHasDelayedRefreshEvent : 1;
4870 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4871 // to have the right semantics. See
4872 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4873 // flag that is set while the window's 'load' event is firing if this document
4874 // is the window's document.
4875 bool mLoadEventFiring : 1;
4877 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4878 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4879 // What we have instead is a flag that is set if completion of our document
4880 // via document.close() should skip firing the load event. Note that this
4881 // flag is only relevant for HTML documents, but lives here for reasons that
4882 // are documented above on SkipLoadEventAfterClose().
4883 bool mSkipLoadEventAfterClose : 1;
4885 // When false, the .cookies property is completely disabled
4886 bool mDisableCookieAccess : 1;
4888 // When false, the document.write() API is disabled.
4889 bool mDisableDocWrite : 1;
4891 // Has document.write() been called with a recursion depth higher than
4892 // allowed?
4893 bool mTooDeepWriteRecursion : 1;
4896 * Temporary flag that is set in EndUpdate() to ignore
4897 * MaybeEditingStateChanged() script runners from a nested scope.
4899 bool mPendingMaybeEditingStateChanged : 1;
4901 // mHasBeenEditable is set to true when mEditingState is firstly set to
4902 // eDesignMode or eContentEditable.
4903 bool mHasBeenEditable : 1;
4905 // Whether we've warned about the CSS zoom property.
4907 // We don't use the general deprecated operation mechanism for this because we
4908 // also record this as a `CountedUnknownProperty`.
4909 bool mHasWarnedAboutZoom : 1;
4911 // While we're handling an execCommand call, set to true.
4912 bool mIsRunningExecCommand : 1;
4914 // True if we should change the readystate to complete after we fire
4915 // DOMContentLoaded. This happens when we abort a load and
4916 // nsDocumentViewer::EndLoad runs while we still have things blocking
4917 // DOMContentLoaded. We wait for those to complete, and then update the
4918 // readystate when they finish.
4919 bool mSetCompleteAfterDOMContentLoaded : 1;
4921 // Set the true if a completed cached stylesheet was created for the document.
4922 bool mDidHitCompleteSheetCache : 1;
4924 // Whether we have initialized mShouldReportUseCounters and
4925 // mShouldSendPageUseCounters, and sent any needed message to the parent
4926 // process to indicate that use counter data will be sent at some later point.
4927 bool mUseCountersInitialized : 1;
4929 // Whether this document should report use counters.
4930 bool mShouldReportUseCounters : 1;
4932 // Whether this document should send page use counters. Set to true after
4933 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
4934 bool mShouldSendPageUseCounters : 1;
4936 // Whether the user has interacted with the document or not:
4937 bool mUserHasInteracted : 1;
4939 // We constantly update the user-interaction anti-tracking permission at any
4940 // user-interaction using a timer. This boolean value is set to true when this
4941 // timer is scheduled.
4942 bool mHasUserInteractionTimerScheduled : 1;
4944 // Whether we should resist fingerprinting.
4945 bool mShouldResistFingerprinting : 1;
4947 uint8_t mXMLDeclarationBits;
4949 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4950 // use uint8_t to avoid having to include a bunch of style system headers
4951 // everywhere.
4952 uint8_t mColorSchemeBits = 0;
4954 // Currently active onload blockers.
4955 uint32_t mOnloadBlockCount;
4957 // Tracks if we are currently processing any document.write calls (either
4958 // implicit or explicit). Note that if a write call writes out something which
4959 // would block the parser, then mWriteLevel will be incorrect until the parser
4960 // finishes processing that script.
4961 uint32_t mWriteLevel;
4963 uint32_t mContentEditableCount;
4964 EditingState mEditingState;
4966 // Compatibility mode
4967 nsCompatibility mCompatMode;
4969 // Our readyState
4970 ReadyState mReadyState;
4972 // Ancestor's loading state
4973 bool mAncestorIsLoading;
4975 // Our visibility state
4976 dom::VisibilityState mVisibilityState;
4978 enum Type {
4979 eUnknown, // should never be used
4980 eHTML,
4981 eXHTML,
4982 eGenericXML,
4983 eSVG
4986 Type mType;
4988 uint8_t mDefaultElementType;
4990 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4992 Tri mAllowXULXBL;
4994 bool mSkipDTDSecurityChecks;
4996 // The document's script global object, the object from which the
4997 // document can get its script context and scope. This is the
4998 // *inner* window object.
4999 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
5001 // If mIsStaticDocument is true, mOriginalDocument points to the original
5002 // document.
5003 RefPtr<Document> mOriginalDocument;
5005 // The bidi options for this document. What this bitfield means is
5006 // defined in nsBidiUtils.h
5007 uint32_t mBidiOptions;
5009 // The sandbox flags on the document. These reflect the value of the sandbox
5010 // attribute of the associated IFRAME or CSP-protectable content, if existent.
5011 // These are set at load time and are immutable - see nsSandboxFlags.h for the
5012 // possible flags.
5013 uint32_t mSandboxFlags;
5015 // The embedder policy obtained from parsing the HTTP response header or from
5016 // our opener if this is the initial about:blank document.
5017 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
5019 nsCString mContentLanguage;
5021 // The channel that got passed to Document::StartDocumentLoad(), if any.
5022 nsCOMPtr<nsIChannel> mChannel;
5024 // The CSP for every load lives in the Client within the LoadInfo. For all
5025 // document-initiated subresource loads we can use that cached version of the
5026 // CSP so we do not have to deserialize the CSP from the Client all the time.
5027 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
5028 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
5030 private:
5031 nsCString mContentType;
5033 protected:
5034 // The document's security info
5035 nsCOMPtr<nsITransportSecurityInfo> mSecurityInfo;
5037 // The channel that failed to load and resulted in an error page.
5038 // This only applies to error pages. Might be null.
5039 nsCOMPtr<nsIChannel> mFailedChannel;
5041 // if this document is part of a multipart document,
5042 // the ID can be used to distinguish it from the other parts.
5043 uint32_t mPartID;
5045 // Cycle collector generation in which we're certain that this document
5046 // won't be collected
5047 uint32_t mMarkedCCGeneration;
5049 PresShell* mPresShell;
5051 nsCOMArray<nsINode> mSubtreeModifiedTargets;
5052 uint32_t mSubtreeModifiedDepth;
5054 // All images in process of being preloaded. This is a hashtable so
5055 // we can remove them as the real image loads start; that way we
5056 // make sure to not keep the image load going when no one cares
5057 // about it anymore.
5058 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
5060 // A list of preconnects initiated by the preloader. This prevents
5061 // the same uri from being used more than once, and allows the dom
5062 // builder to not repeat the work of the preloader.
5063 nsTHashMap<nsURIHashKey, bool> mPreloadedPreconnects;
5065 // Current depth of picture elements from parser
5066 uint32_t mPreloadPictureDepth;
5068 // Set if we've found a URL for the current picture
5069 nsString mPreloadPictureFoundSource;
5071 // If we're an external resource document, this will be non-null and will
5072 // point to our "display document": the one that all resource lookups should
5073 // go to.
5074 RefPtr<Document> mDisplayDocument;
5076 uint32_t mEventsSuppressed;
5078 // Any XHR ChannelEventQueues that were suspended on this document while
5079 // events were suppressed.
5080 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
5082 // Any postMessage events that were suspended on this document while events
5083 // were suppressed.
5084 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
5086 RefPtr<EventListener> mSuppressedEventListener;
5089 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
5091 uint32_t mIgnoreDestructiveWritesCounter;
5093 // Count of live static clones of this document.
5094 uint32_t mStaticCloneCount;
5096 // If the document is currently printing (or in print preview) this will point
5097 // to the current static clone of this document. This is weak since the clone
5098 // also has a reference to this document.
5099 WeakPtr<Document> mLatestStaticClone;
5101 // Array of nodes that have been blocked to prevent user tracking.
5102 // They most likely have had their nsIChannel canceled by the URL
5103 // classifier. (Safebrowsing)
5105 // Weak nsINode pointers are used to allow nodes to disappear.
5106 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
5108 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
5109 // updated on every set of mScriptGlobalObject.
5110 nsPIDOMWindowInner* mWindow;
5112 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
5114 FrameRequestManager mFrameRequestManager;
5116 // This object allows us to evict ourself from the back/forward cache. The
5117 // pointer is non-null iff we're currently in the bfcache.
5118 nsIBFCacheEntry* mBFCacheEntry;
5120 // Our base target.
5121 nsString mBaseTarget;
5123 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
5124 JS::Heap<JS::Value> mCachedStateObject;
5126 uint32_t mInSyncOperationCount;
5128 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
5130 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
5132 uint32_t mBlockDOMContentLoaded;
5134 // Our live MediaQueryLists
5135 LinkedList<MediaQueryList> mDOMMediaQueryLists;
5137 // Array of observers
5138 nsTObserverArray<nsIDocumentObserver*> mObservers;
5140 // Flags for use counters used directly by this document.
5141 UseCounters mUseCounters;
5142 // Flags for use counters from resource documents, static clones,
5143 // and SVG images referenced by this document. Those documents propagate
5144 // their use counters up to here, which then count towards the top-level
5145 // document's page use counters.
5146 UseCounters mChildDocumentUseCounters;
5148 // The CSS property use counters.
5149 UniquePtr<StyleUseCounters> mStyleUseCounters;
5151 TimeStamp mPageUnloadingEventTimeStamp;
5153 RefPtr<DocGroup> mDocGroup;
5155 RefPtr<nsCommandManager> mMidasCommandManager;
5157 // The set of all the tracking script URLs. URLs are added to this set by
5158 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5159 // existing in the set means the corresponding script isn't a tracking script.
5160 nsTHashSet<nsCString> mTrackingScripts;
5162 // Pointer to our parser if we're currently in the process of being
5163 // parsed into.
5164 nsCOMPtr<nsIParser> mParser;
5166 // If the document was created from the the prototype cache there will be a
5167 // reference to the prototype document to allow tracing.
5168 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
5170 // Weak reference to our sink for in case we no longer have a parser. This
5171 // will allow us to flush out any pending stuff from the sink even if
5172 // EndLoad() has already happened.
5173 nsWeakPtr mWeakSink;
5175 // Our update nesting level
5176 uint32_t mUpdateNestLevel;
5178 // HTTPS-Only Mode Status
5179 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5180 uint32_t mHttpsOnlyStatus;
5182 enum ViewportType : uint8_t {
5183 DisplayWidthHeight,
5184 Specified,
5185 Unknown,
5188 ViewportType mViewportType;
5190 // viewport-fit described by
5191 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5192 ViewportFitType mViewportFit;
5194 PLDHashTable* mSubDocuments;
5196 class HeaderData;
5197 UniquePtr<HeaderData> mHeaderData;
5199 nsTArray<net::EarlyHintConnectArgs> mEarlyHints;
5201 nsRevocableEventPtr<nsRunnableMethod<Document, void, false>>
5202 mPendingTitleChangeEvent;
5204 RefPtr<nsDOMNavigationTiming> mTiming;
5206 // Recorded time of change to 'loading' state.
5207 TimeStamp mLoadingTimeStamp;
5209 // Decided to use nsTObserverArray because it allows us to
5210 // remove candidates while iterating them and this is what
5211 // the spec defines. We could implement the spec without
5212 // using nsTObserverArray, however using nsTObserverArray is more clear.
5213 nsTObserverArray<nsWeakPtr> mAutoFocusCandidates;
5215 nsCString mScrollToRef;
5217 // Weak reference to the scope object (aka the script global object)
5218 // that, unlike mScriptGlobalObject, is never unset once set. This
5219 // is a weak reference to avoid leaks due to circular references.
5220 nsWeakPtr mScopeObject;
5222 // Array of intersection observers
5223 nsTHashSet<DOMIntersectionObserver*> mIntersectionObservers;
5225 RefPtr<DOMIntersectionObserver> mLazyLoadImageObserver;
5226 // Used to measure how effective the lazyload thresholds are.
5227 RefPtr<DOMIntersectionObserver> mLazyLoadImageObserverViewport;
5229 // Used for detecting when `content-visibility: auto` elements are near
5230 // or far from the viewport.
5231 RefPtr<DOMIntersectionObserver> mContentVisibilityObserver;
5233 // ResizeObserver for storing and removing the last remembered size.
5234 // @see {@link https://drafts.csswg.org/css-sizing-4/#last-remembered}
5235 RefPtr<ResizeObserver> mLastRememberedSizeObserver;
5237 // Stack of top layer elements.
5238 nsTArray<nsWeakPtr> mTopLayer;
5240 // The root of the doc tree in which this document is in. This is only
5241 // non-null when this document is in fullscreen mode.
5242 nsWeakPtr mFullscreenRoot;
5244 RefPtr<DOMImplementation> mDOMImplementation;
5246 RefPtr<nsContentList> mImageMaps;
5248 // A set of responsive images keyed by address pointer.
5249 nsTHashSet<HTMLImageElement*> mResponsiveContent;
5251 RefPtr<DocumentTimeline> mDocumentTimeline;
5252 LinkedList<DocumentTimeline> mTimelines;
5254 RefPtr<dom::ScriptLoader> mScriptLoader;
5256 // Tracker for animations that are waiting to start.
5257 // nullptr until GetOrCreatePendingAnimationTracker is called.
5258 RefPtr<PendingAnimationTracker> mPendingAnimationTracker;
5260 // Tracker for scroll-driven animations that are waiting to start.
5261 // nullptr until GetOrCreateScrollTimelineAnimationTracker is called.
5262 RefPtr<ScrollTimelineAnimationTracker> mScrollTimelineAnimationTracker;
5264 // A document "without a browsing context" that owns the content of
5265 // HTMLTemplateElement.
5266 RefPtr<Document> mTemplateContentsOwner;
5268 dom::ExternalResourceMap mExternalResourceMap;
5270 // ScreenOrientation "pending promise" as described by
5271 // http://www.w3.org/TR/screen-orientation/
5272 RefPtr<Promise> mOrientationPendingPromise;
5274 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
5275 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
5276 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
5278 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
5280 // The layout history state that should be used by nodes in this
5281 // document. We only actually store a pointer to it when:
5282 // 1) We have no script global object.
5283 // 2) We haven't had Destroy() called on us yet.
5284 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
5286 // The parsed viewport metadata of the last modified <meta name=viewport>
5287 // element.
5288 UniquePtr<ViewportMetaData> mLastModifiedViewportMetaData;
5290 // A tree ordered list of all color-scheme meta tags in this document.
5292 // TODO(emilio): There are other meta tags in the spec that have a similar
5293 // processing model to color-scheme. We could store all in-document meta tags
5294 // here to get sane and fast <meta> element processing.
5295 TreeOrderedArray<HTMLMetaElement> mColorSchemeMetaTags;
5297 // These member variables cache information about the viewport so we don't
5298 // have to recalculate it each time.
5299 LayoutDeviceToScreenScale mScaleMinFloat;
5300 LayoutDeviceToScreenScale mScaleMaxFloat;
5301 LayoutDeviceToScreenScale mScaleFloat;
5302 CSSToLayoutDeviceScale mPixelRatio;
5304 CSSCoord mMinWidth;
5305 CSSCoord mMaxWidth;
5306 CSSCoord mMinHeight;
5307 CSSCoord mMaxHeight;
5309 RefPtr<EventListenerManager> mListenerManager;
5311 nsCOMPtr<nsIRequest> mOnloadBlocker;
5313 // Gecko-internal sheets used for extensions and such.
5314 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5315 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5317 // Member to store out last-selected stylesheet set.
5318 nsString mLastStyleSheetSet;
5319 nsString mPreferredStyleSheetSet;
5321 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5323 // We lazily calculate declaration blocks for SVG elements with mapped
5324 // attributes in Servo mode. This list contains all elements which need lazy
5325 // resolution.
5326 nsTHashSet<SVGElement*> mLazySVGPresElements;
5328 nsTHashSet<RefPtr<nsAtom>> mLanguagesUsed;
5330 // TODO(emilio): Is this hot enough to warrant to be cached?
5331 RefPtr<nsAtom> mLanguageFromCharset;
5333 // Restyle root for servo's style system.
5335 // We store this as an nsINode, rather than as an Element, so that we can
5336 // store the Document node as the restyle root if the entire document (along
5337 // with all document-level native-anonymous content) needs to be restyled.
5339 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5340 // root corresponds to.
5341 nsCOMPtr<nsINode> mServoRestyleRoot;
5342 uint32_t mServoRestyleRootDirtyBits;
5344 // Used in conjunction with the create-an-element-for-the-token algorithm to
5345 // prevent custom element constructors from being able to use document.open(),
5346 // document.close(), and document.write() when they are invoked by the parser.
5347 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5349 // Count of unload/beforeunload/pagehide operations in progress.
5350 uint32_t mIgnoreOpensDuringUnloadCounter;
5352 nsCOMPtr<nsIDOMXULCommandDispatcher>
5353 mCommandDispatcher; // [OWNER] of the focus tracker
5355 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5356 RefPtr<XULPersist> mXULPersist;
5357 RefPtr<ChromeObserver> mChromeObserver;
5359 RefPtr<HTMLAllCollection> mAll;
5361 nsTHashSet<RefPtr<WorkerDocumentListener>> mWorkerListeners;
5363 // Pres shell resolution saved before entering fullscreen mode.
5364 float mSavedResolution;
5366 // Pres shell resolution saved before creating a MobileViewportManager.
5367 float mSavedResolutionBeforeMVM;
5369 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5371 bool mHasStoragePermission;
5373 // Document generation. Gets incremented everytime it changes.
5374 int32_t mGeneration;
5376 // Cached TabSizes values for the document.
5377 int32_t mCachedTabSizeGeneration;
5378 nsTabSizes mCachedTabSizes;
5380 // This is equal to document's principal but with an isolation key. See
5381 // StoragePrincipalHelper.h to know more.
5382 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5384 // The cached storage principal for this document.
5385 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5386 // which is required due to its CloneDocHelper() call site. :-(
5387 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5389 // The cached cookie principal for this document.
5390 // This is mutable so that we can keep EffectiveCookiePrincipal() const
5391 // which is required due to its CloneDocHelper() call site. :-(
5392 mutable nsCOMPtr<nsIPrincipal> mActiveCookiePrincipal;
5394 // See GetNextFormNumber and GetNextControlNumber.
5395 int32_t mNextFormNumber;
5396 int32_t mNextControlNumber;
5398 uint32_t mMediaElementWithMSECount = 0;
5400 // Scope preloads per document. This is used by speculative loading as well.
5401 PreloadService mPreloadService;
5403 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5404 bool mShouldNotifyFetchSuccess;
5406 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5407 bool mShouldNotifyFormOrPasswordRemoved;
5409 // Record page load telemetry
5410 void RecordPageLoadEventTelemetry(
5411 glean::perf::PageLoadExtra& aEventTelemetryData);
5413 // Accumulate JS telemetry collected
5414 void AccumulateJSTelemetry(
5415 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5417 // Accumulate page load metrics
5418 void AccumulatePageLoadTelemetry(
5419 glean::perf::PageLoadExtra& aEventTelemetryDataOut);
5421 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5422 // Not holding strong refs here since we don't actually use the BBCs.
5423 nsTArray<const BrowserBridgeChild*> mOOPChildrenLoading;
5425 // Registry of custom highlight definitions associated with this document.
5426 RefPtr<class HighlightRegistry> mHighlightRegistry;
5428 public:
5429 // Needs to be public because the bindings code pokes at it.
5430 JS::ExpandoAndGeneration mExpandoAndGeneration;
5432 bool HasPendingInitialTranslation();
5434 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5435 mL10nProtoElements;
5437 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5438 void SetSavedResolutionBeforeMVM(float aResolution) {
5439 mSavedResolutionBeforeMVM = aResolution;
5442 void LoadEventFired();
5445 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5448 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5449 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5450 * object is deleted.
5452 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5453 public:
5455 * @param aSubTreeOwner The document in which a subtree will be modified.
5456 * @param aTarget The target of the possible DOMSubtreeModified event.
5457 * Can be nullptr, in which case mozAutoSubtreeModified
5458 * is just used to batch DOM mutations.
5460 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5461 UpdateTarget(aSubtreeOwner, aTarget);
5464 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5466 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5467 if (mSubtreeOwner) {
5468 mSubtreeOwner->MutationEventDispatched(mTarget);
5471 mTarget = aTarget;
5472 mSubtreeOwner = aSubtreeOwner;
5473 if (mSubtreeOwner) {
5474 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5478 private:
5479 nsCOMPtr<nsINode> mTarget;
5480 RefPtr<Document> mSubtreeOwner;
5483 enum class SyncOperationBehavior { eSuspendInput, eAllowInput };
5485 class AutoWalkBrowsingContextGroup {
5486 public:
5487 virtual ~AutoWalkBrowsingContextGroup() = default;
5489 protected:
5490 void SuppressBrowsingContext(BrowsingContext* aContext);
5491 void SuppressBrowsingContextGroup(BrowsingContextGroup* aGroup);
5492 void UnsuppressDocuments() {
5493 for (const auto& doc : mDocuments) {
5494 UnsuppressDocument(doc);
5497 virtual void SuppressDocument(Document* aDocument) = 0;
5498 virtual void UnsuppressDocument(Document* aDocument) = 0;
5499 AutoTArray<RefPtr<Document>, 16> mDocuments;
5502 class MOZ_RAII nsAutoSyncOperation : private AutoWalkBrowsingContextGroup {
5503 public:
5504 explicit nsAutoSyncOperation(Document* aDocument,
5505 SyncOperationBehavior aSyncBehavior);
5506 ~nsAutoSyncOperation();
5508 protected:
5509 void SuppressDocument(Document* aDocument) override;
5510 void UnsuppressDocument(Document* aDocument) override;
5512 private:
5513 uint32_t mMicroTaskLevel;
5514 const SyncOperationBehavior mSyncBehavior;
5515 RefPtr<BrowsingContext> mBrowsingContext;
5518 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5519 public:
5520 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5521 : mDocument(aDocument) {
5522 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5525 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5526 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5529 private:
5530 Document* mDocument;
5533 class MOZ_RAII IgnoreOpensDuringUnload final {
5534 public:
5535 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5536 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5539 ~IgnoreOpensDuringUnload() {
5540 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5543 private:
5544 Document* mDoc;
5547 bool IsInFocusedTab(Document* aDoc);
5549 // This covers all cases covered by IsInFocusedTab, but also ensures that
5550 // focused tab is "active" meaning not occluded.
5551 bool IsInActiveTab(Document* aDoc);
5553 } // namespace mozilla::dom
5555 // XXX These belong somewhere else
5556 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5557 bool aLoadedAsData = false);
5559 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5560 bool aLoadedAsData = false,
5561 bool aIsPlainDocument = false);
5563 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult);
5565 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult);
5567 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult);
5569 // Enum for requesting a particular type of document when creating a doc
5570 enum DocumentFlavor {
5571 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5572 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5573 DocumentFlavorSVG, // SVGDocument
5574 DocumentFlavorXML, // XMLDocument
5575 DocumentFlavorPlain, // Just a Document
5578 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5579 // -- this method will not attempt to get a principal based on aDocumentURI.
5580 // Also, both aDocumentURI and aBaseURI must not be null.
5581 nsresult NS_NewDOMDocument(
5582 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5583 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5584 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5585 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5587 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5588 mozilla::dom::Document* ownerDoc = OwnerDoc();
5590 return ownerDoc != this ? ownerDoc : nullptr;
5593 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5595 inline mozilla::dom::Document* nsINode::AsDocument() {
5596 MOZ_ASSERT(IsDocument());
5597 return static_cast<mozilla::dom::Document*>(this);
5600 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5601 MOZ_ASSERT(IsDocument());
5602 return static_cast<const mozilla::dom::Document*>(this);
5605 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5606 return static_cast<nsINode*>(aDoc);
5609 #endif /* mozilla_dom_Document_h___ */