Bug 1665252 - remove allowpaymentrequest attribute from HTMLIFrameElement r=dom-worke...
[gecko.git] / dom / base / Document.h
blob572afd62752464f315c9fb17ee43e7e7ad530b79
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 "mozilla/EventStates.h" // for EventStates
11 #include "mozilla/FlushType.h" // for enum
12 #include "mozilla/MozPromise.h" // for MozPromise
13 #include "mozilla/FunctionRef.h" // for FunctionRef
14 #include "nsCOMArray.h" // for member
15 #include "nsCompatibility.h" // for member
16 #include "nsCOMPtr.h" // for member
17 #include "nsGkAtoms.h" // for static class members
18 #include "nsIApplicationCacheContainer.h"
19 #include "nsIContentViewer.h"
20 #include "nsIInterfaceRequestor.h"
21 #include "nsILoadContext.h"
22 #include "nsILoadGroup.h" // for member (in nsCOMPtr)
23 #include "nsINode.h" // for base class
24 #include "nsIParser.h"
25 #include "nsIChannelEventSink.h"
26 #include "nsIProgressEventSink.h"
27 #include "nsIRadioGroupContainer.h"
28 #include "nsIScriptObjectPrincipal.h"
29 #include "nsIURI.h" // for use in inline functions
30 #include "nsIWeakReferenceUtils.h" // for nsWeakPtr
31 #include "nsPIDOMWindow.h" // for use in inline functions
32 #include "nsPropertyTable.h" // for member
33 #include "nsStringFwd.h"
34 #include "nsStubMutationObserver.h"
35 #include "nsTHashtable.h" // for member
36 #include "nsURIHashKey.h"
37 #include "mozilla/UseCounter.h"
38 #include "mozilla/WeakPtr.h"
39 #include "Units.h"
40 #include "nsContentListDeclarations.h"
41 #include "nsExpirationTracker.h"
42 #include "nsClassHashtable.h"
43 #include "nsWindowSizes.h"
44 #include "ReferrerInfo.h"
45 #include "mozilla/Attributes.h"
46 #include "mozilla/CallState.h"
47 #include "mozilla/CORSMode.h"
48 #include "mozilla/dom/DispatcherTrait.h"
49 #include "mozilla/dom/DocumentOrShadowRoot.h"
50 #include "mozilla/dom/ViewportMetaData.h"
51 #include "mozilla/HashTable.h"
52 #include "mozilla/LinkedList.h"
53 #include "mozilla/NotNull.h"
54 #include "mozilla/PreloadService.h"
55 #include "mozilla/SegmentedVector.h"
56 #include "mozilla/TimeStamp.h"
57 #include "mozilla/UniquePtr.h"
58 #include <bitset> // for member
59 #include "js/friend/DOMProxy.h" // JS::ExpandoAndGeneration
61 // XXX We need to include this here to ensure that DefaultDeleter for Servo
62 // types is specialized before the template is instantiated. Probably, this
63 // should be included at some other place already that's generated by cbindgen.
64 #include "mozilla/ServoStyleConsts.h"
66 // windows.h #defines CreateEvent
67 #ifdef CreateEvent
68 # undef CreateEvent
69 #endif
71 #ifdef MOZILLA_INTERNAL_API
72 # include "mozilla/dom/DocumentBinding.h"
73 #else
74 namespace mozilla {
75 namespace dom {
76 class ElementCreationOptionsOrString;
77 } // namespace dom
78 } // namespace mozilla
79 #endif // MOZILLA_INTERNAL_API
81 class gfxUserFontSet;
82 class imgIRequest;
83 class nsCachableElementsByNameNodeList;
84 class nsCommandManager;
85 class nsContentList;
86 class nsDocShell;
87 class nsDOMNavigationTiming;
88 class nsFrameLoader;
89 class nsFrameLoaderOwner;
90 class nsGlobalWindowInner;
91 class nsHtml5TreeOpExecutor;
92 class nsHTMLCSSStyleSheet;
93 class nsHTMLDocument;
94 class nsHTMLStyleSheet;
95 class nsGenericHTMLElement;
96 class nsIBFCacheEntry;
97 class nsIContent;
98 class nsIContentSink;
99 class nsIDocShell;
100 class nsIDocShellTreeItem;
101 class nsIDocumentEncoder;
102 class nsIDocumentObserver;
103 class nsIDOMXULCommandDispatcher;
104 class nsIHTMLCollection;
105 class nsILayoutHistoryState;
106 class nsIObjectLoadingContent;
107 class nsIRequest;
108 class nsIRunnable;
109 class nsIScriptGlobalObject;
110 class nsISecurityConsoleMessage;
111 class nsIStructuredCloneContainer;
112 class nsIVariant;
113 class nsViewManager;
114 class nsPresContext;
115 class nsRange;
116 class nsSimpleContentList;
117 class nsTextNode;
118 class nsDOMCaretPosition;
119 class nsViewportInfo;
120 class nsIGlobalObject;
121 class nsIAppWindow;
122 class nsXULPrototypeDocument;
123 class nsXULPrototypeElement;
124 class nsIPermissionDelegateHandler;
125 struct nsFont;
126 struct StyleUseCounters;
128 namespace mozilla {
129 class AbstractThread;
130 class StyleSheet;
131 class EditorCommand;
132 class Encoding;
133 class ErrorResult;
134 class EventListenerManager;
135 class FullscreenExit;
136 class FullscreenRequest;
137 struct LangGroupFontPrefs;
138 class PendingAnimationTracker;
139 class PermissionDelegateHandler;
140 class PresShell;
141 class ServoStyleSet;
142 enum class StyleOrigin : uint8_t;
143 class SMILAnimationController;
144 enum class StyleCursorKind : uint8_t;
145 enum class StylePrefersColorScheme : uint8_t;
146 template <typename>
147 class OwningNonNull;
148 struct URLExtraData;
150 namespace css {
151 class Loader;
152 class ImageLoader;
153 class Rule;
154 } // namespace css
156 namespace dom {
157 class AnonymousContent;
158 class Attr;
159 class XULBroadcastManager;
160 class XULPersist;
161 class ChromeObserver;
162 class ClientInfo;
163 class ClientState;
164 class CDATASection;
165 class Comment;
166 class CSSImportRule;
167 struct CustomElementDefinition;
168 class DocumentL10n;
169 class DocumentFragment;
170 class DocumentTimeline;
171 class DocumentType;
172 class DOMImplementation;
173 class DOMIntersectionObserver;
174 class DOMStringList;
175 class Element;
176 class Event;
177 struct FailedCertSecurityInfo;
178 class FeaturePolicy;
179 class FontFaceSet;
180 class FrameRequestCallback;
181 class ImageTracker;
182 class HTMLAllCollection;
183 class HTMLBodyElement;
184 class HTMLMetaElement;
185 class HTMLDialogElement;
186 class HTMLSharedElement;
187 class HTMLImageElement;
188 struct LifecycleCallbackArgs;
189 class Link;
190 class Location;
191 class MediaQueryList;
192 struct NetErrorInfo;
193 class NodeFilter;
194 class NodeIterator;
195 enum class OrientationType : uint8_t;
196 class ProcessingInstruction;
197 class Promise;
198 class ScriptLoader;
199 class Selection;
200 class ServiceWorkerDescriptor;
201 class SVGDocument;
202 class SVGElement;
203 class SVGSVGElement;
204 class SVGUseElement;
205 class Touch;
206 class TouchList;
207 class TreeWalker;
208 enum class ViewportFitType : uint8_t;
209 class XPathEvaluator;
210 class XPathExpression;
211 class XPathNSResolver;
212 class XPathResult;
213 class BrowsingContext;
215 class nsDocumentOnStack;
216 class nsUnblockOnloadEvent;
218 template <typename, typename>
219 class CallbackObjectHolder;
221 enum class CallerType : uint32_t;
223 enum BFCacheStatus {
224 NOT_ALLOWED = 1 << 0, // Status 0
225 EVENT_HANDLING_SUPPRESSED = 1 << 1, // Status 1
226 SUSPENDED = 1 << 2, // Status 2
227 UNLOAD_LISTENER = 1 << 3, // Status 3
228 REQUEST = 1 << 4, // Status 4
229 ACTIVE_GET_USER_MEDIA = 1 << 5, // Status 5
230 ACTIVE_PEER_CONNECTION = 1 << 6, // Status 6
231 CONTAINS_EME_CONTENT = 1 << 7, // Status 7
232 CONTAINS_MSE_CONTENT = 1 << 8, // Status 8
233 HAS_ACTIVE_SPEECH_SYNTHESIS = 1 << 9, // Status 9
234 HAS_USED_VR = 1 << 10, // Status 10
235 CONTAINS_REMOTE_SUBFRAMES = 1 << 11, // Status 11
236 NOT_ONLY_TOPLEVEL_IN_BCG = 1 << 12 // Status 12
239 } // namespace dom
240 } // namespace mozilla
242 namespace mozilla {
243 namespace net {
244 class ChannelEventQueue;
245 } // namespace net
246 } // namespace mozilla
248 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
249 #define NS_IDOCUMENT_IID \
251 0xce1f7627, 0x7109, 0x4977, { \
252 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
256 namespace mozilla {
257 namespace dom {
259 class Document;
260 class DOMStyleSheetSetList;
261 class ResizeObserver;
262 class ResizeObserverController;
263 class PostMessageEvent;
265 // Document states
267 // RTL locale: specific to the XUL localedir attribute
268 #define NS_DOCUMENT_STATE_RTL_LOCALE NS_DEFINE_EVENT_STATE_MACRO(0)
269 // Window activation status
270 #define NS_DOCUMENT_STATE_WINDOW_INACTIVE NS_DEFINE_EVENT_STATE_MACRO(1)
272 class DocHeaderData {
273 public:
274 DocHeaderData(nsAtom* aField, const nsAString& aData)
275 : mField(aField), mData(aData), mNext(nullptr) {}
277 ~DocHeaderData(void) { delete mNext; }
279 RefPtr<nsAtom> mField;
280 nsString mData;
281 DocHeaderData* mNext;
284 class ExternalResourceMap {
285 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
287 public:
289 * A class that represents an external resource load that has begun but
290 * doesn't have a document yet. Observers can be registered on this object,
291 * and will be notified after the document is created. Observers registered
292 * after the document has been created will NOT be notified. When observers
293 * are notified, the subject will be the newly-created document, the topic
294 * will be "external-resource-document-created", and the data will be null.
295 * If document creation fails for some reason, observers will still be
296 * notified, with a null document pointer.
298 class ExternalResourceLoad : public nsISupports {
299 public:
300 virtual ~ExternalResourceLoad() = default;
302 void AddObserver(nsIObserver* aObserver) {
303 MOZ_ASSERT(aObserver, "Must have observer");
304 mObservers.AppendElement(aObserver);
307 const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
309 protected:
310 AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
313 ExternalResourceMap();
316 * Request an external resource document. This does exactly what
317 * Document::RequestExternalResource is documented to do.
319 Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
320 nsINode* aRequestingNode,
321 Document* aDisplayDocument,
322 ExternalResourceLoad** aPendingLoad);
325 * Enumerate the resource documents. See
326 * Document::EnumerateExternalResources.
328 void EnumerateResources(SubDocEnumFunc aCallback);
331 * Traverse ourselves for cycle-collection
333 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
336 * Shut ourselves down (used for cycle-collection unlink), as well
337 * as for document destruction.
339 void Shutdown() {
340 mPendingLoads.Clear();
341 mMap.Clear();
342 mHaveShutDown = true;
345 bool HaveShutDown() const { return mHaveShutDown; }
347 // Needs to be public so we can traverse them sanely
348 struct ExternalResource {
349 ~ExternalResource();
350 RefPtr<Document> mDocument;
351 nsCOMPtr<nsIContentViewer> mViewer;
352 nsCOMPtr<nsILoadGroup> mLoadGroup;
355 // Hide all our viewers
356 void HideViewers();
358 // Show all our viewers
359 void ShowViewers();
361 protected:
362 class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
363 ~PendingLoad() = default;
365 public:
366 explicit PendingLoad(Document* aDisplayDocument)
367 : mDisplayDocument(aDisplayDocument) {}
369 NS_DECL_ISUPPORTS
370 NS_DECL_NSISTREAMLISTENER
371 NS_DECL_NSIREQUESTOBSERVER
374 * Start aURI loading. This will perform the necessary security checks and
375 * so forth.
377 nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
378 nsINode* aRequestingNode);
380 * Set up an nsIContentViewer based on aRequest. This is guaranteed to
381 * put null in *aViewer and *aLoadGroup on all failures.
383 nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
384 nsILoadGroup** aLoadGroup);
386 private:
387 RefPtr<Document> mDisplayDocument;
388 nsCOMPtr<nsIStreamListener> mTargetListener;
389 nsCOMPtr<nsIURI> mURI;
391 friend class PendingLoad;
393 class LoadgroupCallbacks final : public nsIInterfaceRequestor {
394 ~LoadgroupCallbacks() = default;
396 public:
397 explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
398 : mCallbacks(aOtherCallbacks) {}
399 NS_DECL_ISUPPORTS
400 NS_DECL_NSIINTERFACEREQUESTOR
401 private:
402 // The only reason it's safe to hold a strong ref here without leaking is
403 // that the notificationCallbacks on a loadgroup aren't the docshell itself
404 // but a shim that holds a weak reference to the docshell.
405 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
407 // Use shims for interfaces that docshell implements directly so that we
408 // don't hand out references to the docshell. The shims should all allow
409 // getInterface back on us, but other than that each one should only
410 // implement one interface.
412 // XXXbz I wish we could just derive the _allcaps thing from _i
413 #define DECL_SHIM(_i, _allcaps) \
414 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
415 ~_i##Shim() {} \
417 public: \
418 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
419 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
420 NS_ASSERTION(mIfReq, "Expected non-null here"); \
421 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
423 NS_DECL_ISUPPORTS \
424 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
425 NS_FORWARD_##_allcaps(mRealPtr->) private \
426 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
427 nsCOMPtr<_i> mRealPtr; \
430 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
431 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
432 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
433 DECL_SHIM(nsIApplicationCacheContainer, NSIAPPLICATIONCACHECONTAINER)
434 #undef DECL_SHIM
438 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
439 * when this is called if the URI didn't result in an XML document. This
440 * function makes sure to remove the pending load for aURI, if any, from our
441 * hashtable, and to notify its observers, if any.
443 nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
444 nsILoadGroup* aLoadGroup,
445 Document* aDisplayDocument);
447 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
448 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
449 bool mHaveShutDown;
452 // The current status for a preload.
453 enum class SheetPreloadStatus : uint8_t {
454 // There's no need to preload anything, the sheet is already in-memory.
455 AlreadyComplete,
456 // The load is in-progress. There's no guarantee that a load was started, it
457 // could be coalesced with other redundant loads.
458 InProgress,
459 // Something went wrong, and we errored out.
460 Errored,
463 //----------------------------------------------------------------------
465 // Document interface. This is implemented by all document objects in
466 // Gecko.
467 class Document : public nsINode,
468 public DocumentOrShadowRoot,
469 public nsSupportsWeakReference,
470 public nsIRadioGroupContainer,
471 public nsIScriptObjectPrincipal,
472 public nsIApplicationCacheContainer,
473 public nsStubMutationObserver,
474 public DispatcherTrait,
475 public SupportsWeakPtr {
476 friend class DocumentOrShadowRoot;
478 protected:
479 explicit Document(const char* aContentType);
480 virtual ~Document();
482 Document(const Document&) = delete;
483 Document& operator=(const Document&) = delete;
485 public:
486 typedef dom::ExternalResourceMap::ExternalResourceLoad ExternalResourceLoad;
487 typedef dom::ReferrerPolicy ReferrerPolicyEnum;
488 using AdoptedStyleSheetCloneCache =
489 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
491 // nsINode overrides the new operator for DOM Arena allocation.
492 // to use the default one, we need to bring it back again
493 void* operator new(size_t aSize) { return ::operator new(aSize); }
496 * Called when XPCOM shutdown.
498 static void Shutdown();
500 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
502 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
504 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
506 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
507 nsINode)
509 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
510 do { \
511 NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(mObservers, func_, params_); \
512 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
513 looks bogus. */ \
514 if (PresShell* presShell = GetObservingPresShell()) { \
515 presShell->func_ params_; \
517 } while (0)
519 // nsIApplicationCacheContainer
520 NS_DECL_NSIAPPLICATIONCACHECONTAINER
522 // nsIRadioGroupContainer
523 NS_IMETHOD WalkRadioGroup(const nsAString& aName, nsIRadioVisitor* aVisitor,
524 bool aFlushContent) final {
525 return DocumentOrShadowRoot::WalkRadioGroup(aName, aVisitor, aFlushContent);
528 void SetCurrentRadioButton(const nsAString& aName,
529 HTMLInputElement* aRadio) final {
530 DocumentOrShadowRoot::SetCurrentRadioButton(aName, aRadio);
533 HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) final {
534 return DocumentOrShadowRoot::GetCurrentRadioButton(aName);
537 NS_IMETHOD
538 GetNextRadioButton(const nsAString& aName, const bool aPrevious,
539 HTMLInputElement* aFocusedRadio,
540 HTMLInputElement** aRadioOut) final {
541 return DocumentOrShadowRoot::GetNextRadioButton(aName, aPrevious,
542 aFocusedRadio, aRadioOut);
544 void AddToRadioGroup(const nsAString& aName, HTMLInputElement* aRadio) final {
545 DocumentOrShadowRoot::AddToRadioGroup(aName, aRadio);
547 void RemoveFromRadioGroup(const nsAString& aName,
548 HTMLInputElement* aRadio) final {
549 DocumentOrShadowRoot::RemoveFromRadioGroup(aName, aRadio);
551 uint32_t GetRequiredRadioCount(const nsAString& aName) const final {
552 return DocumentOrShadowRoot::GetRequiredRadioCount(aName);
554 void RadioRequiredWillChange(const nsAString& aName,
555 bool aRequiredAdded) final {
556 DocumentOrShadowRoot::RadioRequiredWillChange(aName, aRequiredAdded);
558 bool GetValueMissingState(const nsAString& aName) const final {
559 return DocumentOrShadowRoot::GetValueMissingState(aName);
561 void SetValueMissingState(const nsAString& aName, bool aValue) final {
562 return DocumentOrShadowRoot::SetValueMissingState(aName, aValue);
565 nsIPrincipal* EffectiveStoragePrincipal() const;
567 // nsIScriptObjectPrincipal
568 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
570 nsIPrincipal* GetEffectiveStoragePrincipal() final {
571 return EffectiveStoragePrincipal();
574 // You should probably not be using this function, since it performs no checks
575 // to ensure that the partitioned principal should really be used here. It is
576 // only designed to be used in very specific circumstances, such as when
577 // inheriting the document/storage principal.
578 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
580 void ClearActiveStoragePrincipal() { mActiveStoragePrincipal = nullptr; }
582 nsIPrincipal* GetContentBlockingAllowListPrincipal() const {
583 return mContentBlockingAllowListPrincipal;
586 // EventTarget
587 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
588 EventListenerManager* GetOrCreateListenerManager() override;
589 EventListenerManager* GetExistingListenerManager() const override;
591 // This helper class must be set when we dispatch beforeunload and unload
592 // events in order to avoid unterminate sync XHRs.
593 class MOZ_RAII PageUnloadingEventTimeStamp {
594 RefPtr<Document> mDocument;
595 bool mSet;
597 public:
598 explicit PageUnloadingEventTimeStamp(Document* aDocument)
599 : mDocument(aDocument), mSet(false) {
600 MOZ_ASSERT(aDocument);
601 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
602 mDocument->SetPageUnloadingEventTimeStamp();
603 mSet = true;
607 ~PageUnloadingEventTimeStamp() {
608 if (mSet) {
609 mDocument->CleanUnloadEventsTimeStamp();
615 * Let the document know that we're starting to load data into it.
616 * @param aCommand The parser command. Must not be null.
617 * XXXbz It's odd to have that here.
618 * @param aChannel The channel the data will come from. The channel must be
619 * able to report its Content-Type.
620 * @param aLoadGroup The loadgroup this document should use from now on.
621 * Note that the document might not be the only thing using
622 * this loadgroup.
623 * @param aContainer The container this document is in. This may be null.
624 * XXXbz maybe we should make it more explicit (eg make the
625 * container an nsIWebNavigation or nsIDocShell or
626 * something)?
627 * @param [out] aDocListener the listener to pump data from the channel into.
628 * Generally this will be the parser this document
629 * sets up, or some sort of data-handler for media
630 * documents.
631 * @param aReset whether the document should call Reset() on itself. If this
632 * is false, the document will NOT set its principal to the
633 * channel's owner, will not clear any event listeners that are
634 * already set on it, etc.
635 * @param aSink The content sink to use for the data. If this is null and
636 * the document needs a content sink, it will create one based
637 * on whatever it knows about the data it's going to load.
638 * This MUST be null if the underlying document is an HTML
639 * document. Even in the XML case, please don't add new calls
640 * with non-null sink.
642 * Once this has been called, the document will return false for
643 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
644 * sure this happens is the responsibility of the caller of
645 * StartDocumentLoad().
647 * This function has an implementation, and does some setup, but does NOT set
648 * *aDocListener; this is the job of subclasses.
650 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
651 nsILoadGroup* aLoadGroup,
652 nsISupports* aContainer,
653 nsIStreamListener** aDocListener,
654 bool aReset,
655 nsIContentSink* aSink = nullptr) = 0;
656 void StopDocumentLoad();
658 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
659 virtual bool SuppressParserErrorElement() { return false; }
661 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
662 virtual bool SuppressParserErrorConsoleMessages() { return false; }
664 // nsINode
665 bool IsNodeOfType(uint32_t aFlags) const final;
666 nsresult InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
667 bool aNotify) override;
668 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
669 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
670 return NS_ERROR_NOT_IMPLEMENTED;
672 nsresult CloneDocHelper(Document* clone) const;
674 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
677 * Signal that the document title may have changed
678 * (see Document::GetTitle).
679 * @param aBoundTitleElement true if an HTML or SVG <title> element
680 * has just been bound to the document.
682 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
685 * Return the URI for the document. May return null. If it ever stops being
686 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
687 * also never return null.
689 * The value returned corresponds to the "document's address" in
690 * HTML5. As such, it may change over the lifetime of the document, for
691 * instance as a result of the user navigating to a fragment identifier on
692 * the page, or as a result to a call to pushState() or replaceState().
694 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
696 nsIURI* GetDocumentURI() const { return mDocumentURI; }
699 * Return the original URI of the document. This is the same as the
700 * document's URI unless that has changed from its original value (for
701 * example, due to history.pushState() or replaceState() being invoked on the
702 * document).
704 * This method corresponds to the "creation URL" in HTML5 and, once set,
705 * doesn't change over the lifetime of the document.
707 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
709 nsIURI* GetOriginalURI() const { return mOriginalURI; }
712 * Return the base domain of the document. This has been computed using
713 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
714 * checks. When the URI of the document changes, this value is recomputed.
716 nsCString GetBaseDomain() const { return mBaseDomain; }
719 * Set the URI for the document. This also sets the document's original URI,
720 * if it's null.
722 void SetDocumentURI(nsIURI* aURI);
725 * Set the URI for the document loaded via XHR, when accessed from
726 * chrome privileged script.
728 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
731 * Set the base URI for the document loaded via XHR, when accessed from
732 * chrome privileged script.
734 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
737 * The CSP in general is stored in the ClientInfo, but we also cache
738 * the CSP on the document so subresources loaded within a document
739 * can query that cached CSP instead of having to deserialize the CSP
740 * from the Client.
742 * Please note that at the time of CSP parsing the Client is not
743 * available yet, hence we sync CSP of document and Client when the
744 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
746 nsIContentSecurityPolicy* GetCsp() const;
747 void SetCsp(nsIContentSecurityPolicy* aCSP);
749 nsIContentSecurityPolicy* GetPreloadCsp() const;
750 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
752 void GetCspJSON(nsString& aJSON);
755 * Set referrer policy and upgrade-insecure-requests flags
757 void ApplySettingsFromCSP(bool aSpeculative);
759 already_AddRefed<nsIParser> CreatorParserOrNull() {
760 nsCOMPtr<nsIParser> parser = mParser;
761 return parser.forget();
765 * ReferrerInfo getter for Document.webidl.
767 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
769 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
771 nsIReferrerInfo* GetPreloadReferrerInfo() const {
772 return mPreloadReferrerInfo;
775 * Return the referrer policy of the document. Return "default" if there's no
776 * valid meta referrer tag found in the document.
777 * Referrer policy should be inherited from parent if the iframe is srcdoc
779 ReferrerPolicyEnum GetReferrerPolicy() const;
782 * GetReferrerPolicy() for Document.webidl.
784 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
787 * If true, this flag indicates that all mixed content subresource
788 * loads for this document (and also embeded browsing contexts) will
789 * be blocked.
791 bool GetBlockAllMixedContent(bool aPreload) const {
792 if (aPreload) {
793 return mBlockAllMixedContentPreloads;
795 return mBlockAllMixedContent;
799 * If true, this flag indicates that all subresource loads for this
800 * document need to be upgraded from http to https.
801 * This flag becomes true if the CSP of the document itself, or any
802 * of the document's ancestors up to the toplevel document makes use
803 * of the CSP directive 'upgrade-insecure-requests'.
805 bool GetUpgradeInsecureRequests(bool aPreload) const {
806 if (aPreload) {
807 return mUpgradeInsecurePreloads;
809 return mUpgradeInsecureRequests;
812 void SetReferrerInfo(nsIReferrerInfo* aReferrerInfo) {
813 mReferrerInfo = aReferrerInfo;
817 * Referrer policy from <meta name="referrer" content=`policy`>
818 * will have higher priority than referrer policy from Referrer-Policy
819 * header. So override the old ReferrerInfo if we get one from meta
821 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
822 bool aPreload) {
823 ReferrerPolicyEnum policy =
824 ReferrerInfo::ReferrerPolicyFromMetaString(aMetaReferrer);
825 // The empty string "" corresponds to no referrer policy, causing a fallback
826 // to a referrer policy defined elsewhere.
827 if (policy == ReferrerPolicy::_empty) {
828 return;
831 MOZ_ASSERT(mReferrerInfo);
832 MOZ_ASSERT(mPreloadReferrerInfo);
834 if (aPreload) {
835 mPreloadReferrerInfo =
836 static_cast<mozilla::dom::ReferrerInfo*>((mPreloadReferrerInfo).get())
837 ->CloneWithNewPolicy(policy);
838 } else {
839 mReferrerInfo =
840 static_cast<mozilla::dom::ReferrerInfo*>((mReferrerInfo).get())
841 ->CloneWithNewPolicy(policy);
846 * Set the principals responsible for this document. Chances are, you do not
847 * want to be using this.
849 void SetPrincipals(nsIPrincipal* aPrincipal,
850 nsIPrincipal* aPartitionedPrincipal);
853 * Returns true if exempt from HTTPS-Only Mode upgrade.
855 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
858 * Return the LoadGroup for the document. May return null.
860 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
861 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
862 return group.forget();
866 * Return the fallback base URL for this document, as defined in the HTML
867 * specification. Note that this can return null if there is no document URI.
869 * XXXbz: This doesn't implement the bits for about:blank yet.
871 nsIURI* GetFallbackBaseURI() const {
872 if (mIsSrcdocDocument && mParentDocument) {
873 return mParentDocument->GetDocBaseURI();
875 return mDocumentURI;
879 * Return the referrer from document URI as defined in the Referrer Policy
880 * specification.
881 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
882 * While document is an iframe srcdoc document, let document be document's
883 * browsing context's browsing context container's node document.
884 * Then referrer should be document's URL
887 nsIURI* GetDocumentURIAsReferrer() const {
888 if (mIsSrcdocDocument && mParentDocument) {
889 return mParentDocument->GetDocumentURIAsReferrer();
891 return mDocumentURI;
895 * Return the base URI for relative URIs in the document (the document uri
896 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
897 * returned URI could be null if there is no document URI. If the document is
898 * a srcdoc document and has no explicit base URL, return the parent
899 * document's base URL.
901 nsIURI* GetDocBaseURI() const {
902 if (mDocumentBaseURI) {
903 return mDocumentBaseURI;
905 return GetFallbackBaseURI();
908 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
910 void SetBaseURI(nsIURI* aURI);
913 * Resolves a URI based on the document's base URI.
915 Result<OwningNonNull<nsIURI>, nsresult> ResolveWithBaseURI(
916 const nsAString& aURI);
919 * Return the URL data which style system needs for resolving url value.
920 * This method attempts to use the cached object in mCachedURLData, but
921 * if the base URI, document URI, or principal has changed since last
922 * call to this function, or the function is called the first time for
923 * the document, a new one is created.
925 URLExtraData* DefaultStyleAttrURLData();
928 * Get/Set the base target of a link in a document.
930 void GetBaseTarget(nsAString& aBaseTarget) const {
931 aBaseTarget = mBaseTarget;
934 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
937 * Return a standard name for the document's character set.
939 NotNull<const Encoding*> GetDocumentCharacterSet() const {
940 return mCharacterSet;
944 * Set the document's character encoding.
946 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
948 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
950 // This method MUST be called before SetDocumentCharacterSet if
951 // you're planning to call both.
952 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
953 mCharacterSetSource = aCharsetSource;
957 * Get the Content-Type of this document.
959 void GetContentType(nsAString& aContentType);
962 * Set the Content-Type of this document.
964 virtual void SetContentType(const nsAString& aContentType);
967 * Return the language of this document.
969 void GetContentLanguage(nsAString& aContentLanguage) const {
970 CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
973 // The states BidiEnabled and MathMLEnabled should persist across multiple
974 // views (screen, print) of the same document.
977 * Check if the document contains bidi data.
978 * If so, we have to apply the Unicode Bidi Algorithm.
980 bool GetBidiEnabled() const { return mBidiEnabled; }
983 * Indicate the document contains bidi data.
984 * Currently, we cannot disable bidi, because once bidi is enabled,
985 * it affects a frame model irreversibly, and plays even though
986 * the document no longer contains bidi data.
988 void SetBidiEnabled() { mBidiEnabled = true; }
990 void SetMathMLEnabled() { mMathMLEnabled = true; }
993 * Ask this document whether it's the initial document in its window.
995 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
998 * Tell this document that it's the initial document in its window. See
999 * comments on mIsInitialDocumentInWindow for when this should be called.
1001 void SetIsInitialDocument(bool aIsInitialDocument);
1003 void SetLoadedAsData(bool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
1006 * Normally we assert if a runnable labeled with one DocGroup touches data
1007 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1008 * means that we can touch that document from any DocGroup without asserting.
1010 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1013 * Get the bidi options for this document.
1014 * @see nsBidiUtils.h
1016 uint32_t GetBidiOptions() const { return mBidiOptions; }
1019 * Set the bidi options for this document. This just sets the bits;
1020 * callers are expected to take action as needed if they want this
1021 * change to actually change anything immediately.
1022 * @see nsBidiUtils.h
1024 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1027 * Set CSP flag for this document.
1029 void SetHasCSP(bool aHasCSP) { mHasCSP = aHasCSP; }
1032 * Set unsafe-inline CSP flag for this document.
1034 void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP) {
1035 mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
1039 * Set unsafe-eval CSP flag for this document.
1041 void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP) {
1042 mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
1046 * Returns true if the document holds a CSP
1047 * delivered through an HTTP Header.
1049 bool GetHasCSPDeliveredThroughHeader() {
1050 return mHasCSPDeliveredThroughHeader;
1054 * Return a promise which resolves to the content blocking events.
1056 typedef MozPromise<uint32_t, bool, true> GetContentBlockingEventsPromise;
1057 MOZ_MUST_USE RefPtr<GetContentBlockingEventsPromise>
1058 GetContentBlockingEvents();
1061 * Get the sandbox flags for this document.
1062 * @see nsSandboxFlags.h for the possible flags
1064 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1066 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1067 return mEmbedderPolicy;
1070 void SetEmbedderPolicy(
1071 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1072 mEmbedderPolicy = aCOEP;
1076 * Get string representation of sandbox flags (null if no flags are set)
1078 void GetSandboxFlagsAsString(nsAString& aFlags);
1081 * Set the sandbox flags for this document.
1082 * @see nsSandboxFlags.h for the possible flags
1084 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1087 * Called when the document was decoded as UTF-8 and decoder encountered no
1088 * errors.
1090 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1093 * Called to disable client access to cookies through the document.cookie API
1094 * from user JavaScript code.
1096 void DisableCookieAccess() { mDisableCookieAccess = true; }
1098 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1099 bool LinkHandlingEnabled() { return mLinksEnabled; }
1102 * Set compatibility mode for this document
1104 void SetCompatibilityMode(nsCompatibility aMode);
1107 * Called to disable client access to document.write() API from user
1108 * JavaScript code.
1110 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1113 * Whether a document.write() call is in progress.
1115 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1118 * Access HTTP header data (this may also get set from other
1119 * sources, like HTML META tags).
1121 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1122 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1125 * Create a new presentation shell that will use aContext for its
1126 * presentation context (presentation contexts <b>must not</b> be
1127 * shared among multiple presentation shells). The caller of this
1128 * method is responsible for calling BeginObservingDocument() on the
1129 * presshell if the presshell should observe document mutations.
1131 already_AddRefed<PresShell> CreatePresShell(nsPresContext* aContext,
1132 nsViewManager* aViewManager);
1133 void DeletePresShell();
1135 PresShell* GetPresShell() const {
1136 return GetBFCacheEntry() ? nullptr : mPresShell;
1139 inline PresShell* GetObservingPresShell() const;
1141 // Return whether the presshell for this document is safe to flush.
1142 bool IsSafeToFlush() const;
1144 inline nsPresContext* GetPresContext() const;
1146 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1148 // Instead using this method, what you probably want is
1149 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1150 void DisallowBFCaching() {
1151 NS_ASSERTION(!mBFCacheEntry, "We're already in the bfcache!");
1152 mBFCacheDisallowed = true;
1155 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1157 // Accepts null to clear the BFCache entry too.
1158 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1160 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1162 // Removes this document from the BFCache, if it is cached, and returns
1163 // true if it was.
1164 bool RemoveFromBFCacheSync();
1167 * Return the parent document of this document. Will return null
1168 * unless this document is within a compound document and has a
1169 * parent. Note that this parent chain may cross chrome boundaries.
1171 Document* GetInProcessParentDocument() const { return mParentDocument; }
1174 * Set the parent document of this document.
1176 void SetParentDocument(Document* aParent) {
1177 mParentDocument = aParent;
1178 if (aParent) {
1179 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1180 if (!mIsDevToolsDocument) {
1181 mIsDevToolsDocument = mParentDocument->IsDevToolsDocument();
1187 * Are plugins allowed in this document ?
1189 bool GetAllowPlugins();
1192 * Set the sub document for aContent to aSubDoc.
1194 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1197 * Get the sub document for aContent
1199 Document* GetSubDocumentFor(nsIContent* aContent) const;
1202 * Find the content node for which aDocument is a sub document.
1204 Element* FindContentForSubDocument(Document* aDocument) const;
1207 * Return the doctype for this document.
1209 DocumentType* GetDoctype() const;
1212 * Return the root element for this document.
1214 Element* GetRootElement() const;
1216 Selection* GetSelection(ErrorResult& aRv);
1218 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1219 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1221 bool UseRegularPrincipal() const;
1224 * Gets the event target to dispatch key events to if there is no focused
1225 * content in the document.
1227 virtual Element* GetUnfocusedKeyEventTarget();
1230 * Retrieve information about the viewport as a data structure.
1231 * This will return information in the viewport META data section
1232 * of the document. This can be used in lieu of ProcessViewportInfo(),
1233 * which places the viewport information in the document header instead
1234 * of returning it directly.
1236 * @param aDisplaySize size of the on-screen display area for this
1237 * document, in device pixels.
1239 * NOTE: If the site is optimized for mobile (via the doctype), this
1240 * will return viewport information that specifies default information.
1242 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1244 void AddMetaViewportElement(HTMLMetaElement* aElement,
1245 ViewportMetaData&& aData);
1246 void RemoveMetaViewportElement(HTMLMetaElement* aElement);
1248 // Returns a ViewportMetaData for this document.
1249 ViewportMetaData GetViewportMetaData() const;
1252 * True iff this doc will ignore manual character encoding overrides.
1254 virtual bool WillIgnoreCharsetOverride() { return true; }
1257 * Return whether the document was created by a srcdoc iframe.
1259 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1262 * Sets whether the document was created by a srcdoc iframe.
1264 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1265 mIsSrcdocDocument = aIsSrcdocDocument;
1269 * Gets the srcdoc string from within the channel (assuming both exist).
1270 * Returns a void string if this isn't a srcdoc document or if
1271 * the channel has not been set.
1273 nsresult GetSrcdocData(nsAString& aSrcdocData);
1275 already_AddRefed<AnonymousContent> InsertAnonymousContent(
1276 Element& aElement, ErrorResult& aError);
1277 void RemoveAnonymousContent(AnonymousContent& aContent, ErrorResult& aError);
1279 * If aNode is a descendant of anonymous content inserted by
1280 * InsertAnonymousContent, this method returns the root element of the
1281 * inserted anonymous content (in other words, the clone of the aElement
1282 * that was passed to InsertAnonymousContent).
1284 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1285 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1286 return mAnonymousContents;
1289 TimeStamp GetPageUnloadingEventTimeStamp() const {
1290 if (!mParentDocument) {
1291 return mPageUnloadingEventTimeStamp;
1294 TimeStamp parentTimeStamp(
1295 mParentDocument->GetPageUnloadingEventTimeStamp());
1296 if (parentTimeStamp.IsNull()) {
1297 return mPageUnloadingEventTimeStamp;
1300 if (!mPageUnloadingEventTimeStamp ||
1301 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1302 return parentTimeStamp;
1305 return mPageUnloadingEventTimeStamp;
1308 void NotifyLayerManagerRecreated();
1311 * Add an SVG element to the list of elements that need
1312 * their mapped attributes resolved to a Servo declaration block.
1314 * These are weak pointers, please manually unschedule them when an element
1315 * is removed.
1317 void ScheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1318 mLazySVGPresElements.PutEntry(aSVG);
1321 // Unschedule an element scheduled by ScheduleFrameRequestCallback (e.g. for
1322 // when it is destroyed)
1323 void UnscheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1324 mLazySVGPresElements.RemoveEntry(aSVG);
1327 // Resolve all SVG pres attrs scheduled in ScheduleSVGForPresAttrEvaluation
1328 void ResolveScheduledSVGPresAttrs();
1330 Maybe<ClientInfo> GetClientInfo() const;
1331 Maybe<ClientState> GetClientState() const;
1332 Maybe<ServiceWorkerDescriptor> GetController() const;
1334 // Returns the size of the mBlockedNodesByClassifier array.
1336 // This array contains nodes that have been blocked to prevent user tracking,
1337 // fingerprinting, cryptomining, etc. They most likely have had their
1338 // nsIChannel canceled by the URL classifier (Safebrowsing).
1340 // A script can subsequently use GetBlockedNodesByClassifier()
1341 // to get a list of references to these nodes.
1343 // Note:
1344 // This expresses how many tracking nodes have been blocked for this document
1345 // since its beginning, not how many of them are still around in the DOM tree.
1346 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1347 // array but they are not removed when those nodes are removed from the tree
1348 // or even garbage collected.
1349 long BlockedNodeByClassifierCount() const {
1350 return mBlockedNodesByClassifier.Length();
1354 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1356 // This array contains nodes that have been blocked to prevent
1357 // user tracking. They most likely have had their nsIChannel
1358 // canceled by the URL classifier (Safebrowsing).
1360 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1362 // Helper method that returns true if the document has storage-access sandbox
1363 // flag.
1364 bool StorageAccessSandboxed() const;
1366 // Helper method that returns true if storage access API is enabled and
1367 // the passed flag has storage-access sandbox flag.
1368 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1370 // Returns the cookie jar settings for this and sub contexts.
1371 nsICookieJarSettings* CookieJarSettings();
1373 // Returns whether this document has the storage access permission.
1374 bool HasStorageAccessPermissionGranted();
1376 // Increments the document generation.
1377 inline void Changed() { ++mGeneration; }
1379 // Returns the current generation.
1380 inline int32_t GetGeneration() const { return mGeneration; }
1382 // Adds cached sizes values to aSizes if there's any
1383 // cached value and if the document generation hasn't
1384 // changed since the cache was created.
1385 // Returns true if sizes were added.
1386 bool GetCachedSizes(nsTabSizes* aSizes);
1388 // Sets the cache sizes for the current generation.
1389 void SetCachedSizes(nsTabSizes* aSizes);
1392 * Should be called when an element's editable changes as a result of
1393 * changing its contentEditable attribute/property.
1395 * The change should be +1 if the contentEditable attribute/property was
1396 * changed to true, -1 if it was changed to false.
1398 void ChangeContentEditableCount(Element*, int32_t aChange);
1399 void DeferredContentEditableCountChange(Element*);
1401 enum class EditingState : int8_t {
1402 eTearingDown = -2,
1403 eSettingUp = -1,
1404 eOff = 0,
1405 eDesignMode,
1406 eContentEditable
1410 * Returns the editing state of the document (not editable, contentEditable or
1411 * designMode).
1413 EditingState GetEditingState() const { return mEditingState; }
1416 * Returns whether the document is editable.
1418 bool IsEditingOn() const {
1419 return GetEditingState() == EditingState::eDesignMode ||
1420 GetEditingState() == EditingState::eContentEditable;
1423 class MOZ_STACK_CLASS nsAutoEditingState {
1424 public:
1425 nsAutoEditingState(Document* aDoc, EditingState aState)
1426 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1427 aDoc->mEditingState = aState;
1429 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1431 private:
1432 RefPtr<Document> mDoc;
1433 EditingState mSavedState;
1435 friend class nsAutoEditingState;
1438 * Set the editing state of the document. Don't use this if you want
1439 * to enable/disable editing, call EditingStateChanged() or
1440 * SetDesignMode().
1442 void SetEditingState(EditingState aState) { mEditingState = aState; }
1445 * Called when this Document's editor is destroyed.
1447 void TearingDownEditor();
1449 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1451 // Gets the next form number.
1453 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1454 // parser inserted form element.
1455 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1457 // Gets the next form control number.
1459 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1460 // parser inserted form control element.
1461 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1463 PreloadService& Preloads() { return mPreloadService; }
1465 bool HasThirdPartyChannel();
1467 bool ShouldIncludeInTelemetry(bool aAllowExtensionURIs);
1469 protected:
1470 friend class nsUnblockOnloadEvent;
1472 nsresult InitCSP(nsIChannel* aChannel);
1473 nsresult InitCOEP(nsIChannel* aChannel);
1475 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1477 nsresult InitReferrerInfo(nsIChannel* aChannel);
1479 void PostUnblockOnloadEvent();
1481 void DoUnblockOnload();
1483 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1485 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1486 NotNull<const Encoding*>& aEncoding,
1487 nsHtml5TreeOpExecutor* aExecutor);
1489 void DispatchContentLoadedEvents();
1491 void DispatchPageTransition(EventTarget* aDispatchTarget,
1492 const nsAString& aType, bool aInFrameSwap,
1493 bool aPersisted, bool aOnlySystemGroup);
1495 // Call this before the document does something that will unbind all content.
1496 // That will stop us from doing a lot of work as each element is removed.
1497 void DestroyElementMaps();
1499 Element* GetRootElementInternal() const;
1500 void DoNotifyPossibleTitleChange();
1502 void SetPageUnloadingEventTimeStamp() {
1503 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1504 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1507 void CleanUnloadEventsTimeStamp() {
1508 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1509 mPageUnloadingEventTimeStamp = TimeStamp();
1513 * Clears any Servo element data stored on Elements in the document.
1515 void ClearStaleServoData();
1518 * Returns the top window root from the outer window.
1520 already_AddRefed<nsPIWindowRoot> GetWindowRoot();
1523 * Do the tree-disconnection that ResetToURI and document.open need to do.
1525 void DisconnectNodeTree();
1528 * Like IsEditingOn(), but will flush as needed first.
1530 bool IsEditingOnAfterFlush();
1533 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1534 * "CheckKeyPressEventModel" event to check whether we should dispatch
1535 * keypress events in confluent model or split model. This should be
1536 * called only when mEditingState is changed to eDesignMode or
1537 * eConentEditable at first time.
1539 void MaybeDispatchCheckKeyPressEventModelEvent();
1541 /* Midas implementation */
1542 nsCommandManager* GetMidasCommandManager();
1544 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1546 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1547 // of places, and I'm pretty sure the exact ExecCommand call it
1548 // makes cannot actually run script.
1549 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1551 void MaybeEditingStateChanged();
1553 private:
1554 class SelectorCacheKey {
1555 public:
1556 explicit SelectorCacheKey(const nsAString& aString) : mKey(aString) {
1557 MOZ_COUNT_CTOR(SelectorCacheKey);
1560 nsString mKey;
1561 nsExpirationState mState;
1563 nsExpirationState* GetExpirationState() { return &mState; }
1565 MOZ_COUNTED_DTOR(SelectorCacheKey)
1568 class SelectorCacheKeyDeleter;
1570 public:
1571 class SelectorCache final : public nsExpirationTracker<SelectorCacheKey, 4> {
1572 public:
1573 using SelectorList = UniquePtr<RawServoSelectorList>;
1575 explicit SelectorCache(nsIEventTarget* aEventTarget);
1577 void CacheList(const nsAString& aSelector, SelectorList aSelectorList) {
1578 MOZ_ASSERT(NS_IsMainThread());
1579 SelectorCacheKey* key = new SelectorCacheKey(aSelector);
1580 mTable.Put(key->mKey, std::move(aSelectorList));
1581 AddObject(key);
1584 void NotifyExpired(SelectorCacheKey* aSelector) final;
1586 // We do not call MarkUsed because it would just slow down lookups and
1587 // because we're OK expiring things after a few seconds even if they're
1588 // being used. Returns whether we actually had an entry for aSelector.
1590 // If we have an entry and the selector list returned has a null
1591 // RawServoSelectorList*, that indicates that aSelector has already been
1592 // parsed and is not a syntactically valid selector.
1593 SelectorList* GetList(const nsAString& aSelector) {
1594 return mTable.GetValue(aSelector);
1597 ~SelectorCache();
1599 private:
1600 nsDataHashtable<nsStringHashKey, SelectorList> mTable;
1603 SelectorCache& GetSelectorCache() {
1604 if (!mSelectorCache) {
1605 mSelectorCache =
1606 MakeUnique<SelectorCache>(EventTargetFor(TaskCategory::Other));
1608 return *mSelectorCache;
1610 // Get the root <html> element, or return null if there isn't one (e.g.
1611 // if the root isn't <html>)
1612 Element* GetHtmlElement() const;
1613 // Returns the first child of GetHtmlContent which has the given tag,
1614 // or nullptr if that doesn't exist.
1615 Element* GetHtmlChildElement(nsAtom* aTag);
1616 // Get the canonical <body> element, or return null if there isn't one (e.g.
1617 // if the root isn't <html> or if the <body> isn't there)
1618 HTMLBodyElement* GetBodyElement();
1619 // Get the canonical <head> element, or return null if there isn't one (e.g.
1620 // if the root isn't <html> or if the <head> isn't there)
1621 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1622 // Get the "body" in the sense of document.body: The first <body> or
1623 // <frameset> that's a child of a root <html>
1624 nsGenericHTMLElement* GetBody();
1625 // Set the "body" in the sense of document.body.
1626 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1627 // Get the "head" element in the sense of document.head.
1628 HTMLSharedElement* GetHead();
1630 ServoStyleSet* StyleSetForPresShellOrMediaQueryEvaluation() const {
1631 return mStyleSet.get();
1634 // ShadowRoot has APIs that can change styles. This notifies the shell that
1635 // stlyes applicable in the shadow tree have potentially changed.
1636 void RecordShadowStyleChange(ShadowRoot&);
1638 // Needs to be called any time the applicable style can has changed, in order
1639 // to schedule a style flush and setup all the relevant state.
1640 void ApplicableStylesChanged();
1642 // Whether we filled the style set with any style sheet. Only meant to be used
1643 // from DocumentOrShadowRoot::Traverse.
1644 bool StyleSetFilled() const { return mStyleSetFilled; }
1647 * Accessors to the collection of stylesheets owned by this document.
1648 * Style sheets are ordered, most significant last.
1651 void InsertSheetAt(size_t aIndex, StyleSheet&);
1654 * Add a stylesheet to the document
1656 * TODO(emilio): This is only used by parts of editor that are no longer in
1657 * use by m-c or c-c, so remove.
1659 void AddStyleSheet(StyleSheet* aSheet) {
1660 MOZ_ASSERT(aSheet);
1661 InsertSheetAt(SheetCount(), *aSheet);
1665 * Notify the document that the applicable state of the sheet changed
1666 * and that observers should be notified and style sets updated
1668 void StyleSheetApplicableStateChanged(StyleSheet&);
1670 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1672 enum additionalSheetType {
1673 eAgentSheet,
1674 eUserSheet,
1675 eAuthorSheet,
1676 AdditionalSheetTypeCount
1679 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1680 nsIURI* aSheetURI);
1681 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1682 StyleSheet* aSheet);
1683 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1685 StyleSheet* GetFirstAdditionalAuthorSheet() {
1686 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1690 * Returns the index that aSheet should be inserted at to maintain document
1691 * ordering.
1693 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1696 * Get this document's CSSLoader. This is guaranteed to not return null.
1698 css::Loader* CSSLoader() const { return mCSSLoader; }
1701 * Get this document's StyleImageLoader. This is guaranteed to not return
1702 * null.
1704 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1707 * Get the channel that was passed to StartDocumentLoad or Reset for this
1708 * document. Note that this may be null in some cases (eg if
1709 * StartDocumentLoad or Reset were never called)
1711 nsIChannel* GetChannel() const { return mChannel; }
1714 * Get this document's attribute stylesheet. May return null if
1715 * there isn't one.
1717 nsHTMLStyleSheet* GetAttributeStyleSheet() const { return mAttrStyleSheet; }
1720 * Get this document's inline style sheet. May return null if there
1721 * isn't one
1723 nsHTMLCSSStyleSheet* GetInlineStyleSheet() const {
1724 return mStyleAttrStyleSheet;
1727 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1730 * Get/set the object from which the context for the event/script handling can
1731 * be got. Normally GetScriptHandlingObject() returns the same object as
1732 * GetScriptGlobalObject(), but if the document is loaded as data,
1733 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1734 * aHasHadScriptHandlingObject is set true if document has had the object
1735 * for event/script handling. Do not process any events/script if the method
1736 * returns null, but aHasHadScriptHandlingObject is true.
1738 nsIScriptGlobalObject* GetScriptHandlingObject(
1739 bool& aHasHadScriptHandlingObject) const {
1740 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1741 return mScriptGlobalObject ? mScriptGlobalObject.get()
1742 : GetScriptHandlingObjectInternal();
1744 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1747 * Get the object that is used as the scope for all of the content
1748 * wrappers whose owner document is this document. Unlike the script global
1749 * object, this will only return null when the global object for this
1750 * document is truly gone. Use this object when you're trying to find a
1751 * content wrapper in XPConnect.
1753 nsIGlobalObject* GetScopeObject() const;
1754 void SetScopeObject(nsIGlobalObject* aGlobal);
1757 * Return the window containing the document (the outer window).
1759 nsPIDOMWindowOuter* GetWindow() const {
1760 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1763 bool IsInBackgroundWindow() const {
1764 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1765 return outer && outer->IsBackground();
1769 * Return the inner window used as the script compilation scope for
1770 * this document. If you're not absolutely sure you need this, use
1771 * GetWindow().
1773 nsPIDOMWindowInner* GetInnerWindow() const {
1774 return mRemovedFromDocShell ? nullptr : mWindow;
1778 * Return the outer window ID.
1780 uint64_t OuterWindowID() const {
1781 nsPIDOMWindowOuter* window = GetWindow();
1782 return window ? window->WindowID() : 0;
1786 * Return the inner window ID.
1788 uint64_t InnerWindowID() const {
1789 nsPIDOMWindowInner* window = GetInnerWindow();
1790 return window ? window->WindowID() : 0;
1794 * Return WindowGlobalChild that is associated with the inner window.
1796 WindowGlobalChild* GetWindowGlobalChild() {
1797 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1798 : nullptr;
1802 * Return WindowContext associated with the inner window.
1804 WindowContext* GetWindowContext() const {
1805 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1808 bool IsTopLevelWindowInactive() const;
1811 * Get the script loader for this document
1813 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1816 * Add/Remove an element to the document's id and name hashes
1818 void AddToIdTable(Element* aElement, nsAtom* aId);
1819 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1820 void AddToNameTable(Element* aElement, nsAtom* aName);
1821 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1824 * Returns all elements in the top layer in the insertion order.
1826 nsTArray<Element*> GetTopLayer() const;
1829 * Asynchronously requests that the document make aElement the fullscreen
1830 * element, and move into fullscreen mode. The current fullscreen element
1831 * (if any) is pushed onto the top layer, and it can be
1832 * returned to fullscreen status by calling RestorePreviousFullscreenState().
1834 * Note that requesting fullscreen in a document also makes the element which
1835 * contains this document in this document's parent document fullscreen. i.e.
1836 * the <iframe> or <browser> that contains this document is also mode
1837 * fullscreen. This happens recursively in all ancestor documents.
1839 void AsyncRequestFullscreen(UniquePtr<FullscreenRequest>);
1841 // Do the "fullscreen element ready check" from the fullscreen spec.
1842 // It returns true if the given element is allowed to go into fullscreen.
1843 // It is responsive to dispatch "fullscreenerror" event when necessary.
1844 bool FullscreenElementReadyCheck(FullscreenRequest&);
1846 // This is called asynchronously by Document::AsyncRequestFullscreen()
1847 // to move this document into fullscreen mode if allowed.
1848 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1849 bool applyFullScreenDirectly = false);
1851 private:
1852 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1853 bool applyFullScreenDirectly);
1854 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1855 bool applyFullScreenDirectly);
1857 public:
1858 // Removes all the elements with fullscreen flag set from the top layer, and
1859 // clears their fullscreen flag.
1860 void CleanupFullscreenState();
1862 // Pushes aElement onto the top layer
1863 void TopLayerPush(Element* aElement);
1865 // Removes the topmost element which have aPredicate return true from the top
1866 // layer. The removed element, if any, is returned.
1867 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicateFunc);
1869 // Pops the fullscreen element from the top layer and clears its
1870 // fullscreen flag.
1871 void UnsetFullscreenElement();
1873 // Pushes the given element into the top of top layer and set fullscreen
1874 // flag.
1875 void SetFullscreenElement(Element* aElement);
1877 // Cancel the dialog element if the document is blocked by the dialog
1878 void TryCancelDialog();
1880 void SetBlockedByModalDialog(HTMLDialogElement&);
1882 void UnsetBlockedByModalDialog(HTMLDialogElement&);
1885 * Called when a frame in a child process has entered fullscreen or when a
1886 * fullscreen frame in a child process changes to another origin.
1887 * aFrameElement is the frame element which contains the child-process
1888 * fullscreen document.
1890 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1893 * Called when a frame in a remote child document has rolled back fullscreen
1894 * so that all its top layer are empty; we must continue the
1895 * rollback in this parent process' doc tree branch which is fullscreen.
1896 * Note that only one branch of the document tree can have its documents in
1897 * fullscreen state at one time. We're in inconsistent state if a
1898 * fullscreen document has a parent and that parent isn't fullscreen. We
1899 * preserve this property across process boundaries.
1901 void RemoteFrameFullscreenReverted();
1904 * Restores the previous fullscreen element to fullscreen status. If there
1905 * is no former fullscreen element, this exits fullscreen, moving the
1906 * top-level browser window out of fullscreen mode.
1908 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1911 * Returns true if this document is a fullscreen leaf document, i.e. it
1912 * is in fullscreen mode and has no fullscreen children.
1914 bool IsFullscreenLeaf();
1917 * Returns the document which is at the root of this document's branch
1918 * in the in-process document tree. Returns nullptr if the document isn't
1919 * fullscreen.
1921 Document* GetFullscreenRoot();
1923 size_t CountFullscreenElements() const;
1926 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1927 * in this document.
1929 void SetFullscreenRoot(Document* aRoot);
1932 * Synchronously cleans up the fullscreen state on the given document.
1934 * Calling this without performing fullscreen transition could lead
1935 * to undesired effect (the transition happens after document state
1936 * flips), hence it should only be called either by nsGlobalWindow
1937 * when we have performed the transition, or when it is necessary to
1938 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1939 * should be called instead.
1941 * aDocument must not be null.
1943 static void ExitFullscreenInDocTree(Document* aDocument);
1946 * Ask the document to exit fullscreen state asynchronously.
1948 * Different from ExitFullscreenInDocTree(), this allows the window
1949 * to perform fullscreen transition first if any.
1951 * If aDocument is null, it will exit fullscreen from all documents
1952 * in all windows.
1954 static void AsyncExitFullscreen(Document* aDocument);
1957 * Handles any pending fullscreen in aDocument or its subdocuments.
1959 * Returns whether there is any fullscreen request handled.
1961 static bool HandlePendingFullscreenRequests(Document* aDocument);
1963 void RequestPointerLock(Element* aElement, CallerType);
1964 MOZ_CAN_RUN_SCRIPT bool SetPointerLock(Element* aElement, StyleCursorKind);
1966 MOZ_CAN_RUN_SCRIPT_BOUNDARY
1967 static void UnlockPointer(Document* aDoc = nullptr);
1969 // ScreenOrientation related APIs
1971 void ClearOrientationPendingPromise();
1972 bool SetOrientationPendingPromise(Promise* aPromise);
1973 Promise* GetOrientationPendingPromise() const {
1974 return mOrientationPendingPromise;
1977 //----------------------------------------------------------------------
1979 // Document notification API's
1982 * Add a new observer of document change notifications. Whenever
1983 * content is changed, appended, inserted or removed the observers are
1984 * informed. An observer that is already observing the document must
1985 * not be added without being removed first.
1987 void AddObserver(nsIDocumentObserver* aObserver);
1990 * Remove an observer of document change notifications. This will
1991 * return false if the observer cannot be found.
1993 bool RemoveObserver(nsIDocumentObserver* aObserver);
1995 // Observation hooks used to propagate notifications to document observers.
1996 // BeginUpdate must be called before any batch of modifications of the
1997 // content model or of style data, EndUpdate must be called afterward.
1998 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1999 void BeginUpdate();
2000 void EndUpdate();
2001 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
2003 void BeginLoad();
2004 virtual void EndLoad();
2006 enum ReadyState {
2007 READYSTATE_UNINITIALIZED = 0,
2008 READYSTATE_LOADING = 1,
2009 READYSTATE_INTERACTIVE = 3,
2010 READYSTATE_COMPLETE = 4
2012 // Set the readystate of the document. If aUpdateTimingInformation is true,
2013 // this will record relevant timestamps in the document's performance timing.
2014 // Some consumers (document.open is the only one right now, actually) don't
2015 // want to do that, though.
2016 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2017 ReadyState GetReadyStateEnum() { return mReadyState; }
2019 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2020 ReadyState aNewState);
2022 void NotifyAbortedLoad();
2024 // notify that a content node changed state. This must happen under
2025 // a scriptblocker but NOT within a begin/end update.
2026 void ContentStateChanged(nsIContent* aContent, EventStates aStateMask);
2028 // Update a set of document states that may have changed.
2029 // This should only be called by callers whose state is also reflected in the
2030 // implementation of Document::GetDocumentState.
2032 // aNotify controls whether we notify our DocumentStatesChanged observers.
2033 void UpdateDocumentStates(EventStates aStateMask, bool aNotify);
2035 void ResetDocumentDirection();
2037 // Observation hooks for style data to propagate notifications
2038 // to document observers
2039 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2040 void RuleAdded(StyleSheet&, css::Rule&);
2041 void RuleRemoved(StyleSheet&, css::Rule&);
2042 void SheetCloned(StyleSheet&) {}
2043 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2046 * Flush notifications for this document and its parent documents
2047 * (since those may affect the layout of this one).
2049 void FlushPendingNotifications(FlushType aType);
2052 * Another variant of the above FlushPendingNotifications. This function
2053 * takes a ChangesToFlush to specify whether throttled animations are flushed
2054 * or not.
2055 * If in doublt, use the above FlushPendingNotifications.
2057 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2058 void FlushPendingNotifications(ChangesToFlush aFlush);
2061 * Calls FlushPendingNotifications on any external resources this document
2062 * has. If this document has no external resources or is an external resource
2063 * itself this does nothing. This should only be called with
2064 * aType >= FlushType::Style.
2066 void FlushExternalResources(FlushType aType);
2068 // Triggers an update of <svg:use> element shadow trees.
2069 void UpdateSVGUseElementShadowTrees() {
2070 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2071 return;
2073 DoUpdateSVGUseElementShadowTrees();
2077 * Only to be used inside Gecko, you can't really do anything with the
2078 * pointer outside Gecko anyway.
2080 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2083 * Reset the document using the given channel and loadgroup. This works
2084 * like ResetToURI, but also sets the document's channel to aChannel.
2085 * The principal of the document will be set from the channel.
2087 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2090 * Reset this document to aURI, aLoadGroup, aPrincipal and
2091 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2092 * content principal based on aURI will be used.
2094 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2095 nsIPrincipal* aPrincipal,
2096 nsIPrincipal* aPartitionedPrincipal);
2099 * Set the container (docshell) for this document. Virtual so that
2100 * docshell can call it.
2102 virtual void SetContainer(nsDocShell* aContainer);
2105 * Get the container (docshell) for this document.
2107 nsISupports* GetContainer() const;
2110 * Get the container's load context for this document.
2112 nsILoadContext* GetLoadContext() const;
2115 * Get docshell the for this document.
2117 nsIDocShell* GetDocShell() const;
2120 * Set and get XML declaration. If aVersion is null there is no declaration.
2121 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2122 * was no standalone parameter in the declaration, that it was given as no,
2123 * or that it was given as yes.
2125 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2126 const int32_t aStandalone);
2127 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2128 nsAString& Standalone);
2131 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2132 * regular HTML document with Content-Type "text/html", image documents and
2133 * media documents). Returns false for XHTML and any other documents parsed
2134 * by the XML parser.
2136 bool IsHTMLDocument() const { return mType == eHTML; }
2137 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2138 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2139 bool IsSVGDocument() const { return mType == eSVG; }
2140 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2141 bool LoadsFullXULStyleSheetUpFront() {
2142 if (IsSVGDocument()) {
2143 return false;
2145 return AllowXULXBL();
2148 bool IsScriptEnabled();
2151 * Returns true if this document was created from a nsXULPrototypeDocument.
2153 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2155 * Returns the prototype the document was created from, or null if it was not
2156 * created from a prototype.
2158 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2160 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2161 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2162 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2165 bool IsContentDocument() const { return mIsContentDocument; }
2166 void SetIsContentDocument(bool aIsContentDocument) {
2167 mIsContentDocument = aIsContentDocument;
2170 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2172 * Create an element with the specified name, prefix and namespace ID.
2173 * Returns null if element name parsing failed.
2175 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2176 int32_t aNamespaceID,
2177 const nsAString* aIs = nullptr);
2180 * Get the security info (i.e. SSL state etc) that the document got
2181 * from the channel/document that created the content of the
2182 * document.
2184 * @see nsIChannel
2186 nsISupports* GetSecurityInfo() { return mSecurityInfo; }
2189 * Get the channel that failed to load and resulted in an error page, if it
2190 * exists. This is only relevant to error pages.
2192 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2195 * This function checks if the document that is trying to access
2196 * GetNetErrorInfo is a trusted about net error page or not.
2198 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2201 * Get security info like error code for a failed channel. This
2202 * property is only exposed to about:neterror documents.
2204 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2207 * This function checks if the document that is trying to access
2208 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2210 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2213 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2214 * failed Channel. This property is only exposed for about:certerror
2215 * documents.
2217 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2218 ErrorResult& aRv);
2221 * Controls whether or not we allow TLS 1.0/1.1. Only exposed to error pages.
2223 bool AllowDeprecatedTls();
2224 void SetAllowDeprecatedTls(bool aResult);
2227 * Set the channel that failed to load and resulted in an error page.
2228 * This is only relevant to error pages.
2230 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2233 * Returns the default namespace ID used for elements created in this
2234 * document.
2236 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2238 void RemoveAllProperties();
2239 void RemoveAllPropertiesFor(nsINode* aNode);
2241 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2244 * Sets the ID used to identify this part of the multipart document
2246 void SetPartID(uint32_t aID) { mPartID = aID; }
2249 * Return the ID used to identify this part of the multipart document
2251 uint32_t GetPartID() const { return mPartID; }
2254 * Sanitize the document by resetting all input elements and forms that have
2255 * autocomplete=off to their default values.
2257 void Sanitize();
2260 * Enumerate all subdocuments.
2261 * The enumerator callback should return CallState::Continue to continue
2262 * enumerating, or CallState::Stop to stop. This will never get passed a null
2263 * aDocument.
2265 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2266 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2269 * Collect all the descendant documents for which |aCalback| returns true.
2270 * The callback function must not mutate any state for the given document.
2272 typedef bool (*nsDocTestFunc)(const Document* aDocument);
2273 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2274 nsDocTestFunc aCallback) const;
2277 * Check whether it is safe to cache the presentation of this document
2278 * and all of its subdocuments. This method checks the following conditions
2279 * recursively:
2280 * - Some document types, such as plugin documents, cannot be safely cached.
2281 * - If there are any pending requests, we don't allow the presentation
2282 * to be cached. Ideally these requests would be suspended and resumed,
2283 * but that is difficult in some cases, such as XMLHttpRequest.
2284 * - If there are any beforeunload or unload listeners, we must fire them
2285 * for correctness, but this likely puts the document into a state where
2286 * it would not function correctly if restored.
2288 * |aNewRequest| should be the request for a new document which will
2289 * replace this document in the docshell. The new document's request
2290 * will be ignored when checking for active requests. If there is no
2291 * request associated with the new document, this parameter may be null.
2293 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2294 * combination is when we try to BFCache aNewRequest
2296 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2297 uint16_t& aBFCacheCombo);
2299 virtual nsresult Init();
2302 * Notify the document that its associated ContentViewer is being destroyed.
2303 * This releases circular references so that the document can go away.
2304 * Destroy() is only called on documents that have a content viewer.
2306 virtual void Destroy();
2309 * Notify the document that its associated ContentViewer is no longer
2310 * the current viewer for the docshell. The document might still
2311 * be rendered in "zombie state" until the next document is ready.
2312 * The document should save form control state.
2314 void RemovedFromDocShell();
2317 * Get the layout history state that should be used to save and restore state
2318 * for nodes in this document. This may return null; if that happens state
2319 * saving and restoration is not possible.
2321 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2324 * Methods that can be used to prevent onload firing while an event that
2325 * should block onload is posted. onload is guaranteed to not fire until
2326 * either all calls to BlockOnload() have been matched by calls to
2327 * UnblockOnload() or the load has been stopped altogether (by the user
2328 * pressing the Stop button, say).
2330 void BlockOnload();
2332 * @param aFireSync whether to fire onload synchronously. If false,
2333 * onload will fire asynchronously after all onload blocks have been
2334 * removed. It will NOT fire from inside UnblockOnload. If true,
2335 * onload may fire from inside UnblockOnload.
2337 void UnblockOnload(bool aFireSync);
2339 // Only BlockOnload should call this!
2340 void AsyncBlockOnload();
2342 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2344 void UnblockDOMContentLoaded();
2347 * Notification that the page has been shown, for documents which are loaded
2348 * into a DOM window. This corresponds to the completion of document load,
2349 * or to the page's presentation being restored into an existing DOM window.
2350 * This notification fires applicable DOM events to the content window. See
2351 * PageTransitionEvent.webidl for a description of the |aPersisted|
2352 * parameter. If aDispatchStartTarget is null, the pageshow event is
2353 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2354 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2355 * event is only dispatched to listeners in the system group.
2356 * Note: if aDispatchStartTarget isn't null, the showing state of the
2357 * document won't be altered.
2359 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2360 bool aOnlySystemGroup = false);
2363 * Notification that the page has been hidden, for documents which are loaded
2364 * into a DOM window. This corresponds to the unloading of the document, or
2365 * to the document's presentation being saved but removed from an existing
2366 * DOM window. This notification fires applicable DOM events to the content
2367 * window. See PageTransitionEvent.webidl for a description of the
2368 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2369 * event is dispatched on the ScriptGlobalObject for this document,
2370 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2371 * true, the event is only dispatched to listeners in the system group.
2372 * Note: if aDispatchStartTarget isn't null, the showing state of the
2373 * document won't be altered.
2375 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2376 bool aOnlySystemGroup = false);
2379 * We record the set of links in the document that are relevant to
2380 * style.
2383 * Notification that an element is a link that is relevant to style.
2385 void AddStyleRelevantLink(Link* aLink) {
2386 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2387 #ifdef DEBUG
2388 nsPtrHashKey<Link>* entry = mStyledLinks.GetEntry(aLink);
2389 NS_ASSERTION(!entry, "Document already knows about this Link!");
2390 mStyledLinksCleared = false;
2391 #endif
2392 mStyledLinks.PutEntry(aLink);
2396 * Notification that an element is a link and its URI might have been
2397 * changed or the element removed. If the element is still a link relevant
2398 * to style, then someone must ensure that AddStyleRelevantLink is
2399 * (eventually) called on it again.
2401 void ForgetLink(Link* aLink) {
2402 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2403 #ifdef DEBUG
2404 nsPtrHashKey<Link>* entry = mStyledLinks.GetEntry(aLink);
2405 NS_ASSERTION(entry || mStyledLinksCleared,
2406 "Document knows nothing about this Link!");
2407 #endif
2408 mStyledLinks.RemoveEntry(aLink);
2411 // Refreshes the hrefs of all the links in the document.
2412 void RefreshLinkHrefs();
2415 * Support for window.matchMedia()
2418 already_AddRefed<MediaQueryList> MatchMedia(const nsAString& aMediaQueryList,
2419 CallerType aCallerType);
2421 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2424 * Get the compatibility mode for this document
2426 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2429 * Check whether we've ever fired a DOMTitleChanged event for this
2430 * document.
2432 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2435 * To batch DOMSubtreeModified, document needs to be informed when
2436 * a mutation event might be dispatched, even if the event isn't actually
2437 * created because there are no listeners for it.
2439 * @param aTarget is the target for the mutation event.
2441 void MayDispatchMutationEvent(nsINode* aTarget) {
2442 if (mSubtreeModifiedDepth > 0) {
2443 mSubtreeModifiedTargets.AppendObject(aTarget);
2448 * Marks as not-going-to-be-collected for the given generation of
2449 * cycle collection.
2451 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2452 mMarkedCCGeneration = aGeneration;
2456 * Gets the cycle collector generation this document is marked for.
2458 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2461 * Returns whether this document is cookie averse. See
2462 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2464 bool IsCookieAverse() const {
2465 // If we are a document that "has no browsing context."
2466 if (!GetInnerWindow()) {
2467 return true;
2470 // If we are a document "whose URL's scheme is not a network scheme."
2471 // NB: Explicitly allow file: URIs to store cookies.
2473 return !NodePrincipal()->SchemeIs("http") &&
2474 !NodePrincipal()->SchemeIs("https") &&
2475 !NodePrincipal()->SchemeIs("ftp") &&
2476 !NodePrincipal()->SchemeIs("file");
2479 bool IsLoadedAsData() { return mLoadedAsData; }
2481 bool MayStartLayout() { return mMayStartLayout; }
2483 void SetMayStartLayout(bool aMayStartLayout);
2485 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2487 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2489 // In case of failure, the document really can't initialize the frame loader.
2490 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2491 // In case of failure, the caller must handle the error, for example by
2492 // finalizing frame loader asynchronously.
2493 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2494 // Removes the frame loader of aShell from the initialization list.
2495 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2498 * Check whether this document is a root document that is not an
2499 * external resource.
2501 bool IsRootDisplayDocument() const {
2502 return !mParentDocument && !mDisplayDocument;
2505 bool IsDocumentURISchemeChrome() const { return mDocURISchemeIsChrome; }
2507 bool IsInChromeDocShell() const {
2508 const Document* root = this;
2509 while (const Document* displayDoc = root->GetDisplayDocument()) {
2510 root = displayDoc;
2512 return root->mInChromeDocShell;
2515 bool IsDevToolsDocument() const { return mIsDevToolsDocument; }
2517 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2519 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2521 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2523 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2525 bool IsResourceDoc() const {
2526 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2527 mHasDisplayDocument; // Are we an external resource doc?
2531 * Get the document for which this document is an external resource. This
2532 * will be null if this document is not an external resource. Otherwise,
2533 * GetDisplayDocument() will return a non-null document, and
2534 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2536 Document* GetDisplayDocument() const { return mDisplayDocument; }
2539 * Set the display document for this document. aDisplayDocument must not be
2540 * null.
2542 void SetDisplayDocument(Document* aDisplayDocument) {
2543 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2544 "Shouldn't set mDisplayDocument on documents that already "
2545 "have a presentation or a docshell or a window");
2546 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2547 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2548 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2549 "Display documents should not nest");
2550 mDisplayDocument = aDisplayDocument;
2551 mHasDisplayDocument = !!aDisplayDocument;
2555 * Request an external resource document for aURI. This will return the
2556 * resource document if available. If one is not available yet, it will
2557 * start loading as needed, and the pending load object will be returned in
2558 * aPendingLoad so that the caller can register an observer to wait for the
2559 * load. If this function returns null and doesn't return a pending load,
2560 * that means that there is no resource document for this URI and won't be
2561 * one in the future.
2563 * @param aURI the URI to get
2564 * @param aReferrerInfo the referrerInfo of the request
2565 * @param aRequestingNode the node making the request
2566 * @param aPendingLoad the pending load for this request, if any
2568 Document* RequestExternalResource(nsIURI* aURI,
2569 nsIReferrerInfo* aReferrerInfo,
2570 nsINode* aRequestingNode,
2571 ExternalResourceLoad** aPendingLoad);
2574 * Enumerate the external resource documents associated with this document.
2575 * The enumerator callback should return CallState::Continue to continue
2576 * enumerating, or CallState::Stop to stop. This callback will never get
2577 * passed a null aDocument.
2579 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2581 dom::ExternalResourceMap& ExternalResourceMap() {
2582 return mExternalResourceMap;
2586 * Return whether the document is currently showing (in the sense of
2587 * OnPageShow() having been called already and OnPageHide() not having been
2588 * called yet.
2590 bool IsShowing() const { return mIsShowing; }
2592 * Return whether the document is currently visible (in the sense of
2593 * OnPageHide having been called and OnPageShow not yet having been called)
2595 bool IsVisible() const { return mVisible; }
2598 * Return whether the document and all its ancestors are visible in the sense
2599 * of pageshow / hide.
2601 bool IsVisibleConsideringAncestors() const;
2603 void SetSuppressedEventListener(EventListener* aListener);
2605 EventListener* GetSuppressedEventListener() {
2606 return mSuppressedEventListener;
2610 * Return true when this document is active, i.e., an active document
2611 * in a content viewer. Note that this will return true for bfcached
2612 * documents, so this does NOT match the "active document" concept in
2613 * the WHATWG spec - see IsCurrentActiveDocument.
2615 bool IsActive() const { return mDocumentContainer && !mRemovedFromDocShell; }
2618 * Return true if this is the current active document for its
2619 * docshell. Note that a docshell may have multiple active documents
2620 * due to the bfcache -- this should be used when you need to
2621 * differentiate the *current* active document from any active
2622 * documents.
2624 bool IsCurrentActiveDocument() const {
2625 nsPIDOMWindowInner* inner = GetInnerWindow();
2626 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2630 * Returns whether this document should perform image loads.
2632 bool ShouldLoadImages() const {
2633 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2634 // images can themselves have data: URL image references.
2635 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2636 IsStaticDocument();
2639 void SetHasPrintCallbacks() {
2640 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2641 mHasPrintCallbacks = true;
2644 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2647 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2648 * the document's activity changes such as OnPageHide, visibility, activity.
2649 * The ActivityObserver objects can be nsIObjectLoadingContent or
2650 * nsIDocumentActivity or HTMLMEdiaElement.
2652 void RegisterActivityObserver(nsISupports* aSupports);
2653 bool UnregisterActivityObserver(nsISupports* aSupports);
2654 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2655 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2656 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2658 // Indicates whether mAnimationController has been (lazily) initialized.
2659 // If this returns true, we're promising that GetAnimationController()
2660 // will have a non-null return value.
2661 bool HasAnimationController() { return !!mAnimationController; }
2663 // Getter for this document's SMIL Animation Controller. Performs lazy
2664 // initialization, if this document supports animation and if
2665 // mAnimationController isn't yet initialized.
2667 // If HasAnimationController is true, this is guaranteed to return non-null.
2668 SMILAnimationController* GetAnimationController();
2670 // Gets the tracker for animations that are waiting to start.
2671 // Returns nullptr if there is no pending animation tracker for this document
2672 // which will be the case if there have never been any CSS animations or
2673 // transitions on elements in the document.
2674 PendingAnimationTracker* GetPendingAnimationTracker() {
2675 return mPendingAnimationTracker;
2678 // Gets the tracker for animations that are waiting to start and
2679 // creates it if it doesn't already exist. As a result, the return value
2680 // will never be nullptr.
2681 PendingAnimationTracker* GetOrCreatePendingAnimationTracker();
2684 * Prevents user initiated events from being dispatched to the document and
2685 * subdocuments.
2687 void SuppressEventHandling(uint32_t aIncrease = 1);
2690 * Unsuppress event handling.
2691 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2692 * asynchronously.
2694 void UnsuppressEventHandlingAndFireEvents(bool aFireEvents);
2696 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2698 bool IsEventHandlingEnabled() const {
2699 return !EventHandlingSuppressed() && mScriptGlobalObject;
2702 bool WouldScheduleFrameRequestCallbacks() const {
2703 // If this function changes to depend on some other variable, make sure to
2704 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2705 // where that variable can change.
2706 return mPresShell && IsEventHandlingEnabled();
2709 void DecreaseEventSuppression() {
2710 MOZ_ASSERT(mEventsSuppressed);
2711 --mEventsSuppressed;
2712 UpdateFrameRequestCallbackSchedulingState();
2716 * Some clipboard commands are unconditionally enabled on some documents, so
2717 * as to always dispatch copy / paste events even though you'd normally not be
2718 * able to copy.
2720 bool AreClipboardCommandsUnconditionallyEnabled() const;
2723 * Note a ChannelEventQueue which has been suspended on the document's behalf
2724 * to prevent XHRs from running content scripts while event handling is
2725 * suppressed. The document is responsible for resuming the queue after
2726 * event handling is unsuppressed.
2728 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2731 * Returns true if a postMessage event should be suspended instead of running.
2732 * The document is responsible for running the event later, in the order they
2733 * were received.
2735 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2738 * Run any suspended postMessage events, or clear them.
2740 void FireOrClearPostMessageEvents(bool aFireEvents);
2742 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2745 * Flag whether we're about to fire the window's load event for this document.
2747 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2750 * Test whether we should be firing a load event for this document after a
2751 * document.close(). This is public and on Document, instead of being private
2752 * to Document, because we need to go through the normal docloader logic
2753 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2754 * semantics of firing the load event; we just don't want to fire the load
2755 * event if this tests true. So we need the docloader to be able to access
2756 * this state.
2758 * This method should only be called at the point when the load event is about
2759 * to be fired. It resets the "skip" flag, so it is not idempotent.
2761 bool SkipLoadEventAfterClose() {
2762 bool skip = mSkipLoadEventAfterClose;
2763 mSkipLoadEventAfterClose = false;
2764 return skip;
2768 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2770 void IncrementIgnoreDestructiveWritesCounter() {
2771 ++mIgnoreDestructiveWritesCounter;
2775 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2777 void DecrementIgnoreDestructiveWritesCounter() {
2778 --mIgnoreDestructiveWritesCounter;
2781 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2784 * Returns true if this document is allowed to contain XUL element and
2785 * use non-builtin XBL bindings.
2787 bool AllowXULXBL() {
2788 return mAllowXULXBL == eTriTrue
2789 ? true
2790 : mAllowXULXBL == eTriFalse ? false : InternalAllowXULXBL();
2794 * Returns true if this document is allowed to load DTDs from UI resources
2795 * no matter what.
2797 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2799 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2801 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2804 * Returns the template content owner document that owns the content of
2805 * HTMLTemplateElement.
2807 Document* GetTemplateContentsOwner();
2810 * Returns true if this document is a static clone of a normal document.
2812 * We create static clones for print preview and printing (possibly other
2813 * things in future).
2815 * Note that static documents are also "loaded as data" (if this method
2816 * returns true, IsLoadedAsData() will also return true).
2818 bool IsStaticDocument() const { return mIsStaticDocument; }
2821 * Clones the document along with any subdocuments, stylesheet, etc.
2823 * The resulting document and everything it contains (including any
2824 * sub-documents) are created purely via cloning. The returned documents and
2825 * any sub-documents are "loaded as data" documents to preserve the state as
2826 * it was during the clone process (we don't want external resources to load
2827 * and replace the cloned resources).
2829 * @param aCloneContainer The container for the clone document.
2830 * @param aContentViewer The viewer for the clone document. Must be the viewer
2831 * of aCloneContainer, but callers must have a reference
2832 * to it already and ensure it's not null.
2833 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2835 already_AddRefed<Document> CreateStaticClone(
2836 nsIDocShell* aCloneContainer, nsIContentViewer* aContentViewer,
2837 bool* aOutHasInProcessPrintCallbacks);
2840 * If this document is a static clone, this returns the original
2841 * document.
2843 Document* GetOriginalDocument() const {
2844 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2845 return mOriginalDocument;
2849 * If this document is a static clone, let the original document know that
2850 * we're going away and then release our reference to it.
2852 void UnlinkOriginalDocumentIfStatic();
2855 * These are called by the parser as it encounters <picture> tags, the end of
2856 * said tags, and possible picture <source srcset> sources respectively. These
2857 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2858 * expected to be marked void.
2860 * NOTE that the parser does not attempt to track the current picture nesting
2861 * level or whether the given <source> tag is within a picture -- it is only
2862 * guaranteed to order these calls properly with respect to
2863 * ResolvePreLoadImage.
2866 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2868 void PreloadPictureClosed();
2870 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2871 const nsAString& aSizesAttr,
2872 const nsAString& aTypeAttr,
2873 const nsAString& aMediaAttr);
2876 * Called by the parser to resolve an image for preloading. The parser will
2877 * call the PreloadPicture* functions to inform us of possible <picture>
2878 * nesting and possible sources, which are used to inform URL selection
2879 * responsive <picture> or <img srcset> images. Unset attributes are expected
2880 * to be marked void.
2881 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2882 * true, false otherwise.
2884 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2885 const nsAString& aSrcAttr,
2886 const nsAString& aSrcsetAttr,
2887 const nsAString& aSizesAttr,
2888 bool* aIsImgSet);
2890 * Called by nsParser to preload images. Can be removed and code moved
2891 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2892 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2893 * be a void string if the attr is not present.
2894 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2895 * when this image is for loading <picture> or <img srcset> images.
2897 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2898 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2899 bool aLinkPreload);
2900 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2901 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2902 bool aLinkPreload);
2905 * Called by images to forget an image preload when they start doing
2906 * the real load.
2908 void ForgetImagePreload(nsIURI* aURI);
2911 * Called by nsParser to preload style sheets. aCrossOriginAttr should be a
2912 * void string if the attr is not present.
2914 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2915 const nsAString& aCrossOriginAttr,
2916 ReferrerPolicyEnum aReferrerPolicy,
2917 const nsAString& aIntegrity,
2918 bool aIsLinkPreload);
2921 * Called by the chrome registry to load style sheets.
2923 * This always does a synchronous load, and parses as a normal document sheet.
2925 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2928 * Returns true if the locale used for the document specifies a direction of
2929 * right to left. For chrome documents, this comes from the chrome registry.
2930 * This is used to determine the current state for the :-moz-locale-dir
2931 * pseudoclass so once can know whether a document is expected to be rendered
2932 * left-to-right or right-to-left.
2934 bool IsDocumentRightToLeft();
2937 * Called by Parser for link rel=preconnect
2939 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2941 enum DocumentTheme {
2942 Doc_Theme_Uninitialized, // not determined yet
2943 Doc_Theme_None,
2944 Doc_Theme_Neutral,
2945 Doc_Theme_Dark,
2946 Doc_Theme_Bright
2950 * Set the document's pending state object (as serialized using structured
2951 * clone).
2953 void SetStateObject(nsIStructuredCloneContainer* scContainer);
2956 * Set the document's pending state object to the same state object as
2957 * aDocument.
2959 void SetStateObjectFrom(Document* aDocument) {
2960 SetStateObject(aDocument->mStateObjectContainer);
2964 * Returns Doc_Theme_None if there is no lightweight theme specified,
2965 * Doc_Theme_Dark for a dark theme, Doc_Theme_Bright for a light theme, and
2966 * Doc_Theme_Neutral for any other theme. This is used to determine the state
2967 * of the pseudoclasses :-moz-lwtheme and :-moz-lwtheme-text.
2969 DocumentTheme GetDocumentLWTheme();
2970 DocumentTheme ThreadSafeGetDocumentLWTheme() const;
2971 void ResetDocumentLWTheme() { mDocLWTheme = Doc_Theme_Uninitialized; }
2973 // Whether we're a media document or not.
2974 enum class MediaDocumentKind {
2975 NotMedia,
2976 Video,
2977 Image,
2978 Plugin,
2981 virtual enum MediaDocumentKind MediaDocumentKind() const {
2982 return MediaDocumentKind::NotMedia;
2986 * Returns the document state.
2987 * Document state bits have the form NS_DOCUMENT_STATE_* and are declared in
2988 * Document.h.
2990 EventStates GetDocumentState() const { return mDocumentState; }
2992 nsISupports* GetCurrentContentSink();
2994 void SetAutoFocusElement(Element* aAutoFocusElement);
2995 void TriggerAutoFocus();
2996 void SetAutoFocusFired();
2997 bool IsAutoFocusFired();
2999 void SetScrollToRef(nsIURI* aDocumentURI);
3000 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3001 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3003 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3004 mChangeScrollPosWhenScrollingToRef = aValue;
3007 using DocumentOrShadowRoot::GetElementById;
3008 using DocumentOrShadowRoot::GetElementsByClassName;
3009 using DocumentOrShadowRoot::GetElementsByTagName;
3010 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3012 DocumentTimeline* Timeline();
3013 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3015 SVGSVGElement* GetSVGRootElement() const;
3017 struct FrameRequest {
3018 FrameRequest(FrameRequestCallback& aCallback, int32_t aHandle);
3019 ~FrameRequest();
3021 // Comparator operators to allow RemoveElementSorted with an
3022 // integer argument on arrays of FrameRequest
3023 bool operator==(int32_t aHandle) const { return mHandle == aHandle; }
3024 bool operator<(int32_t aHandle) const { return mHandle < aHandle; }
3026 RefPtr<FrameRequestCallback> mCallback;
3027 int32_t mHandle;
3030 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3031 int32_t* aHandle);
3032 void CancelFrameRequestCallback(int32_t aHandle);
3035 * Returns true if the handle refers to a callback that was canceled that
3036 * we did not find in our list of callbacks (e.g. because it is one of those
3037 * in the set of callbacks currently queued to be run).
3039 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3042 * Put this document's frame request callbacks into the provided
3043 * list, and forget about them.
3045 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3048 * @return true if this document's frame request callbacks should be
3049 * throttled. We throttle requestAnimationFrame for documents which aren't
3050 * visible (e.g. scrolled out of the viewport).
3052 bool ShouldThrottleFrameRequests() const;
3054 // This returns true when the document tree is being teared down.
3055 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3057 dom::ImageTracker* ImageTracker();
3059 // AddPlugin adds a plugin-related element to mPlugins when the element is
3060 // added to the tree.
3061 void AddPlugin(nsIObjectLoadingContent* aPlugin) {
3062 MOZ_ASSERT(aPlugin);
3063 mPlugins.PutEntry(aPlugin);
3066 // RemovePlugin removes a plugin-related element to mPlugins when the
3067 // element is removed from the tree.
3068 void RemovePlugin(nsIObjectLoadingContent* aPlugin) {
3069 MOZ_ASSERT(aPlugin);
3070 mPlugins.RemoveEntry(aPlugin);
3073 // GetPlugins returns the plugin-related elements from
3074 // the frame and any subframes.
3075 void GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins);
3077 // Adds an element to mResponsiveContent when the element is
3078 // added to the tree.
3079 void AddResponsiveContent(HTMLImageElement* aContent) {
3080 MOZ_ASSERT(aContent);
3081 mResponsiveContent.PutEntry(aContent);
3084 // Removes an element from mResponsiveContent when the element is
3085 // removed from the tree.
3086 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3087 MOZ_ASSERT(aContent);
3088 mResponsiveContent.RemoveEntry(aContent);
3091 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3092 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3093 mSVGUseElementsNeedingShadowTreeUpdate.RemoveEntry(&aElement);
3096 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3097 return mSVGUseElementsNeedingShadowTreeUpdate.GetEntry(&aElement);
3100 using ShadowRootSet = nsTHashtable<nsPtrHashKey<ShadowRoot>>;
3102 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3103 mComposedShadowRoots.PutEntry(&aShadowRoot);
3106 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3107 mComposedShadowRoots.RemoveEntry(&aShadowRoot);
3110 // If you're considering using this, you probably want to use
3111 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3112 // sanity-checking.
3113 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3114 return mComposedShadowRoots.Contains(&aShadowRoot);
3117 const ShadowRootSet& ComposedShadowRoots() const {
3118 return mComposedShadowRoots;
3121 // WebIDL method for chrome code.
3122 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3124 // Notifies any responsive content added by AddResponsiveContent upon media
3125 // features values changing.
3126 void NotifyMediaFeatureValuesChanged();
3128 nsresult GetStateObject(nsIVariant** aResult);
3130 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3132 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3134 nsContentList* ImageMapList();
3136 // Add aLink to the set of links that need their status resolved.
3137 void RegisterPendingLinkUpdate(Link* aLink);
3139 // Update state on links in mLinksToUpdate.
3140 void FlushPendingLinkUpdates();
3142 #define DEPRECATED_OPERATION(_op) e##_op,
3143 enum DeprecatedOperations {
3144 #include "nsDeprecatedOperationList.h"
3145 eDeprecatedOperationCount
3147 #undef DEPRECATED_OPERATION
3148 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3149 void WarnOnceAbout(
3150 DeprecatedOperations aOperation, bool asError = false,
3151 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3153 #define DOCUMENT_WARNING(_op) e##_op,
3154 enum DocumentWarnings {
3155 #include "nsDocumentWarningList.h"
3156 eDocumentWarningCount
3158 #undef DOCUMENT_WARNING
3159 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3160 void WarnOnceAbout(
3161 DocumentWarnings aWarning, bool asError = false,
3162 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3164 // This method may fire a DOM event; if it does so it will happen
3165 // synchronously.
3166 void UpdateVisibilityState();
3168 // Posts an event to call UpdateVisibilityState.
3169 void PostVisibilityUpdateEvent();
3171 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3173 // Adds the size of a given node, which must not be a document node, to the
3174 // window sizes passed-in.
3175 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3177 // Note: Document is a sub-class of nsINode, which has a
3178 // SizeOfExcludingThis function. However, because Document objects can
3179 // only appear at the top of the DOM tree, we have a specialized measurement
3180 // function which returns multiple sizes.
3181 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3182 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3183 // because Document inherits from nsINode; see the comment above the
3184 // declaration of nsINode::SizeOfIncludingThis.
3185 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3187 void ConstructUbiNode(void* storage) override;
3189 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3191 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3193 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3195 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3197 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3199 void SetIsInSyncOperation(bool aSync) {
3200 if (aSync) {
3201 ++mInSyncOperationCount;
3202 } else {
3203 --mInSyncOperationCount;
3207 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3210 * Creates a new element in the HTML namespace with a local name given by
3211 * aTag.
3213 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3215 // WebIDL API
3216 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3217 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3218 ErrorResult& rv);
3219 DOMImplementation* GetImplementation(ErrorResult& rv);
3220 MOZ_MUST_USE nsresult GetURL(nsString& retval) const;
3221 MOZ_MUST_USE nsresult GetDocumentURI(nsString& retval) const;
3222 // Return the URI for the document.
3223 // The returned value may differ if the document is loaded via XHR, and
3224 // when accessed from chrome privileged script and
3225 // from content privileged script for compatibility.
3226 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3227 ErrorResult& aRv) const;
3228 void GetCompatMode(nsString& retval) const;
3229 void GetCharacterSet(nsAString& retval) const;
3230 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3231 // GetDoctype defined above
3232 Element* GetDocumentElement() const { return GetRootElement(); }
3234 enum ElementCallbackType {
3235 eConnected,
3236 eDisconnected,
3237 eAdopted,
3238 eAttributeChanged,
3239 eGetCustomInterface
3242 WindowContext* GetTopLevelWindowContext() const;
3244 Document* GetTopLevelContentDocument();
3245 const Document* GetTopLevelContentDocument() const;
3247 // Returns the associated app window if this is a top-level chrome document,
3248 // null otherwise.
3249 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3251 already_AddRefed<Element> CreateElement(
3252 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3253 ErrorResult& rv);
3254 already_AddRefed<Element> CreateElementNS(
3255 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3256 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3257 already_AddRefed<Element> CreateXULElement(
3258 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3259 ErrorResult& aRv);
3260 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3261 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3262 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3263 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3264 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3265 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3266 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3267 ErrorResult& rv) const;
3268 nsINode* AdoptNode(nsINode& aNode, ErrorResult& rv);
3269 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3270 CallerType aCallerType,
3271 ErrorResult& rv) const;
3272 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3273 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3274 uint32_t aWhatToShow,
3275 NodeFilter* aFilter,
3276 ErrorResult& rv) const;
3277 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3278 uint32_t aWhatToShow,
3279 NodeFilter* aFilter,
3280 ErrorResult& rv) const;
3281 // Deprecated WebIDL bits
3282 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3283 ErrorResult& rv);
3284 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3285 ErrorResult& rv);
3286 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3287 const nsAString& aQualifiedName,
3288 ErrorResult& rv);
3289 void GetInputEncoding(nsAString& aInputEncoding) const;
3290 already_AddRefed<Location> GetLocation() const;
3291 void GetDomain(nsAString& aDomain);
3292 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3293 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3294 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3295 void GetReferrer(nsAString& aReferrer) const;
3296 void GetLastModified(nsAString& aLastModified) const;
3297 void GetReadyState(nsAString& aReadyState) const;
3299 void GetTitle(nsAString& aTitle);
3300 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3301 void GetDir(nsAString& aDirection) const;
3302 void SetDir(const nsAString& aDirection);
3303 nsIHTMLCollection* Images();
3304 nsIHTMLCollection* Embeds();
3305 nsIHTMLCollection* Plugins() { return Embeds(); }
3306 nsIHTMLCollection* Links();
3307 nsIHTMLCollection* Forms();
3308 nsIHTMLCollection* Scripts();
3309 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3310 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3311 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3313 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3314 const mozilla::dom::Optional<nsAString>& /* unused */,
3315 mozilla::ErrorResult& aError);
3316 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3317 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3318 mozilla::ErrorResult& rv);
3319 void Close(mozilla::ErrorResult& rv);
3320 void Write(const mozilla::dom::Sequence<nsString>& aText,
3321 mozilla::ErrorResult& rv);
3322 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3323 mozilla::ErrorResult& rv);
3324 Nullable<WindowProxyHolder> GetDefaultView() const;
3325 Element* GetActiveElement();
3326 nsIContent* GetUnretargetedFocusedContent() const;
3327 bool HasFocus(ErrorResult& rv) const;
3328 void GetDesignMode(nsAString& aDesignMode);
3329 void SetDesignMode(const nsAString& aDesignMode,
3330 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3331 void SetDesignMode(const nsAString& aDesignMode,
3332 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3333 mozilla::ErrorResult& rv);
3334 MOZ_CAN_RUN_SCRIPT
3335 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3336 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3337 mozilla::ErrorResult& aRv);
3338 bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3339 nsIPrincipal& aSubjectPrincipal,
3340 mozilla::ErrorResult& aRv);
3341 bool QueryCommandIndeterm(const nsAString& aHTMLCommandName,
3342 mozilla::ErrorResult& aRv);
3343 bool QueryCommandState(const nsAString& aHTMLCommandName,
3344 mozilla::ErrorResult& aRv);
3345 bool QueryCommandSupported(const nsAString& aHTMLCommandName,
3346 mozilla::dom::CallerType aCallerType,
3347 mozilla::ErrorResult& aRv);
3348 MOZ_CAN_RUN_SCRIPT
3349 void QueryCommandValue(const nsAString& aHTMLCommandName, nsAString& aValue,
3350 mozilla::ErrorResult& aRv);
3351 nsIHTMLCollection* Applets();
3352 nsIHTMLCollection* Anchors();
3353 TimeStamp LastFocusTime() const;
3354 void SetLastFocusTime(const TimeStamp& aFocusTime);
3355 // Event handlers are all on nsINode already
3356 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3357 Element* GetCurrentScript();
3358 void ReleaseCapture() const;
3359 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3360 nsIURI* GetDocumentURIObject() const;
3361 // Not const because all the fullscreen goop is not const
3362 const char* GetFullscreenError(CallerType);
3363 bool FullscreenEnabled(CallerType aCallerType) {
3364 return !GetFullscreenError(aCallerType);
3367 Element* GetTopLayerTop();
3368 // Return the fullscreen element in the top layer
3369 Element* GetUnretargetedFullScreenElement();
3370 bool Fullscreen() { return !!GetFullscreenElement(); }
3371 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3372 void ExitPointerLock() { UnlockPointer(this); }
3373 void GetFgColor(nsAString& aFgColor);
3374 void SetFgColor(const nsAString& aFgColor);
3375 void GetLinkColor(nsAString& aLinkColor);
3376 void SetLinkColor(const nsAString& aLinkColor);
3377 void GetVlinkColor(nsAString& aAvlinkColor);
3378 void SetVlinkColor(const nsAString& aVlinkColor);
3379 void GetAlinkColor(nsAString& aAlinkColor);
3380 void SetAlinkColor(const nsAString& aAlinkColor);
3381 void GetBgColor(nsAString& aBgColor);
3382 void SetBgColor(const nsAString& aBgColor);
3383 void Clear() const {
3384 // Deprecated
3386 void CaptureEvents();
3387 void ReleaseEvents();
3389 mozilla::dom::HTMLAllCollection* All();
3391 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3392 static bool IsWebAnimationsEnabled(JSContext* aCx, JSObject* aObject);
3393 static bool IsWebAnimationsEnabled(CallerType aCallerType);
3394 static bool IsWebAnimationsGetAnimationsEnabled(JSContext* aCx,
3395 JSObject* aObject);
3396 static bool AreWebAnimationsImplicitKeyframesEnabled(JSContext* aCx,
3397 JSObject* aObject);
3398 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3399 JSObject* aObject);
3400 // Checks that the caller is either chrome or some addon.
3401 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3403 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3404 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3406 private:
3407 int32_t mPictureInPictureChildElementCount = 0;
3409 public:
3410 void EnableChildElementInPictureInPictureMode();
3411 void DisableChildElementInPictureInPictureMode();
3413 // True if any child element is being used in picture in picture mode.
3414 bool HasPictureInPictureChildElement() const;
3416 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3417 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3418 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3419 aSheetSet = mLastStyleSheetSet;
3421 const nsString& GetCurrentStyleSheetSet() const {
3422 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3423 : mLastStyleSheetSet;
3425 void SetPreferredStyleSheetSet(const nsAString&);
3426 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3427 aSheetSet = mPreferredStyleSheetSet;
3429 DOMStringList* StyleSheetSets();
3430 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3433 * Retrieve the location of the caret position (DOM node and character
3434 * offset within that node), given a point.
3436 * @param aX Horizontal point at which to determine the caret position, in
3437 * page coordinates.
3438 * @param aY Vertical point at which to determine the caret position, in
3439 * page coordinates.
3441 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3442 float aY);
3444 Element* GetScrollingElement();
3445 // A way to check whether a given element is what would get returned from
3446 // GetScrollingElement. It can be faster than comparing to the return value
3447 // of GetScrollingElement() due to being able to avoid flushes in various
3448 // cases. This method assumes that null is NOT passed.
3449 bool IsScrollingElement(Element* aElement);
3451 // QuerySelector and QuerySelectorAll already defined on nsINode
3453 XPathExpression* CreateExpression(const nsAString& aExpression,
3454 XPathNSResolver* aResolver,
3455 ErrorResult& rv);
3456 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3457 already_AddRefed<XPathResult> Evaluate(
3458 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3459 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3460 ErrorResult& rv);
3461 // Touch event handlers already on nsINode
3462 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3463 EventTarget* aTarget, int32_t aIdentifier,
3464 int32_t aPageX, int32_t aPageY,
3465 int32_t aScreenX, int32_t aScreenY,
3466 int32_t aClientX, int32_t aClientY,
3467 int32_t aRadiusX, int32_t aRadiusY,
3468 float aRotationAngle, float aForce);
3469 already_AddRefed<TouchList> CreateTouchList();
3470 already_AddRefed<TouchList> CreateTouchList(
3471 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3472 already_AddRefed<TouchList> CreateTouchList(
3473 const Sequence<OwningNonNull<Touch>>& aTouches);
3475 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3476 mStyleSheetChangeEventsEnabled = aValue;
3479 bool StyleSheetChangeEventsEnabled() const {
3480 return mStyleSheetChangeEventsEnabled;
3483 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3484 const BlockParsingOptions& aOptions,
3485 ErrorResult& aRv);
3487 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3489 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3491 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3492 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3493 void InitializeXULBroadcastManager();
3494 XULBroadcastManager* GetXULBroadcastManager() const {
3495 return mXULBroadcastManager;
3497 already_AddRefed<nsINode> GetPopupNode();
3498 void SetPopupNode(nsINode* aNode);
3499 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3500 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3501 already_AddRefed<nsINode> GetTooltipNode();
3502 void SetTooltipNode(nsINode* aNode) { /* do nothing */
3505 bool DontWarnAboutMutationEventsAndAllowSlowDOMMutations() {
3506 return mDontWarnAboutMutationEventsAndAllowSlowDOMMutations;
3508 void SetDontWarnAboutMutationEventsAndAllowSlowDOMMutations(
3509 bool aDontWarnAboutMutationEventsAndAllowSlowDOMMutations) {
3510 mDontWarnAboutMutationEventsAndAllowSlowDOMMutations =
3511 aDontWarnAboutMutationEventsAndAllowSlowDOMMutations;
3514 void MaybeWarnAboutZoom();
3516 // ParentNode
3517 nsIHTMLCollection* Children();
3518 uint32_t ChildElementCount();
3521 * Asserts IsHTMLOrXHTML, and can't return null.
3522 * Defined inline in nsHTMLDocument.h
3524 inline nsHTMLDocument* AsHTMLDocument();
3527 * Asserts IsSVGDocument, and can't return null.
3528 * Defined inline in SVGDocument.h
3530 inline SVGDocument* AsSVGDocument();
3533 * Given a node, get a weak reference to it and append that reference to
3534 * mBlockedNodesByClassifier. Can be used later on to look up a node in it.
3535 * (e.g., by the UI)
3537 void AddBlockedNodeByClassifier(nsINode* node) {
3538 if (!node) {
3539 return;
3542 nsWeakPtr weakNode = do_GetWeakReference(node);
3544 if (weakNode) {
3545 mBlockedNodesByClassifier.AppendElement(weakNode);
3549 gfxUserFontSet* GetUserFontSet();
3550 void FlushUserFontSet();
3551 void MarkUserFontSetDirty();
3552 FontFaceSet* GetFonts() { return mFontFaceSet; }
3554 // FontFaceSource
3555 FontFaceSet* Fonts();
3557 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3559 bool IsSynthesized();
3561 void ReportUseCounters();
3563 void SetUseCounter(UseCounter aUseCounter) {
3564 mUseCounters[aUseCounter] = true;
3567 const StyleUseCounters* GetStyleUseCounters() {
3568 return mStyleUseCounters.get();
3571 void PropagateUseCountersToPage();
3572 void PropagateUseCounters(Document* aParentDocument);
3574 // Called to track whether this document has had any interaction.
3575 // This is used to track whether we should permit "beforeunload".
3576 void SetUserHasInteracted();
3577 bool UserHasInteracted() { return mUserHasInteracted; }
3578 void ResetUserInteractionTimer();
3580 // This method would return current autoplay policy, it would be "allowed"
3581 // , "allowed-muted" or "disallowed".
3582 DocumentAutoplayPolicy AutoplayPolicy() const;
3584 // This should be called when this document receives events which are likely
3585 // to be user interaction with the document, rather than the byproduct of
3586 // interaction with the browser (i.e. a keypress to scroll the view port,
3587 // keyboard shortcuts, etc). This is used to decide whether we should
3588 // permit autoplay audible media. This also gesture activates all other
3589 // content documents in this tab.
3590 void NotifyUserGestureActivation();
3592 // This function is used for mochitest only.
3593 void ClearUserGestureActivation();
3595 // Return true if NotifyUserGestureActivation() has been called on any
3596 // document in the document tree.
3597 bool HasBeenUserGestureActivated();
3599 // Return true if there is transient user gesture activation and it hasn't yet
3600 // timed out.
3601 bool HasValidTransientUserGestureActivation();
3603 // Return true.
3604 bool ConsumeTransientUserGestureActivation();
3606 BrowsingContext* GetBrowsingContext() const;
3608 // This document is a WebExtension page, it might be a background page, a
3609 // popup, a visible tab, a visible iframe ...e.t.c.
3610 bool IsExtensionPage() const;
3612 bool HasScriptsBlockedBySandbox();
3614 void ReportHasScrollLinkedEffect();
3615 bool HasScrollLinkedEffect() const { return mHasScrollLinkedEffect; }
3617 #ifdef DEBUG
3618 void AssertDocGroupMatchesKey() const;
3619 #endif
3621 DocGroup* GetDocGroup() const {
3622 #ifdef DEBUG
3623 AssertDocGroupMatchesKey();
3624 #endif
3625 return mDocGroup;
3628 DocGroup* GetDocGroupOrCreate();
3631 * If we're a sub-document, the parent document's layout can affect our style
3632 * and layout (due to the viewport size, viewport units, media queries...).
3634 * This function returns true if our parent document and our child document
3635 * can observe each other. If they cannot, then we don't need to synchronously
3636 * update the parent document layout every time the child document may need
3637 * up-to-date layout information.
3639 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3640 return GetInProcessParentDocument() &&
3641 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3644 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3645 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3646 "Intersection observer already in the list");
3647 mIntersectionObservers.PutEntry(aObserver);
3650 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3651 mIntersectionObservers.RemoveEntry(aObserver);
3654 bool HasIntersectionObservers() const {
3655 return !mIntersectionObservers.IsEmpty();
3658 void UpdateIntersectionObservations(TimeStamp aNowTime);
3659 void ScheduleIntersectionObserverNotification();
3660 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3662 DOMIntersectionObserver* GetLazyLoadImageObserver() {
3663 return mLazyLoadImageObserver;
3665 DOMIntersectionObserver& EnsureLazyLoadImageObserver();
3667 // Dispatch a runnable related to the document.
3668 nsresult Dispatch(TaskCategory aCategory,
3669 already_AddRefed<nsIRunnable>&& aRunnable) final;
3671 virtual nsISerialEventTarget* EventTargetFor(
3672 TaskCategory aCategory) const override;
3674 virtual AbstractThread* AbstractMainThreadFor(
3675 TaskCategory aCategory) override;
3677 // The URLs passed to this function should match what
3678 // JS::DescribeScriptedCaller() returns, since this API is used to
3679 // determine whether some code is being called from a tracking script.
3680 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3681 // The JSContext passed to this method represents the context that we want to
3682 // determine if it belongs to a tracker.
3683 bool IsScriptTracking(JSContext* aCx) const;
3685 // For more information on Flash classification, see
3686 // toolkit/components/url-classifier/flash-block-lists.rst
3687 FlashClassification DocumentFlashClassification();
3689 // ResizeObserver usage.
3690 void AddResizeObserver(ResizeObserver&);
3691 void RemoveResizeObserver(ResizeObserver&);
3692 void ScheduleResizeObserversNotification() const;
3694 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3695 PermissionDelegateHandler* GetPermissionDelegateHandler();
3698 * Localization
3700 * For more information on DocumentL10n see
3701 * intl/l10n/docs/fluent_tutorial.rst
3704 public:
3706 * This is a public method exposed on Document WebIDL
3707 * to chrome only documents.
3709 DocumentL10n* GetL10n();
3712 * This method should be called when the container
3713 * of l10n resources parsing is completed.
3715 * It triggers initial async fetch of the resources
3716 * as early as possible.
3718 * In HTML case this is </head>.
3719 * In XUL case this is </linkset>.
3721 void OnL10nResourceContainerParsed();
3724 * This method should be called when a link element
3725 * with rel="localization" is being added to the
3726 * l10n resource container element.
3728 void LocalizationLinkAdded(Element* aLinkElement);
3731 * This method should be called when a link element
3732 * with rel="localization" is being removed.
3734 void LocalizationLinkRemoved(Element* aLinkElement);
3737 * This method should be called as soon as the
3738 * parsing of the document is completed.
3740 * In HTML/XHTML this happens when we finish parsing
3741 * the document element.
3742 * In XUL it happens at `DoneWalking`, during
3743 * `MozBeforeInitialXULLayout`.
3745 void OnParsingCompleted();
3748 * This method is called when the initial translation
3749 * of the document is completed.
3751 * It unblocks the load event if translation was blocking it.
3753 * If the `aL10nCached` is set to `true`, and the document has
3754 * a prototype, it will set the `isL10nCached` flag on it.
3756 void InitialTranslationCompleted(bool aL10nCached);
3759 * Returns whether the document allows localization.
3761 bool AllowsL10n() const;
3763 protected:
3764 RefPtr<DocumentL10n> mDocumentL10n;
3767 * Return true when you want a document without explicitly specified viewport
3768 * dimensions/scale to be treated as if "width=device-width" had in fact been
3769 * specified.
3771 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3773 private:
3774 bool IsErrorPage() const;
3776 void EnsureL10n();
3778 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3779 // mUseCounters.
3780 void SetCssUseCounterBits();
3782 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3783 const nsAString& aHeightString,
3784 bool aIsAutoScale);
3786 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3787 // represents the scale property and returns the scale value if it's valid.
3788 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
3790 // Parse scale values in |aViewportMetaData| and set the values in
3791 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3792 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
3794 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3795 // stored in parent iframe or container's browsingContext (cross process)
3796 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
3798 FlashClassification DocumentFlashClassificationInternal();
3800 // The application cache that this document is associated with, if
3801 // any. This can change during the lifetime of the document.
3802 nsCOMPtr<nsIApplicationCache> mApplicationCache;
3804 public:
3805 bool IsThirdPartyForFlashClassifier();
3807 private:
3808 void DoCacheAllKnownLangPrefs();
3809 void RecomputeLanguageFromCharset();
3810 bool GetSHEntryHasUserInteraction();
3812 public:
3813 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
3815 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
3817 void SetSHEntryHasUserInteraction(bool aHasInteraction);
3819 already_AddRefed<nsAtom> GetContentLanguageAsAtomForStyle() const;
3820 already_AddRefed<nsAtom> GetLanguageForStyle() const;
3823 * Fetch the user's font preferences for the given aLanguage's
3824 * language group.
3826 const LangGroupFontPrefs* GetFontPrefsForLang(
3827 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
3829 void ForceCacheLang(nsAtom* aLanguage) {
3830 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
3831 return;
3833 GetFontPrefsForLang(aLanguage);
3836 void CacheAllKnownLangPrefs() {
3837 if (!mMayNeedFontPrefsUpdate) {
3838 return;
3840 DoCacheAllKnownLangPrefs();
3843 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
3845 uint32_t GetServoRestyleRootDirtyBits() const {
3846 MOZ_ASSERT(mServoRestyleRoot);
3847 MOZ_ASSERT(mServoRestyleRootDirtyBits);
3848 return mServoRestyleRootDirtyBits;
3851 void ClearServoRestyleRoot() {
3852 mServoRestyleRoot = nullptr;
3853 mServoRestyleRootDirtyBits = 0;
3856 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3857 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3859 bool ShouldThrowOnDynamicMarkupInsertion() {
3860 return mThrowOnDynamicMarkupInsertionCounter;
3863 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3864 ++mThrowOnDynamicMarkupInsertionCounter;
3867 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3868 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3869 --mThrowOnDynamicMarkupInsertionCounter;
3872 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
3874 void IncrementIgnoreOpensDuringUnloadCounter() {
3875 ++mIgnoreOpensDuringUnloadCounter;
3878 void DecrementIgnoreOpensDuringUnloadCounter() {
3879 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3880 --mIgnoreOpensDuringUnloadCounter;
3883 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
3885 bool ModuleScriptsEnabled();
3888 * Find the (non-anonymous) content in this document for aFrame. It will
3889 * be aFrame's content node if that content is in this document and not
3890 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
3891 * element containing the subdocument containing aFrame, and/or find the
3892 * nearest non-anonymous ancestor in this document.
3893 * Returns null if there is no such element.
3895 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
3897 void ReportShadowDOMUsage();
3899 // Sets flags for media telemetry.
3900 void SetDocTreeHadMedia();
3902 dom::XPathEvaluator* XPathEvaluator();
3904 void MaybeInitializeFinalizeFrameLoaders();
3906 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
3907 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
3910 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
3912 nsIPermissionDelegateHandler* PermDelegateHandler();
3914 // CSS prefers-color-scheme media feature for this document.
3915 enum class IgnoreRFP { No, Yes };
3916 StylePrefersColorScheme PrefersColorScheme(IgnoreRFP = IgnoreRFP::No) const;
3918 // Returns true if we use overlay scrollbars on the system wide or on the
3919 // given document.
3920 static bool UseOverlayScrollbars(const Document* aDocument);
3922 static bool HasRecentlyStartedForegroundLoads();
3924 static bool AutomaticStorageAccessPermissionCanBeGranted(
3925 nsIPrincipal* aPrincipal);
3927 already_AddRefed<Promise> AddCertException(bool aIsTemporary);
3929 // Subframes need to be static cloned after the main document has been
3930 // embedded within a script global. A `PendingFrameStaticClone` is a static
3931 // clone which has not yet been performed.
3933 // The getter returns a direct reference to an internal array which is
3934 // manipulated from within printing code.
3935 struct PendingFrameStaticClone {
3936 PendingFrameStaticClone() = default;
3937 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
3938 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
3939 ~PendingFrameStaticClone();
3941 RefPtr<nsFrameLoaderOwner> mElement;
3942 RefPtr<nsFrameLoader> mStaticCloneOf;
3944 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
3945 nsFrameLoader* aStaticCloneOf);
3947 bool ShouldAvoidNativeTheme() const;
3949 protected:
3950 void DoUpdateSVGUseElementShadowTrees();
3952 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
3953 nsIPrincipal* aPrincipal);
3955 void EnsureOnloadBlocker();
3957 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
3959 // Returns true if the scheme for the url for this document is "about".
3960 bool IsAboutPage() const;
3962 bool ContainsEMEContent();
3963 bool ContainsMSEContent();
3966 * Returns the title element of the document as defined by the HTML
3967 * specification, or null if there isn't one. For documents whose root
3968 * element is an <svg:svg>, this is the first <svg:title> element that's a
3969 * child of the root. For other documents, it's the first HTML title element
3970 * in the document.
3972 Element* GetTitleElement();
3974 void RecordNavigationTiming(ReadyState aReadyState);
3976 // Recomputes the visibility state but doesn't set the new value.
3977 dom::VisibilityState ComputeVisibilityState() const;
3979 // Since we wouldn't automatically play media from non-visited page, we need
3980 // to notify window when the page was first visited.
3981 void MaybeActiveMediaComponents();
3983 // Apply the fullscreen state to the document, and trigger related
3984 // events. It returns false if the fullscreen element ready check
3985 // fails and nothing gets changed.
3986 bool ApplyFullscreen(UniquePtr<FullscreenRequest>);
3988 bool GetUseCounter(UseCounter aUseCounter) {
3989 return mUseCounters[aUseCounter];
3992 void SetChildDocumentUseCounter(UseCounter aUseCounter) {
3993 if (!mChildDocumentUseCounters[aUseCounter]) {
3994 mChildDocumentUseCounters[aUseCounter] = true;
3998 bool GetChildDocumentUseCounter(UseCounter aUseCounter) {
3999 return mChildDocumentUseCounters[aUseCounter];
4002 void RemoveDocStyleSheetsFromStyleSets();
4003 void ResetStylesheetsToURI(nsIURI* aURI);
4004 void FillStyleSet();
4005 void FillStyleSetUserAndUASheets();
4006 void FillStyleSetDocumentSheets();
4007 void CompatibilityModeChanged();
4008 bool NeedsQuirksSheet() const {
4009 // SVG documents never load quirk.css.
4010 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4011 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
4013 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
4014 void RemoveContentEditableStyleSheets();
4015 void AddStyleSheetToStyleSets(StyleSheet&);
4016 void RemoveStyleSheetFromStyleSets(StyleSheet&);
4017 void NotifyStyleSheetApplicableStateChanged();
4018 // Just like EnableStyleSheetsForSet, but doesn't check whether
4019 // aSheetSet is null and allows the caller to control whether to set
4020 // aSheetSet as the preferred set in the CSSLoader.
4021 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
4022 bool aUpdateCSSLoader);
4024 already_AddRefed<nsIURI> GetDomainURI();
4025 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4026 const nsACString& aHostString);
4027 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4028 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4030 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4031 mozilla::ErrorResult& aRv);
4032 // A version of WriteCommon used by WebIDL bindings
4033 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4034 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4036 void* GenerateParserKey(void);
4038 private:
4039 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4040 // parameter.
4041 enum class ExecCommandParam : uint8_t {
4042 // Always ignore it.
4043 Ignore,
4044 // Treat the given parameter as-is. If the command requires it, use it.
4045 // Otherwise, ignore it.
4046 String,
4047 // Always treat it as boolean parameter.
4048 Boolean,
4049 // Always treat it as boolean, but inverted.
4050 InvertedBoolean,
4053 typedef mozilla::EditorCommand*(GetEditorCommandFunc)();
4055 struct InternalCommandData {
4056 const char* mXULCommandName;
4057 mozilla::Command mCommand; // uint8_t
4058 // How ConvertToInternalCommand() to treats aValue.
4059 // Its callers don't need to check this.
4060 ExecCommandParam mExecCommandParam; // uint8_t
4061 GetEditorCommandFunc* mGetEditorCommandFunc;
4063 InternalCommandData()
4064 : mXULCommandName(nullptr),
4065 mCommand(mozilla::Command::DoNothing),
4066 mExecCommandParam(ExecCommandParam::Ignore),
4067 mGetEditorCommandFunc(nullptr) {}
4068 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4069 ExecCommandParam aExecCommandParam,
4070 GetEditorCommandFunc aGetEditorCommandFunc)
4071 : mXULCommandName(aXULCommandName),
4072 mCommand(aCommand),
4073 mExecCommandParam(aExecCommandParam),
4074 mGetEditorCommandFunc(aGetEditorCommandFunc) {}
4076 bool IsAvailableOnlyWhenEditable() const {
4077 return mCommand != mozilla::Command::Cut &&
4078 mCommand != mozilla::Command::Copy &&
4079 mCommand != mozilla::Command::Paste;
4081 bool IsCutOrCopyCommand() const {
4082 return mCommand == mozilla::Command::Cut ||
4083 mCommand == mozilla::Command::Copy;
4085 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4089 * Helper method to initialize sInternalCommandDataHashtable.
4091 static void EnsureInitializeInternalCommandDataHashtable();
4094 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4095 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4096 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4097 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4098 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4099 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4100 * returns a copy of instance created with default constructor. I.e., its
4101 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4102 * is unsupported in such case.
4104 * @param aHTMLCommandName Command name in HTML, e.g., used by
4105 * execCommand().
4106 * @param aValue The value which is set to the 3rd parameter
4107 * of execCommand().
4108 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4109 * Will be set to adjusted value for executing
4110 * the internal command.
4111 * @return Returns a copy of instance created with the
4112 * default constructor if there is no
4113 * corresponding internal command for
4114 * aHTMLCommandName or aValue is invalid for
4115 * found internal command when aAdjustedValue
4116 * is not nullptr. Otherwise, returns a copy of
4117 * instance registered in
4118 * sInternalCommandDataHashtable.
4120 static InternalCommandData ConvertToInternalCommand(
4121 const nsAString& aHTMLCommandName, const nsAString& aValue = u""_ns,
4122 nsAString* aAdjustedValue = nullptr);
4125 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4126 * Since it's a bit field, not a bool member, therefore, we cannot use
4127 * AutoRestorer for it.
4129 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4130 public:
4131 AutoRunningExecCommandMarker() = delete;
4132 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4133 delete;
4134 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4135 MOZ_CAN_RUN_SCRIPT explicit AutoRunningExecCommandMarker(
4136 Document& aDocument)
4137 : mDocument(aDocument),
4138 mHasBeenRunning(aDocument.mIsRunningExecCommand) {
4139 aDocument.mIsRunningExecCommand = true;
4141 ~AutoRunningExecCommandMarker() {
4142 if (!mHasBeenRunning) {
4143 mDocument.mIsRunningExecCommand = false;
4147 private:
4148 Document& mDocument;
4149 bool mHasBeenRunning;
4152 // Mapping table from HTML command name to internal command.
4153 typedef nsDataHashtable<nsStringCaseInsensitiveHashKey, InternalCommandData>
4154 InternalCommandDataHashtable;
4155 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4157 mutable std::bitset<eDeprecatedOperationCount> mDeprecationWarnedAbout;
4158 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4160 // Lazy-initialization to have mDocGroup initialized in prior to the
4161 // SelectorCaches.
4162 UniquePtr<SelectorCache> mSelectorCache;
4163 UniquePtr<ServoStyleSet> mStyleSet;
4165 protected:
4166 friend class nsDocumentOnStack;
4168 void IncreaseStackRefCnt() { ++mStackRefCnt; }
4170 void DecreaseStackRefCnt() {
4171 if (--mStackRefCnt == 0 && mNeedsReleaseAfterStackRefCntRelease) {
4172 mNeedsReleaseAfterStackRefCntRelease = false;
4173 NS_RELEASE_THIS();
4177 // Never ever call this. Only call GetWindow!
4178 nsPIDOMWindowOuter* GetWindowInternal() const;
4180 // Never ever call this. Only call GetScriptHandlingObject!
4181 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4183 // Never ever call this. Only call AllowXULXBL!
4184 bool InternalAllowXULXBL();
4187 * These methods should be called before and after dispatching
4188 * a mutation event.
4189 * To make this easy and painless, use the mozAutoSubtreeModified helper
4190 * class.
4192 void WillDispatchMutationEvent(nsINode* aTarget);
4193 void MutationEventDispatched(nsINode* aTarget);
4194 friend class mozAutoSubtreeModified;
4196 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4198 void SetContentTypeInternal(const nsACString& aType);
4200 nsCString GetContentTypeInternal() const { return mContentType; }
4202 // Update our frame request callback scheduling state, if needed. This will
4203 // schedule or unschedule them, if necessary, and update
4204 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4205 // mPresShell is becoming null; in that case it will be used to get hold of
4206 // the relevant refresh driver.
4207 void UpdateFrameRequestCallbackSchedulingState(
4208 PresShell* aOldPresShell = nullptr);
4210 // Helper for GetScrollingElement/IsScrollingElement.
4211 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4213 void MaybeAllowStorageForOpenerAfterUserInteraction();
4215 void MaybeStoreUserInteractionAsPermission();
4217 // Helpers for GetElementsByName.
4218 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4219 nsAtom* aAtom, void* aData);
4220 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4222 void MaybeResolveReadyForIdle();
4224 typedef MozPromise<bool, bool, true>
4225 AutomaticStorageAccessPermissionGrantPromise;
4226 MOZ_MUST_USE RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4227 AutomaticStorageAccessPermissionCanBeGranted();
4229 static void AddToplevelLoadingDocument(Document* aDoc);
4230 static void RemoveToplevelLoadingDocument(Document* aDoc);
4231 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4232 friend class cycleCollection;
4234 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4235 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4237 nsString mLastModified;
4239 nsCOMPtr<nsIURI> mDocumentURI;
4240 nsCOMPtr<nsIURI> mOriginalURI;
4241 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4242 nsCOMPtr<nsIURI> mDocumentBaseURI;
4243 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4245 // The base domain of the document for third-party checks.
4246 nsCString mBaseDomain;
4248 // A lazily-constructed URL data for style system to resolve URL value.
4249 RefPtr<URLExtraData> mCachedURLData;
4250 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfo;
4252 nsWeakPtr mDocumentLoadGroup;
4254 bool mBlockAllMixedContent;
4255 bool mBlockAllMixedContentPreloads;
4256 bool mUpgradeInsecureRequests;
4257 bool mUpgradeInsecurePreloads;
4259 bool mDontWarnAboutMutationEventsAndAllowSlowDOMMutations;
4261 WeakPtr<nsDocShell> mDocumentContainer;
4263 NotNull<const Encoding*> mCharacterSet;
4264 int32_t mCharacterSetSource;
4266 // This is just a weak pointer; the parent document owns its children.
4267 Document* mParentDocument;
4269 // A reference to the element last returned from GetRootElement().
4270 Element* mCachedRootElement;
4272 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4273 // which in turn holds a strong reference to this mNodeInfoManager.
4274 nsNodeInfoManager* mNodeInfoManager;
4275 RefPtr<css::Loader> mCSSLoader;
4276 RefPtr<css::ImageLoader> mStyleImageLoader;
4277 RefPtr<nsHTMLStyleSheet> mAttrStyleSheet;
4278 RefPtr<nsHTMLCSSStyleSheet> mStyleAttrStyleSheet;
4280 // Tracking for images in the document.
4281 RefPtr<dom::ImageTracker> mImageTracker;
4283 // A hashtable of ShadowRoots belonging to the composed doc.
4285 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4286 ShadowRootSet mComposedShadowRoots;
4288 using SVGUseElementSet = nsTHashtable<nsPtrHashKey<SVGUseElement>>;
4290 // The set of <svg:use> elements that need a shadow tree reclone because the
4291 // tree they map to has changed.
4292 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4294 // The set of all object, embed, video/audio elements or
4295 // nsIObjectLoadingContent or DocumentActivity for which this is
4296 // the owner document. (They might not be in the document.)
4298 // These are non-owning pointers, the elements are responsible for removing
4299 // themselves when they go away.
4300 UniquePtr<nsTHashtable<nsPtrHashKey<nsISupports>>> mActivityObservers;
4302 // A hashtable of styled links keyed by address pointer.
4303 nsTHashtable<nsPtrHashKey<Link>> mStyledLinks;
4304 #ifdef DEBUG
4305 // Indicates whether mStyledLinks was cleared or not. This is used to track
4306 // state so we can provide useful assertions to consumers of ForgetLink and
4307 // AddStyleRelevantLink.
4308 bool mStyledLinksCleared;
4309 #endif
4311 // The array of all links that need their status resolved. Links must add
4312 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4313 // document.
4314 static const size_t kSegmentSize = 128;
4316 typedef SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>
4317 LinksToUpdateList;
4319 LinksToUpdateList mLinksToUpdate;
4321 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4322 RefPtr<SMILAnimationController> mAnimationController;
4324 // Table of element properties for this document.
4325 nsPropertyTable mPropertyTable;
4327 // Our cached .children collection
4328 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4330 // Various DOM lists
4331 RefPtr<nsContentList> mImages;
4332 RefPtr<nsContentList> mEmbeds;
4333 RefPtr<nsContentList> mLinks;
4334 RefPtr<nsContentList> mForms;
4335 RefPtr<nsContentList> mScripts;
4336 nsCOMPtr<nsIHTMLCollection> mApplets;
4337 RefPtr<nsContentList> mAnchors;
4339 // container for per-context fonts (downloadable, SVG, etc.)
4340 RefPtr<FontFaceSet> mFontFaceSet;
4342 // Last time this document or a one of its sub-documents was focused. If
4343 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4344 TimeStamp mLastFocusTime;
4346 EventStates mDocumentState;
4348 RefPtr<Promise> mReadyForIdle;
4350 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4352 UniquePtr<ResizeObserverController> mResizeObserverController;
4354 // Permission Delegate Handler, lazily-initialized in
4355 // GetPermissionDelegateHandler
4356 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4358 // True if BIDI is enabled.
4359 bool mBidiEnabled : 1;
4360 // True if we may need to recompute the language prefs for this document.
4361 bool mMayNeedFontPrefsUpdate : 1;
4362 // True if a MathML element has ever been owned by this document.
4363 bool mMathMLEnabled : 1;
4365 // True if this document is the initial document for a window. This should
4366 // basically be true only for documents that exist in newly-opened windows or
4367 // documents created to satisfy a GetDocument() on a window when there's no
4368 // document in it.
4369 bool mIsInitialDocumentInWindow : 1;
4371 bool mIgnoreDocGroupMismatches : 1;
4373 // True if we're loaded as data and therefor has any dangerous stuff, such
4374 // as scripts and plugins, disabled.
4375 bool mLoadedAsData : 1;
4377 // If true, whoever is creating the document has gotten it to the
4378 // point where it's safe to start layout on it.
4379 bool mMayStartLayout : 1;
4381 // True iff we've ever fired a DOMTitleChanged event for this document
4382 bool mHaveFiredTitleChange : 1;
4384 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4385 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4386 // before the initial load completes and when we're in bfcache or unloaded,
4387 // true otherwise.
4388 bool mIsShowing : 1;
4390 // State for IsVisible(). mVisible starts off true. It becomes false when
4391 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4392 // it's false only when we're in bfcache or unloaded.
4393 bool mVisible : 1;
4395 // True if our content viewer has been removed from the docshell
4396 // (it may still be displayed, but in zombie state). Form control data
4397 // has been saved.
4398 bool mRemovedFromDocShell : 1;
4400 // True iff DNS prefetch is allowed for this document. Note that if the
4401 // document has no window, DNS prefetch won't be performed no matter what.
4402 bool mAllowDNSPrefetch : 1;
4404 // True when this document is a static clone of a normal document
4405 bool mIsStaticDocument : 1;
4407 // True while this document is being cloned to a static document.
4408 bool mCreatingStaticClone : 1;
4410 // True if this static document has any <canvas> element with a
4411 // mozPrintCallback property at the time of the clone.
4412 bool mHasPrintCallbacks : 1;
4414 // True iff the document is being unlinked or deleted.
4415 bool mInUnlinkOrDeletion : 1;
4417 // True if document has ever had script handling object.
4418 bool mHasHadScriptHandlingObject : 1;
4420 // True if we're an SVG document being used as an image.
4421 bool mIsBeingUsedAsImage : 1;
4423 // True if our current document URI's scheme is chrome://
4424 bool mDocURISchemeIsChrome : 1;
4426 // True if we're loaded in a chrome docshell.
4427 bool mInChromeDocShell : 1;
4429 // True if our current document is a DevTools document. Either the url is
4430 // about:devtools-toolbox or the parent document already has
4431 // mIsDevToolsDocument set to true.
4432 // This is used to avoid applying High Contrast mode to DevTools documents.
4433 // See Bug 1575766.
4434 bool mIsDevToolsDocument : 1;
4436 // True is this document is synthetic : stand alone image, video, audio
4437 // file, etc.
4438 bool mIsSyntheticDocument : 1;
4440 // True is there is a pending runnable which will call
4441 // FlushPendingLinkUpdates().
4442 bool mHasLinksToUpdateRunnable : 1;
4444 // True if we're flushing pending link updates.
4445 bool mFlushingPendingLinkUpdates : 1;
4447 // True if a DOMMutationObserver is perhaps attached to a node in the
4448 // document.
4449 bool mMayHaveDOMMutationObservers : 1;
4451 // True if an nsIAnimationObserver is perhaps attached to a node in the
4452 // document.
4453 bool mMayHaveAnimationObservers : 1;
4455 // True if a document load has a CSP attached.
4456 bool mHasCSP : 1;
4458 // True if a document load has a CSP with unsafe-eval attached.
4459 bool mHasUnsafeEvalCSP : 1;
4461 // True if a document load has a CSP with unsafe-inline attached.
4462 bool mHasUnsafeInlineCSP : 1;
4464 // True if the document has a CSP delivered throuh a header
4465 bool mHasCSPDeliveredThroughHeader : 1;
4467 // True if DisallowBFCaching has been called on this document.
4468 bool mBFCacheDisallowed : 1;
4470 bool mHasHadDefaultView : 1;
4472 // Whether style sheet change events will be dispatched for this document
4473 bool mStyleSheetChangeEventsEnabled : 1;
4475 // Whether the document was created by a srcdoc iframe.
4476 bool mIsSrcdocDocument : 1;
4478 // Whether this document has a display document and thus is considered to
4479 // be a resource document. Normally this is the same as !!mDisplayDocument,
4480 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4481 // valid in the document's destructor.
4482 bool mHasDisplayDocument : 1;
4484 // Is the current mFontFaceSet valid?
4485 bool mFontFaceSetDirty : 1;
4487 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4488 // (e.g. we're not being parsed at all).
4489 bool mDidFireDOMContentLoaded : 1;
4491 // True if ReportHasScrollLinkedEffect() has been called.
4492 bool mHasScrollLinkedEffect : 1;
4494 // True if we have frame request callbacks scheduled with the refresh driver.
4495 // This should generally be updated only via
4496 // UpdateFrameRequestCallbackSchedulingState.
4497 bool mFrameRequestCallbacksScheduled : 1;
4499 bool mIsTopLevelContentDocument : 1;
4501 bool mIsContentDocument : 1;
4503 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4504 bool mDidCallBeginLoad : 1;
4506 // True if the encoding menu should be disabled.
4507 bool mEncodingMenuDisabled : 1;
4509 // False if we've disabled link handling for elements inside this document,
4510 // true otherwise.
4511 bool mLinksEnabled : 1;
4513 // True if this document is for an SVG-in-OpenType font.
4514 bool mIsSVGGlyphsDocument : 1;
4516 // True if the document is being destroyed.
4517 bool mInDestructor : 1;
4519 // True if the document has been detached from its content viewer.
4520 bool mIsGoingAway : 1;
4522 bool mInXBLUpdate : 1;
4524 bool mNeedsReleaseAfterStackRefCntRelease : 1;
4526 // Whether we have filled our style set with all the stylesheets.
4527 bool mStyleSetFilled : 1;
4529 // Whether we have a quirks mode stylesheet in the style set.
4530 bool mQuirkSheetAdded : 1;
4532 // Whether we have a contenteditable.css stylesheet in the style set.
4533 bool mContentEditableSheetAdded : 1;
4535 // Whether we have a designmode.css stylesheet in the style set.
4536 bool mDesignModeSheetAdded : 1;
4538 // Keeps track of whether we have a pending
4539 // 'style-sheet-applicable-state-changed' notification.
4540 bool mSSApplicableStateNotificationPending : 1;
4542 // True if this document has ever had an HTML or SVG <title> element
4543 // bound to it
4544 bool mMayHaveTitleElement : 1;
4546 bool mDOMLoadingSet : 1;
4547 bool mDOMInteractiveSet : 1;
4548 bool mDOMCompleteSet : 1;
4549 bool mAutoFocusFired : 1;
4551 bool mScrolledToRefAlready : 1;
4552 bool mChangeScrollPosWhenScrollingToRef : 1;
4554 bool mDelayFrameLoaderInitialization : 1;
4556 bool mSynchronousDOMContentLoaded : 1;
4558 // Set to true when the document is possibly controlled by the ServiceWorker.
4559 // Used to prevent multiple requests to ServiceWorkerManager.
4560 bool mMaybeServiceWorkerControlled : 1;
4562 // These member variables cache information about the viewport so we don't
4563 // have to recalculate it each time.
4564 bool mAllowZoom : 1;
4565 bool mValidScaleFloat : 1;
4566 bool mValidMinScale : 1;
4567 bool mValidMaxScale : 1;
4568 bool mWidthStrEmpty : 1;
4570 // Parser aborted. True if the parser of this document was forcibly
4571 // terminated instead of letting it finish at its own pace.
4572 bool mParserAborted : 1;
4574 // Whether we have reported use counters for this document with Telemetry yet.
4575 // Normally this is only done at document destruction time, but for image
4576 // documents (SVG documents) that are not guaranteed to be destroyed, we
4577 // report use counters when the image cache no longer has any imgRequestProxys
4578 // pointing to them. We track whether we ever reported use counters so
4579 // that we only report them once for the document.
4580 bool mReportedUseCounters : 1;
4582 bool mHasReportedShadowDOMUsage : 1;
4584 // Whether an event triggered by the refresh driver was delayed because this
4585 // document has suppressed events.
4586 bool mHasDelayedRefreshEvent : 1;
4588 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4589 // to have the right semantics. See
4590 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4591 // flag that is set while the window's 'load' event is firing if this document
4592 // is the window's document.
4593 bool mLoadEventFiring : 1;
4595 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4596 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4597 // What we have instead is a flag that is set if completion of our document
4598 // via document.close() should skip firing the load event. Note that this
4599 // flag is only relevant for HTML documents, but lives here for reasons that
4600 // are documented above on SkipLoadEventAfterClose().
4601 bool mSkipLoadEventAfterClose : 1;
4603 // When false, the .cookies property is completely disabled
4604 bool mDisableCookieAccess : 1;
4606 // When false, the document.write() API is disabled.
4607 bool mDisableDocWrite : 1;
4609 // Has document.write() been called with a recursion depth higher than
4610 // allowed?
4611 bool mTooDeepWriteRecursion : 1;
4614 * Temporary flag that is set in EndUpdate() to ignore
4615 * MaybeEditingStateChanged() script runners from a nested scope.
4617 bool mPendingMaybeEditingStateChanged : 1;
4619 // mHasBeenEditable is set to true when mEditingState is firstly set to
4620 // eDesignMode or eContentEditable.
4621 bool mHasBeenEditable : 1;
4623 // Whether we've warned about the CSS zoom property.
4625 // We don't use the general deprecated operation mechanism for this because we
4626 // also record this as a `CountedUnknownProperty`.
4627 bool mHasWarnedAboutZoom : 1;
4629 // While we're handling an execCommand call, set to true.
4630 bool mIsRunningExecCommand : 1;
4632 // True if we should change the readystate to complete after we fire
4633 // DOMContentLoaded. This happens when we abort a load and
4634 // nsDocumentViewer::EndLoad runs while we still have things blocking
4635 // DOMContentLoaded. We wait for those to complete, and then update the
4636 // readystate when they finish.
4637 bool mSetCompleteAfterDOMContentLoaded : 1;
4639 uint8_t mPendingFullscreenRequests;
4641 uint8_t mXMLDeclarationBits;
4643 // Currently active onload blockers.
4644 uint32_t mOnloadBlockCount;
4646 // Onload blockers which haven't been activated yet.
4647 uint32_t mAsyncOnloadBlockCount;
4649 // Tracks if we are currently processing any document.write calls (either
4650 // implicit or explicit). Note that if a write call writes out something which
4651 // would block the parser, then mWriteLevel will be incorrect until the parser
4652 // finishes processing that script.
4653 uint32_t mWriteLevel;
4655 uint32_t mContentEditableCount;
4656 EditingState mEditingState;
4658 // Compatibility mode
4659 nsCompatibility mCompatMode;
4661 // Our readyState
4662 ReadyState mReadyState;
4664 // Ancestor's loading state
4665 bool mAncestorIsLoading;
4667 // Our visibility state
4668 dom::VisibilityState mVisibilityState;
4670 enum Type {
4671 eUnknown, // should never be used
4672 eHTML,
4673 eXHTML,
4674 eGenericXML,
4675 eSVG
4678 Type mType;
4680 uint8_t mDefaultElementType;
4682 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4684 Tri mAllowXULXBL;
4686 bool mSkipDTDSecurityChecks;
4688 // The document's script global object, the object from which the
4689 // document can get its script context and scope. This is the
4690 // *inner* window object.
4691 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4693 // If mIsStaticDocument is true, mOriginalDocument points to the original
4694 // document.
4695 RefPtr<Document> mOriginalDocument;
4697 // The bidi options for this document. What this bitfield means is
4698 // defined in nsBidiUtils.h
4699 uint32_t mBidiOptions;
4701 // The sandbox flags on the document. These reflect the value of the sandbox
4702 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4703 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4704 // possible flags.
4705 uint32_t mSandboxFlags;
4707 // The embedder policy obtained from parsing the HTTP response header or from
4708 // our opener if this is the initial about:blank document.
4709 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4711 nsCString mContentLanguage;
4713 // The channel that got passed to Document::StartDocumentLoad(), if any.
4714 nsCOMPtr<nsIChannel> mChannel;
4716 // The CSP for every load lives in the Client within the LoadInfo. For all
4717 // document-initiated subresource loads we can use that cached version of the
4718 // CSP so we do not have to deserialize the CSP from the Client all the time.
4719 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4720 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4722 private:
4723 nsCString mContentType;
4725 protected:
4726 // The document's security info
4727 nsCOMPtr<nsISupports> mSecurityInfo;
4729 // The channel that failed to load and resulted in an error page.
4730 // This only applies to error pages. Might be null.
4731 nsCOMPtr<nsIChannel> mFailedChannel;
4733 // if this document is part of a multipart document,
4734 // the ID can be used to distinguish it from the other parts.
4735 uint32_t mPartID;
4737 // Cycle collector generation in which we're certain that this document
4738 // won't be collected
4739 uint32_t mMarkedCCGeneration;
4741 PresShell* mPresShell;
4743 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4744 uint32_t mSubtreeModifiedDepth;
4746 // All images in process of being preloaded. This is a hashtable so
4747 // we can remove them as the real image loads start; that way we
4748 // make sure to not keep the image load going when no one cares
4749 // about it anymore.
4750 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4752 // A list of preconnects initiated by the preloader. This prevents
4753 // the same uri from being used more than once, and allows the dom
4754 // builder to not repeat the work of the preloader.
4755 nsDataHashtable<nsURIHashKey, bool> mPreloadedPreconnects;
4757 // Current depth of picture elements from parser
4758 uint32_t mPreloadPictureDepth;
4760 // Set if we've found a URL for the current picture
4761 nsString mPreloadPictureFoundSource;
4763 // If we're an external resource document, this will be non-null and will
4764 // point to our "display document": the one that all resource lookups should
4765 // go to.
4766 RefPtr<Document> mDisplayDocument;
4768 uint32_t mEventsSuppressed;
4770 // Any XHR ChannelEventQueues that were suspended on this document while
4771 // events were suppressed.
4772 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
4774 // Any postMessage events that were suspended on this document while events
4775 // were suppressed.
4776 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
4778 RefPtr<EventListener> mSuppressedEventListener;
4781 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
4783 uint32_t mIgnoreDestructiveWritesCounter;
4786 * The current frame request callback handle
4788 int32_t mFrameRequestCallbackCounter;
4790 // Count of live static clones of this document.
4791 uint32_t mStaticCloneCount;
4793 // If the document is currently printing (or in print preview) this will point
4794 // to the current static clone of this document. This is weak since the clone
4795 // also has a reference to this document.
4796 WeakPtr<Document> mLatestStaticClone;
4798 // Array of nodes that have been blocked to prevent user tracking.
4799 // They most likely have had their nsIChannel canceled by the URL
4800 // classifier. (Safebrowsing)
4802 // Weak nsINode pointers are used to allow nodes to disappear.
4803 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
4805 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
4806 // updated on every set of mScriptGlobalObject.
4807 nsPIDOMWindowInner* mWindow;
4809 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
4811 nsTArray<FrameRequest> mFrameRequestCallbacks;
4813 // The set of frame request callbacks that were canceled but which we failed
4814 // to find in mFrameRequestCallbacks.
4815 HashSet<int32_t> mCanceledFrameRequestCallbacks;
4817 // This object allows us to evict ourself from the back/forward cache. The
4818 // pointer is non-null iff we're currently in the bfcache.
4819 nsIBFCacheEntry* mBFCacheEntry;
4821 // Our base target.
4822 nsString mBaseTarget;
4824 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
4825 nsCOMPtr<nsIVariant> mStateObjectCached;
4827 uint32_t mInSyncOperationCount;
4829 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
4831 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
4833 uint32_t mBlockDOMContentLoaded;
4835 // Our live MediaQueryLists
4836 LinkedList<MediaQueryList> mDOMMediaQueryLists;
4838 // Array of observers
4839 nsTObserverArray<nsIDocumentObserver*> mObservers;
4841 // Flags for use counters used directly by this document.
4842 std::bitset<eUseCounter_Count> mUseCounters;
4843 // Flags for use counters used by any child documents of this document.
4844 std::bitset<eUseCounter_Count> mChildDocumentUseCounters;
4846 // The CSS property use counters.
4847 UniquePtr<StyleUseCounters> mStyleUseCounters;
4849 // Whether the user has interacted with the document or not:
4850 bool mUserHasInteracted;
4852 // We constantly update the user-interaction anti-tracking permission at any
4853 // user-interaction using a timer. This boolean value is set to true when this
4854 // timer is scheduled.
4855 bool mHasUserInteractionTimerScheduled;
4857 TimeStamp mPageUnloadingEventTimeStamp;
4859 RefPtr<DocGroup> mDocGroup;
4861 RefPtr<nsCommandManager> mMidasCommandManager;
4863 // The set of all the tracking script URLs. URLs are added to this set by
4864 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
4865 // existing in the set means the corresponding script isn't a tracking script.
4866 nsTHashtable<nsCStringHashKey> mTrackingScripts;
4868 // Pointer to our parser if we're currently in the process of being
4869 // parsed into.
4870 nsCOMPtr<nsIParser> mParser;
4872 // If the document was created from the the prototype cache there will be a
4873 // reference to the prototype document to allow tracing.
4874 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
4876 nsrefcnt mStackRefCnt;
4878 // Weak reference to our sink for in case we no longer have a parser. This
4879 // will allow us to flush out any pending stuff from the sink even if
4880 // EndLoad() has already happened.
4881 nsWeakPtr mWeakSink;
4883 // Our update nesting level
4884 uint32_t mUpdateNestLevel;
4886 // HTTPS-Only Mode Status
4887 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
4888 uint32_t mHttpsOnlyStatus;
4890 enum ViewportType : uint8_t {
4891 DisplayWidthHeight,
4892 Specified,
4893 Unknown,
4896 ViewportType mViewportType;
4898 // viewport-fit described by
4899 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
4900 ViewportFitType mViewportFit;
4902 PLDHashTable* mSubDocuments;
4904 DocHeaderData* mHeaderData;
4906 // For determining if this is a flash document which should be
4907 // blocked based on its principal.
4908 FlashClassification mFlashClassification;
4910 // Do not use this value directly. Call the |IsThirdPartyForFlashClassifier()|
4911 // method, which caches its result here.
4912 Maybe<bool> mIsThirdPartyForFlashClassifier;
4914 nsRevocableEventPtr<nsRunnableMethod<Document, void, false>>
4915 mPendingTitleChangeEvent;
4917 RefPtr<nsDOMNavigationTiming> mTiming;
4919 // Recorded time of change to 'loading' state.
4920 TimeStamp mLoadingTimeStamp;
4922 nsWeakPtr mAutoFocusElement;
4924 nsCString mScrollToRef;
4926 // Weak reference to the scope object (aka the script global object)
4927 // that, unlike mScriptGlobalObject, is never unset once set. This
4928 // is a weak reference to avoid leaks due to circular references.
4929 nsWeakPtr mScopeObject;
4931 // Array of intersection observers
4932 nsTHashtable<nsPtrHashKey<DOMIntersectionObserver>> mIntersectionObservers;
4934 RefPtr<DOMIntersectionObserver> mLazyLoadImageObserver;
4936 // Stack of top layer elements.
4937 nsTArray<nsWeakPtr> mTopLayer;
4939 // The root of the doc tree in which this document is in. This is only
4940 // non-null when this document is in fullscreen mode.
4941 nsWeakPtr mFullscreenRoot;
4943 RefPtr<DOMImplementation> mDOMImplementation;
4945 RefPtr<nsContentList> mImageMaps;
4947 // A set of responsive images keyed by address pointer.
4948 nsTHashtable<nsPtrHashKey<HTMLImageElement>> mResponsiveContent;
4950 // Tracking for plugins in the document.
4951 nsTHashtable<nsPtrHashKey<nsIObjectLoadingContent>> mPlugins;
4953 RefPtr<DocumentTimeline> mDocumentTimeline;
4954 LinkedList<DocumentTimeline> mTimelines;
4956 RefPtr<dom::ScriptLoader> mScriptLoader;
4958 // Tracker for animations that are waiting to start.
4959 // nullptr until GetOrCreatePendingAnimationTracker is called.
4960 RefPtr<PendingAnimationTracker> mPendingAnimationTracker;
4962 // A document "without a browsing context" that owns the content of
4963 // HTMLTemplateElement.
4964 RefPtr<Document> mTemplateContentsOwner;
4966 dom::ExternalResourceMap mExternalResourceMap;
4968 // ScreenOrientation "pending promise" as described by
4969 // http://www.w3.org/TR/screen-orientation/
4970 RefPtr<Promise> mOrientationPendingPromise;
4972 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
4973 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
4974 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
4976 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
4978 // The layout history state that should be used by nodes in this
4979 // document. We only actually store a pointer to it when:
4980 // 1) We have no script global object.
4981 // 2) We haven't had Destroy() called on us yet.
4982 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
4984 struct MetaViewportElementAndData;
4985 // An array of <meta name="viewport"> elements and their data.
4986 nsTArray<MetaViewportElementAndData> mMetaViewports;
4988 // These member variables cache information about the viewport so we don't
4989 // have to recalculate it each time.
4990 LayoutDeviceToScreenScale mScaleMinFloat;
4991 LayoutDeviceToScreenScale mScaleMaxFloat;
4992 LayoutDeviceToScreenScale mScaleFloat;
4993 CSSToLayoutDeviceScale mPixelRatio;
4995 CSSCoord mMinWidth;
4996 CSSCoord mMaxWidth;
4997 CSSCoord mMinHeight;
4998 CSSCoord mMaxHeight;
5000 RefPtr<EventListenerManager> mListenerManager;
5002 nsCOMPtr<nsIRequest> mOnloadBlocker;
5004 // Gecko-internal sheets used for extensions and such.
5005 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5006 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5008 // Member to store out last-selected stylesheet set.
5009 nsString mLastStyleSheetSet;
5010 nsString mPreferredStyleSheetSet;
5012 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5014 // We lazily calculate declaration blocks for SVG elements with mapped
5015 // attributes in Servo mode. This list contains all elements which need lazy
5016 // resolution.
5017 nsTHashtable<nsPtrHashKey<SVGElement>> mLazySVGPresElements;
5019 nsTHashtable<nsRefPtrHashKey<nsAtom>> mLanguagesUsed;
5021 // TODO(emilio): Is this hot enough to warrant to be cached?
5022 RefPtr<nsAtom> mLanguageFromCharset;
5024 // Restyle root for servo's style system.
5026 // We store this as an nsINode, rather than as an Element, so that we can
5027 // store the Document node as the restyle root if the entire document (along
5028 // with all document-level native-anonymous content) needs to be restyled.
5030 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5031 // root corresponds to.
5032 nsCOMPtr<nsINode> mServoRestyleRoot;
5033 uint32_t mServoRestyleRootDirtyBits;
5035 // Used in conjunction with the create-an-element-for-the-token algorithm to
5036 // prevent custom element constructors from being able to use document.open(),
5037 // document.close(), and document.write() when they are invoked by the parser.
5038 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5040 // Count of unload/beforeunload/pagehide operations in progress.
5041 uint32_t mIgnoreOpensDuringUnloadCounter;
5043 nsCOMPtr<nsIDOMXULCommandDispatcher>
5044 mCommandDispatcher; // [OWNER] of the focus tracker
5046 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5047 RefPtr<XULPersist> mXULPersist;
5048 RefPtr<ChromeObserver> mChromeObserver;
5050 RefPtr<HTMLAllCollection> mAll;
5052 // document lightweight theme for use with :-moz-lwtheme,
5053 // :-moz-lwtheme-brighttext and :-moz-lwtheme-darktext
5054 DocumentTheme mDocLWTheme;
5056 // Pres shell resolution saved before entering fullscreen mode.
5057 float mSavedResolution;
5059 // Pres shell resolution saved before creating a MobileViewportManager.
5060 float mSavedResolutionBeforeMVM;
5062 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5064 bool mHasStoragePermission;
5066 // Document generation. Gets incremented everytime it changes.
5067 int32_t mGeneration;
5069 // Cached TabSizes values for the document.
5070 int32_t mCachedTabSizeGeneration;
5071 nsTabSizes mCachedTabSizes;
5073 // This is equal to document's principal but with an isolation key. See
5074 // StoragePrincipalHelper.h to know more.
5075 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5077 // The cached storage principal for this document.
5078 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5079 // which is required due to its CloneDocHelper() call site. :-(
5080 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5082 // The principal to use for the content blocking allow list.
5083 nsCOMPtr<nsIPrincipal> mContentBlockingAllowListPrincipal;
5085 // See GetNextFormNumber and GetNextControlNumber.
5086 int32_t mNextFormNumber;
5087 int32_t mNextControlNumber;
5089 // Scope preloads per document. This is used by speculative loading as well.
5090 PreloadService mPreloadService;
5092 public:
5093 // Needs to be public because the bindings code pokes at it.
5094 JS::ExpandoAndGeneration mExpandoAndGeneration;
5096 bool HasPendingInitialTranslation();
5098 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5099 mL10nProtoElements;
5101 void TraceProtos(JSTracer* aTrc);
5103 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5104 void SetSavedResolutionBeforeMVM(float aResolution) {
5105 mSavedResolutionBeforeMVM = aResolution;
5109 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5112 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5113 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5114 * object is deleted.
5116 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5117 public:
5119 * @param aSubTreeOwner The document in which a subtree will be modified.
5120 * @param aTarget The target of the possible DOMSubtreeModified event.
5121 * Can be nullptr, in which case mozAutoSubtreeModified
5122 * is just used to batch DOM mutations.
5124 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5125 UpdateTarget(aSubtreeOwner, aTarget);
5128 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5130 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5131 if (mSubtreeOwner) {
5132 mSubtreeOwner->MutationEventDispatched(mTarget);
5135 mTarget = aTarget;
5136 mSubtreeOwner = aSubtreeOwner;
5137 if (mSubtreeOwner) {
5138 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5142 private:
5143 nsCOMPtr<nsINode> mTarget;
5144 RefPtr<Document> mSubtreeOwner;
5147 class MOZ_STACK_CLASS nsAutoSyncOperation {
5148 public:
5149 explicit nsAutoSyncOperation(Document* aDocument);
5150 ~nsAutoSyncOperation();
5152 private:
5153 nsTArray<RefPtr<Document>> mDocuments;
5154 uint32_t mMicroTaskLevel;
5157 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5158 public:
5159 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5160 : mDocument(aDocument) {
5161 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5164 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5165 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5168 private:
5169 Document* mDocument;
5172 class MOZ_RAII IgnoreOpensDuringUnload final {
5173 public:
5174 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5175 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5178 ~IgnoreOpensDuringUnload() {
5179 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5182 private:
5183 Document* mDoc;
5186 bool IsInActiveTab(Document* aDoc);
5188 } // namespace dom
5189 } // namespace mozilla
5191 // XXX These belong somewhere else
5192 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5193 bool aLoadedAsData = false);
5195 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5196 bool aLoadedAsData = false,
5197 bool aIsPlainDocument = false);
5199 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult);
5201 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult);
5203 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult);
5205 // Enum for requesting a particular type of document when creating a doc
5206 enum DocumentFlavor {
5207 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5208 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5209 DocumentFlavorSVG, // SVGDocument
5210 DocumentFlavorXML, // XMLDocument
5211 DocumentFlavorPlain, // Just a Document
5214 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5215 // -- this method will not attempt to get a principal based on aDocumentURI.
5216 // Also, both aDocumentURI and aBaseURI must not be null.
5217 nsresult NS_NewDOMDocument(
5218 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5219 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5220 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5221 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5223 nsresult NS_NewPluginDocument(mozilla::dom::Document** aInstancePtrResult);
5225 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5226 mozilla::dom::Document* ownerDoc = OwnerDoc();
5228 return ownerDoc != this ? ownerDoc : nullptr;
5231 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5233 inline bool ShouldUseNACScope(const nsINode* aNode) {
5234 return aNode->IsInNativeAnonymousSubtree();
5237 inline bool ShouldUseUAWidgetScope(const nsINode* aNode) {
5238 return aNode->HasBeenInUAWidget();
5241 inline mozilla::dom::ParentObject nsINode::GetParentObject() const {
5242 mozilla::dom::ParentObject p(OwnerDoc());
5243 // Note that mReflectionScope is a no-op for chrome, and other places
5244 // where we don't check this value.
5245 if (ShouldUseNACScope(this)) {
5246 p.mReflectionScope = mozilla::dom::ReflectionScope::NAC;
5247 } else if (ShouldUseUAWidgetScope(this)) {
5248 p.mReflectionScope = mozilla::dom::ReflectionScope::UAWidget;
5250 return p;
5253 inline mozilla::dom::Document* nsINode::AsDocument() {
5254 MOZ_ASSERT(IsDocument());
5255 return static_cast<mozilla::dom::Document*>(this);
5258 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5259 MOZ_ASSERT(IsDocument());
5260 return static_cast<const mozilla::dom::Document*>(this);
5263 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5264 return static_cast<nsINode*>(aDoc);
5267 #endif /* mozilla_dom_Document_h___ */