Bug 1660051 [wpt PR 25111] - Origin isolation: expand getter test coverage, a=testonly
[gecko.git] / dom / base / Document.h
blob0fb35054651a55c0b45687b54c73ebbed4d7228b
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/. */
6 #ifndef mozilla_dom_Document_h___
7 #define mozilla_dom_Document_h___
9 #include "mozilla/EventStates.h" // for EventStates
10 #include "mozilla/FlushType.h" // for enum
11 #include "mozilla/MozPromise.h" // for MozPromise
12 #include "mozilla/FunctionRef.h" // for FunctionRef
13 #include "nsCOMArray.h" // for member
14 #include "nsCompatibility.h" // for member
15 #include "nsCOMPtr.h" // for member
16 #include "nsGkAtoms.h" // for static class members
17 #include "nsIApplicationCacheContainer.h"
18 #include "nsIContentViewer.h"
19 #include "nsIInterfaceRequestor.h"
20 #include "nsILoadContext.h"
21 #include "nsILoadGroup.h" // for member (in nsCOMPtr)
22 #include "nsINode.h" // for base class
23 #include "nsIParser.h"
24 #include "nsIChannelEventSink.h"
25 #include "nsIProgressEventSink.h"
26 #include "nsIRadioGroupContainer.h"
27 #include "nsIScriptObjectPrincipal.h"
28 #include "nsIURI.h" // for use in inline functions
29 #include "nsIWeakReferenceUtils.h" // for nsWeakPtr
30 #include "nsPIDOMWindow.h" // for use in inline functions
31 #include "nsPropertyTable.h" // for member
32 #include "nsStringFwd.h"
33 #include "nsStubMutationObserver.h"
34 #include "nsTHashtable.h" // for member
35 #include "nsURIHashKey.h"
36 #include "mozilla/UseCounter.h"
37 #include "mozilla/WeakPtr.h"
38 #include "Units.h"
39 #include "nsContentListDeclarations.h"
40 #include "nsExpirationTracker.h"
41 #include "nsClassHashtable.h"
42 #include "nsWindowSizes.h"
43 #include "ReferrerInfo.h"
44 #include "mozilla/Attributes.h"
45 #include "mozilla/CallState.h"
46 #include "mozilla/CORSMode.h"
47 #include "mozilla/dom/DispatcherTrait.h"
48 #include "mozilla/dom/DocumentOrShadowRoot.h"
49 #include "mozilla/dom/ViewportMetaData.h"
50 #include "mozilla/HashTable.h"
51 #include "mozilla/LinkedList.h"
52 #include "mozilla/NotNull.h"
53 #include "mozilla/PreloadService.h"
54 #include "mozilla/SegmentedVector.h"
55 #include "mozilla/TimeStamp.h"
56 #include "mozilla/UniquePtr.h"
57 #include <bitset> // for member
59 // XXX We need to include this here to ensure that DefaultDeleter for Servo
60 // types is specialized before the template is instantiated. Probably, this
61 // should be included at some other place already that's generated by cbindgen.
62 #include "mozilla/ServoStyleConsts.h"
64 // windows.h #defines CreateEvent
65 #ifdef CreateEvent
66 # undef CreateEvent
67 #endif
69 #ifdef MOZILLA_INTERNAL_API
70 # include "mozilla/dom/DocumentBinding.h"
71 #else
72 namespace mozilla {
73 namespace dom {
74 class ElementCreationOptionsOrString;
75 } // namespace dom
76 } // namespace mozilla
77 #endif // MOZILLA_INTERNAL_API
79 class gfxUserFontSet;
80 class imgIRequest;
81 class nsCachableElementsByNameNodeList;
82 class nsCommandManager;
83 class nsContentList;
84 class nsDocShell;
85 class nsDOMNavigationTiming;
86 class nsFrameLoader;
87 class nsFrameLoaderOwner;
88 class nsGlobalWindowInner;
89 class nsHtml5TreeOpExecutor;
90 class nsHTMLCSSStyleSheet;
91 class nsHTMLDocument;
92 class nsHTMLStyleSheet;
93 class nsGenericHTMLElement;
94 class nsIBFCacheEntry;
95 class nsIContent;
96 class nsIContentSink;
97 class nsIDocShell;
98 class nsIDocShellTreeItem;
99 class nsIDocumentEncoder;
100 class nsIDocumentObserver;
101 class nsIDOMXULCommandDispatcher;
102 class nsIHTMLCollection;
103 class nsILayoutHistoryState;
104 class nsIObjectLoadingContent;
105 class nsIRequest;
106 class nsIRunnable;
107 class nsIScriptGlobalObject;
108 class nsISecurityConsoleMessage;
109 class nsIStructuredCloneContainer;
110 class nsIVariant;
111 class nsViewManager;
112 class nsPresContext;
113 class nsRange;
114 class nsSimpleContentList;
115 class nsTextNode;
116 class nsDOMCaretPosition;
117 class nsViewportInfo;
118 class nsIGlobalObject;
119 class nsIAppWindow;
120 class nsXULPrototypeDocument;
121 class nsXULPrototypeElement;
122 class nsIPermissionDelegateHandler;
123 struct nsFont;
124 struct StyleUseCounters;
126 namespace mozilla {
127 class AbstractThread;
128 class StyleSheet;
129 class EditorCommand;
130 class Encoding;
131 class ErrorResult;
132 class EventListenerManager;
133 class FullscreenExit;
134 class FullscreenRequest;
135 struct LangGroupFontPrefs;
136 class PendingAnimationTracker;
137 class PermissionDelegateHandler;
138 class PresShell;
139 class ServoStyleSet;
140 enum class StyleOrigin : uint8_t;
141 class SMILAnimationController;
142 enum class StyleCursorKind : uint8_t;
143 enum class StylePrefersColorScheme : uint8_t;
144 template <typename>
145 class OwningNonNull;
146 struct URLExtraData;
148 namespace css {
149 class Loader;
150 class ImageLoader;
151 class Rule;
152 } // namespace css
154 namespace dom {
155 class AnonymousContent;
156 class Attr;
157 class XULBroadcastManager;
158 class XULPersist;
159 class ChromeObserver;
160 class ClientInfo;
161 class ClientState;
162 class CDATASection;
163 class Comment;
164 class CSSImportRule;
165 struct CustomElementDefinition;
166 class DocumentL10n;
167 class DocumentFragment;
168 class DocumentTimeline;
169 class DocumentType;
170 class DOMImplementation;
171 class DOMIntersectionObserver;
172 class DOMStringList;
173 class Element;
174 class Event;
175 struct FailedCertSecurityInfo;
176 class FeaturePolicy;
177 class FontFaceSet;
178 class FrameRequestCallback;
179 class ImageTracker;
180 class HTMLAllCollection;
181 class HTMLBodyElement;
182 class HTMLMetaElement;
183 class HTMLDialogElement;
184 class HTMLSharedElement;
185 class HTMLImageElement;
186 struct LifecycleCallbackArgs;
187 class Link;
188 class Location;
189 class MediaQueryList;
190 struct NetErrorInfo;
191 class NodeFilter;
192 class NodeIterator;
193 enum class OrientationType : uint8_t;
194 class ProcessingInstruction;
195 class Promise;
196 class ScriptLoader;
197 class Selection;
198 class ServiceWorkerDescriptor;
199 class SVGDocument;
200 class SVGElement;
201 class SVGSVGElement;
202 class SVGUseElement;
203 class Touch;
204 class TouchList;
205 class TreeWalker;
206 enum class ViewportFitType : uint8_t;
207 class XPathEvaluator;
208 class XPathExpression;
209 class XPathNSResolver;
210 class XPathResult;
211 class BrowsingContext;
213 class nsDocumentOnStack;
214 class nsUnblockOnloadEvent;
216 template <typename, typename>
217 class CallbackObjectHolder;
219 enum class CallerType : uint32_t;
221 enum BFCacheStatus {
222 NOT_ALLOWED = 1 << 0, // Status 0
223 EVENT_HANDLING_SUPPRESSED = 1 << 1, // Status 1
224 SUSPENDED = 1 << 2, // Status 2
225 UNLOAD_LISTENER = 1 << 3, // Status 3
226 REQUEST = 1 << 4, // Status 4
227 ACTIVE_GET_USER_MEDIA = 1 << 5, // Status 5
228 ACTIVE_PEER_CONNECTION = 1 << 6, // Status 6
229 CONTAINS_EME_CONTENT = 1 << 7, // Status 7
230 CONTAINS_MSE_CONTENT = 1 << 8, // Status 8
231 HAS_ACTIVE_SPEECH_SYNTHESIS = 1 << 9, // Status 9
232 HAS_USED_VR = 1 << 10, // Status 10
233 CONTAINS_REMOTE_SUBFRAMES = 1 << 11, // Status 11
234 NOT_ONLY_TOPLEVEL_IN_BCG = 1 << 12 // Status 12
237 } // namespace dom
238 } // namespace mozilla
240 namespace mozilla {
241 namespace net {
242 class ChannelEventQueue;
243 } // namespace net
244 } // namespace mozilla
246 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
247 #define NS_IDOCUMENT_IID \
249 0xce1f7627, 0x7109, 0x4977, { \
250 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
254 namespace mozilla {
255 namespace dom {
257 class Document;
258 class DOMStyleSheetSetList;
259 class ResizeObserver;
260 class ResizeObserverController;
261 class PostMessageEvent;
263 // Document states
265 // RTL locale: specific to the XUL localedir attribute
266 #define NS_DOCUMENT_STATE_RTL_LOCALE NS_DEFINE_EVENT_STATE_MACRO(0)
267 // Window activation status
268 #define NS_DOCUMENT_STATE_WINDOW_INACTIVE NS_DEFINE_EVENT_STATE_MACRO(1)
270 class DocHeaderData {
271 public:
272 DocHeaderData(nsAtom* aField, const nsAString& aData)
273 : mField(aField), mData(aData), mNext(nullptr) {}
275 ~DocHeaderData(void) { delete mNext; }
277 RefPtr<nsAtom> mField;
278 nsString mData;
279 DocHeaderData* mNext;
282 class ExternalResourceMap {
283 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
285 public:
287 * A class that represents an external resource load that has begun but
288 * doesn't have a document yet. Observers can be registered on this object,
289 * and will be notified after the document is created. Observers registered
290 * after the document has been created will NOT be notified. When observers
291 * are notified, the subject will be the newly-created document, the topic
292 * will be "external-resource-document-created", and the data will be null.
293 * If document creation fails for some reason, observers will still be
294 * notified, with a null document pointer.
296 class ExternalResourceLoad : public nsISupports {
297 public:
298 virtual ~ExternalResourceLoad() = default;
300 void AddObserver(nsIObserver* aObserver) {
301 MOZ_ASSERT(aObserver, "Must have observer");
302 mObservers.AppendElement(aObserver);
305 const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
307 protected:
308 AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
311 ExternalResourceMap();
314 * Request an external resource document. This does exactly what
315 * Document::RequestExternalResource is documented to do.
317 Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
318 nsINode* aRequestingNode,
319 Document* aDisplayDocument,
320 ExternalResourceLoad** aPendingLoad);
323 * Enumerate the resource documents. See
324 * Document::EnumerateExternalResources.
326 void EnumerateResources(SubDocEnumFunc aCallback);
329 * Traverse ourselves for cycle-collection
331 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
334 * Shut ourselves down (used for cycle-collection unlink), as well
335 * as for document destruction.
337 void Shutdown() {
338 mPendingLoads.Clear();
339 mMap.Clear();
340 mHaveShutDown = true;
343 bool HaveShutDown() const { return mHaveShutDown; }
345 // Needs to be public so we can traverse them sanely
346 struct ExternalResource {
347 ~ExternalResource();
348 RefPtr<Document> mDocument;
349 nsCOMPtr<nsIContentViewer> mViewer;
350 nsCOMPtr<nsILoadGroup> mLoadGroup;
353 // Hide all our viewers
354 void HideViewers();
356 // Show all our viewers
357 void ShowViewers();
359 protected:
360 class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
361 ~PendingLoad() = default;
363 public:
364 explicit PendingLoad(Document* aDisplayDocument)
365 : mDisplayDocument(aDisplayDocument) {}
367 NS_DECL_ISUPPORTS
368 NS_DECL_NSISTREAMLISTENER
369 NS_DECL_NSIREQUESTOBSERVER
372 * Start aURI loading. This will perform the necessary security checks and
373 * so forth.
375 nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
376 nsINode* aRequestingNode);
378 * Set up an nsIContentViewer based on aRequest. This is guaranteed to
379 * put null in *aViewer and *aLoadGroup on all failures.
381 nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
382 nsILoadGroup** aLoadGroup);
384 private:
385 RefPtr<Document> mDisplayDocument;
386 nsCOMPtr<nsIStreamListener> mTargetListener;
387 nsCOMPtr<nsIURI> mURI;
389 friend class PendingLoad;
391 class LoadgroupCallbacks final : public nsIInterfaceRequestor {
392 ~LoadgroupCallbacks() = default;
394 public:
395 explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
396 : mCallbacks(aOtherCallbacks) {}
397 NS_DECL_ISUPPORTS
398 NS_DECL_NSIINTERFACEREQUESTOR
399 private:
400 // The only reason it's safe to hold a strong ref here without leaking is
401 // that the notificationCallbacks on a loadgroup aren't the docshell itself
402 // but a shim that holds a weak reference to the docshell.
403 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
405 // Use shims for interfaces that docshell implements directly so that we
406 // don't hand out references to the docshell. The shims should all allow
407 // getInterface back on us, but other than that each one should only
408 // implement one interface.
410 // XXXbz I wish we could just derive the _allcaps thing from _i
411 #define DECL_SHIM(_i, _allcaps) \
412 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
413 ~_i##Shim() {} \
415 public: \
416 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
417 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
418 NS_ASSERTION(mIfReq, "Expected non-null here"); \
419 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
421 NS_DECL_ISUPPORTS \
422 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
423 NS_FORWARD_##_allcaps(mRealPtr->) private \
424 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
425 nsCOMPtr<_i> mRealPtr; \
428 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
429 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
430 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
431 DECL_SHIM(nsIApplicationCacheContainer, NSIAPPLICATIONCACHECONTAINER)
432 #undef DECL_SHIM
436 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
437 * when this is called if the URI didn't result in an XML document. This
438 * function makes sure to remove the pending load for aURI, if any, from our
439 * hashtable, and to notify its observers, if any.
441 nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
442 nsILoadGroup* aLoadGroup,
443 Document* aDisplayDocument);
445 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
446 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
447 bool mHaveShutDown;
450 // The current status for a preload.
451 enum class SheetPreloadStatus : uint8_t {
452 // There's no need to preload anything, the sheet is already in-memory.
453 AlreadyComplete,
454 // The load is in-progress. There's no guarantee that a load was started, it
455 // could be coalesced with other redundant loads.
456 InProgress,
457 // Something went wrong, and we errored out.
458 Errored,
461 //----------------------------------------------------------------------
463 // Document interface. This is implemented by all document objects in
464 // Gecko.
465 class Document : public nsINode,
466 public DocumentOrShadowRoot,
467 public nsSupportsWeakReference,
468 public nsIRadioGroupContainer,
469 public nsIScriptObjectPrincipal,
470 public nsIApplicationCacheContainer,
471 public nsStubMutationObserver,
472 public DispatcherTrait,
473 public SupportsWeakPtr {
474 friend class DocumentOrShadowRoot;
476 protected:
477 explicit Document(const char* aContentType);
478 virtual ~Document();
480 Document(const Document&) = delete;
481 Document& operator=(const Document&) = delete;
483 public:
484 typedef dom::ExternalResourceMap::ExternalResourceLoad ExternalResourceLoad;
485 typedef dom::ReferrerPolicy ReferrerPolicyEnum;
486 using AdoptedStyleSheetCloneCache =
487 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
489 // nsINode overrides the new operator for DOM Arena allocation.
490 // to use the default one, we need to bring it back again
491 void* operator new(size_t aSize) { return ::operator new(aSize); }
494 * Called when XPCOM shutdown.
496 static void Shutdown();
498 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
500 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
502 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
504 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
505 nsINode)
507 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
508 do { \
509 NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(mObservers, func_, params_); \
510 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
511 looks bogus. */ \
512 if (PresShell* presShell = GetObservingPresShell()) { \
513 presShell->func_ params_; \
515 } while (0)
517 // nsIApplicationCacheContainer
518 NS_DECL_NSIAPPLICATIONCACHECONTAINER
520 // nsIRadioGroupContainer
521 NS_IMETHOD WalkRadioGroup(const nsAString& aName, nsIRadioVisitor* aVisitor,
522 bool aFlushContent) final {
523 return DocumentOrShadowRoot::WalkRadioGroup(aName, aVisitor, aFlushContent);
526 void SetCurrentRadioButton(const nsAString& aName,
527 HTMLInputElement* aRadio) final {
528 DocumentOrShadowRoot::SetCurrentRadioButton(aName, aRadio);
531 HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) final {
532 return DocumentOrShadowRoot::GetCurrentRadioButton(aName);
535 NS_IMETHOD
536 GetNextRadioButton(const nsAString& aName, const bool aPrevious,
537 HTMLInputElement* aFocusedRadio,
538 HTMLInputElement** aRadioOut) final {
539 return DocumentOrShadowRoot::GetNextRadioButton(aName, aPrevious,
540 aFocusedRadio, aRadioOut);
542 void AddToRadioGroup(const nsAString& aName, HTMLInputElement* aRadio) final {
543 DocumentOrShadowRoot::AddToRadioGroup(aName, aRadio);
545 void RemoveFromRadioGroup(const nsAString& aName,
546 HTMLInputElement* aRadio) final {
547 DocumentOrShadowRoot::RemoveFromRadioGroup(aName, aRadio);
549 uint32_t GetRequiredRadioCount(const nsAString& aName) const final {
550 return DocumentOrShadowRoot::GetRequiredRadioCount(aName);
552 void RadioRequiredWillChange(const nsAString& aName,
553 bool aRequiredAdded) final {
554 DocumentOrShadowRoot::RadioRequiredWillChange(aName, aRequiredAdded);
556 bool GetValueMissingState(const nsAString& aName) const final {
557 return DocumentOrShadowRoot::GetValueMissingState(aName);
559 void SetValueMissingState(const nsAString& aName, bool aValue) final {
560 return DocumentOrShadowRoot::SetValueMissingState(aName, aValue);
563 nsIPrincipal* EffectiveStoragePrincipal() const;
565 // nsIScriptObjectPrincipal
566 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
568 nsIPrincipal* GetEffectiveStoragePrincipal() final {
569 return EffectiveStoragePrincipal();
572 // You should probably not be using this function, since it performs no checks
573 // to ensure that the partitioned principal should really be used here. It is
574 // only designed to be used in very specific circumstances, such as when
575 // inheriting the document/storage principal.
576 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
578 void ClearActiveStoragePrincipal() { mActiveStoragePrincipal = nullptr; }
580 nsIPrincipal* GetContentBlockingAllowListPrincipal() const {
581 return mContentBlockingAllowListPrincipal;
584 // EventTarget
585 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
586 EventListenerManager* GetOrCreateListenerManager() override;
587 EventListenerManager* GetExistingListenerManager() const override;
589 // This helper class must be set when we dispatch beforeunload and unload
590 // events in order to avoid unterminate sync XHRs.
591 class MOZ_RAII PageUnloadingEventTimeStamp {
592 RefPtr<Document> mDocument;
593 bool mSet;
595 public:
596 explicit PageUnloadingEventTimeStamp(Document* aDocument)
597 : mDocument(aDocument), mSet(false) {
598 MOZ_ASSERT(aDocument);
599 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
600 mDocument->SetPageUnloadingEventTimeStamp();
601 mSet = true;
605 ~PageUnloadingEventTimeStamp() {
606 if (mSet) {
607 mDocument->CleanUnloadEventsTimeStamp();
613 * Let the document know that we're starting to load data into it.
614 * @param aCommand The parser command. Must not be null.
615 * XXXbz It's odd to have that here.
616 * @param aChannel The channel the data will come from. The channel must be
617 * able to report its Content-Type.
618 * @param aLoadGroup The loadgroup this document should use from now on.
619 * Note that the document might not be the only thing using
620 * this loadgroup.
621 * @param aContainer The container this document is in. This may be null.
622 * XXXbz maybe we should make it more explicit (eg make the
623 * container an nsIWebNavigation or nsIDocShell or
624 * something)?
625 * @param [out] aDocListener the listener to pump data from the channel into.
626 * Generally this will be the parser this document
627 * sets up, or some sort of data-handler for media
628 * documents.
629 * @param aReset whether the document should call Reset() on itself. If this
630 * is false, the document will NOT set its principal to the
631 * channel's owner, will not clear any event listeners that are
632 * already set on it, etc.
633 * @param aSink The content sink to use for the data. If this is null and
634 * the document needs a content sink, it will create one based
635 * on whatever it knows about the data it's going to load.
636 * This MUST be null if the underlying document is an HTML
637 * document. Even in the XML case, please don't add new calls
638 * with non-null sink.
640 * Once this has been called, the document will return false for
641 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
642 * sure this happens is the responsibility of the caller of
643 * StartDocumentLoad().
645 * This function has an implementation, and does some setup, but does NOT set
646 * *aDocListener; this is the job of subclasses.
648 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
649 nsILoadGroup* aLoadGroup,
650 nsISupports* aContainer,
651 nsIStreamListener** aDocListener,
652 bool aReset,
653 nsIContentSink* aSink = nullptr) = 0;
654 void StopDocumentLoad();
656 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
657 virtual bool SuppressParserErrorElement() { return false; }
659 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
660 virtual bool SuppressParserErrorConsoleMessages() { return false; }
662 // nsINode
663 bool IsNodeOfType(uint32_t aFlags) const final;
664 nsresult InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
665 bool aNotify) override;
666 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
667 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
668 return NS_ERROR_NOT_IMPLEMENTED;
670 nsresult CloneDocHelper(Document* clone) const;
672 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
675 * Signal that the document title may have changed
676 * (see Document::GetTitle).
677 * @param aBoundTitleElement true if an HTML or SVG <title> element
678 * has just been bound to the document.
680 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
683 * Return the URI for the document. May return null. If it ever stops being
684 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
685 * also never return null.
687 * The value returned corresponds to the "document's address" in
688 * HTML5. As such, it may change over the lifetime of the document, for
689 * instance as a result of the user navigating to a fragment identifier on
690 * the page, or as a result to a call to pushState() or replaceState().
692 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
694 nsIURI* GetDocumentURI() const { return mDocumentURI; }
697 * Return the original URI of the document. This is the same as the
698 * document's URI unless that has changed from its original value (for
699 * example, due to history.pushState() or replaceState() being invoked on the
700 * document).
702 * This method corresponds to the "creation URL" in HTML5 and, once set,
703 * doesn't change over the lifetime of the document.
705 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
707 nsIURI* GetOriginalURI() const { return mOriginalURI; }
710 * Return the base domain of the document. This has been computed using
711 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
712 * checks. When the URI of the document changes, this value is recomputed.
714 nsCString GetBaseDomain() const { return mBaseDomain; }
717 * Set the URI for the document. This also sets the document's original URI,
718 * if it's null.
720 void SetDocumentURI(nsIURI* aURI);
723 * Set the URI for the document loaded via XHR, when accessed from
724 * chrome privileged script.
726 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
729 * Set the base URI for the document loaded via XHR, when accessed from
730 * chrome privileged script.
732 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
735 * The CSP in general is stored in the ClientInfo, but we also cache
736 * the CSP on the document so subresources loaded within a document
737 * can query that cached CSP instead of having to deserialize the CSP
738 * from the Client.
740 * Please note that at the time of CSP parsing the Client is not
741 * available yet, hence we sync CSP of document and Client when the
742 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
744 nsIContentSecurityPolicy* GetCsp() const;
745 void SetCsp(nsIContentSecurityPolicy* aCSP);
747 nsIContentSecurityPolicy* GetPreloadCsp() const;
748 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
750 void GetCspJSON(nsString& aJSON);
753 * Set referrer policy and upgrade-insecure-requests flags
755 void ApplySettingsFromCSP(bool aSpeculative);
757 already_AddRefed<nsIParser> CreatorParserOrNull() {
758 nsCOMPtr<nsIParser> parser = mParser;
759 return parser.forget();
763 * ReferrerInfo getter for Document.webidl.
765 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
767 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
769 nsIReferrerInfo* GetPreloadReferrerInfo() const {
770 return mPreloadReferrerInfo;
773 * Return the referrer policy of the document. Return "default" if there's no
774 * valid meta referrer tag found in the document.
775 * Referrer policy should be inherited from parent if the iframe is srcdoc
777 ReferrerPolicyEnum GetReferrerPolicy() const;
780 * GetReferrerPolicy() for Document.webidl.
782 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
785 * If true, this flag indicates that all mixed content subresource
786 * loads for this document (and also embeded browsing contexts) will
787 * be blocked.
789 bool GetBlockAllMixedContent(bool aPreload) const {
790 if (aPreload) {
791 return mBlockAllMixedContentPreloads;
793 return mBlockAllMixedContent;
797 * If true, this flag indicates that all subresource loads for this
798 * document need to be upgraded from http to https.
799 * This flag becomes true if the CSP of the document itself, or any
800 * of the document's ancestors up to the toplevel document makes use
801 * of the CSP directive 'upgrade-insecure-requests'.
803 bool GetUpgradeInsecureRequests(bool aPreload) const {
804 if (aPreload) {
805 return mUpgradeInsecurePreloads;
807 return mUpgradeInsecureRequests;
810 void SetReferrerInfo(nsIReferrerInfo* aReferrerInfo) {
811 mReferrerInfo = aReferrerInfo;
815 * Referrer policy from <meta name="referrer" content=`policy`>
816 * will have higher priority than referrer policy from Referrer-Policy
817 * header. So override the old ReferrerInfo if we get one from meta
819 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
820 bool aPreload) {
821 ReferrerPolicyEnum policy =
822 ReferrerInfo::ReferrerPolicyFromMetaString(aMetaReferrer);
823 // The empty string "" corresponds to no referrer policy, causing a fallback
824 // to a referrer policy defined elsewhere.
825 if (policy == ReferrerPolicy::_empty) {
826 return;
829 MOZ_ASSERT(mReferrerInfo);
830 MOZ_ASSERT(mPreloadReferrerInfo);
832 if (aPreload) {
833 mPreloadReferrerInfo =
834 static_cast<mozilla::dom::ReferrerInfo*>((mPreloadReferrerInfo).get())
835 ->CloneWithNewPolicy(policy);
836 } else {
837 mReferrerInfo =
838 static_cast<mozilla::dom::ReferrerInfo*>((mReferrerInfo).get())
839 ->CloneWithNewPolicy(policy);
844 * Set the principals responsible for this document. Chances are, you do not
845 * want to be using this.
847 void SetPrincipals(nsIPrincipal* aPrincipal,
848 nsIPrincipal* aPartitionedPrincipal);
851 * Returns true if exempt from HTTPS-Only Mode upgrade.
853 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
856 * Return the LoadGroup for the document. May return null.
858 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
859 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
860 return group.forget();
864 * Return the fallback base URL for this document, as defined in the HTML
865 * specification. Note that this can return null if there is no document URI.
867 * XXXbz: This doesn't implement the bits for about:blank yet.
869 nsIURI* GetFallbackBaseURI() const {
870 if (mIsSrcdocDocument && mParentDocument) {
871 return mParentDocument->GetDocBaseURI();
873 return mDocumentURI;
877 * Return the referrer from document URI as defined in the Referrer Policy
878 * specification.
879 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
880 * While document is an iframe srcdoc document, let document be document's
881 * browsing context's browsing context container's node document.
882 * Then referrer should be document's URL
885 nsIURI* GetDocumentURIAsReferrer() const {
886 if (mIsSrcdocDocument && mParentDocument) {
887 return mParentDocument->GetDocumentURIAsReferrer();
889 return mDocumentURI;
893 * Return the base URI for relative URIs in the document (the document uri
894 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
895 * returned URI could be null if there is no document URI. If the document is
896 * a srcdoc document and has no explicit base URL, return the parent
897 * document's base URL.
899 nsIURI* GetDocBaseURI() const {
900 if (mDocumentBaseURI) {
901 return mDocumentBaseURI;
903 return GetFallbackBaseURI();
906 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
908 void SetBaseURI(nsIURI* aURI);
911 * Resolves a URI based on the document's base URI.
913 Result<nsCOMPtr<nsIURI>, nsresult> ResolveWithBaseURI(const nsAString& aURI);
916 * Return the URL data which style system needs for resolving url value.
917 * This method attempts to use the cached object in mCachedURLData, but
918 * if the base URI, document URI, or principal has changed since last
919 * call to this function, or the function is called the first time for
920 * the document, a new one is created.
922 URLExtraData* DefaultStyleAttrURLData();
925 * Get/Set the base target of a link in a document.
927 void GetBaseTarget(nsAString& aBaseTarget) const {
928 aBaseTarget = mBaseTarget;
931 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
934 * Return a standard name for the document's character set.
936 NotNull<const Encoding*> GetDocumentCharacterSet() const {
937 return mCharacterSet;
941 * Set the document's character encoding.
943 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
945 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
947 // This method MUST be called before SetDocumentCharacterSet if
948 // you're planning to call both.
949 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
950 mCharacterSetSource = aCharsetSource;
954 * Get the Content-Type of this document.
956 void GetContentType(nsAString& aContentType);
959 * Set the Content-Type of this document.
961 virtual void SetContentType(const nsAString& aContentType);
964 * Return the language of this document.
966 void GetContentLanguage(nsAString& aContentLanguage) const {
967 CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
970 // The states BidiEnabled and MathMLEnabled should persist across multiple
971 // views (screen, print) of the same document.
974 * Check if the document contains bidi data.
975 * If so, we have to apply the Unicode Bidi Algorithm.
977 bool GetBidiEnabled() const { return mBidiEnabled; }
980 * Indicate the document contains bidi data.
981 * Currently, we cannot disable bidi, because once bidi is enabled,
982 * it affects a frame model irreversibly, and plays even though
983 * the document no longer contains bidi data.
985 void SetBidiEnabled() { mBidiEnabled = true; }
987 void SetMathMLEnabled() { mMathMLEnabled = true; }
990 * Ask this document whether it's the initial document in its window.
992 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
995 * Tell this document that it's the initial document in its window. See
996 * comments on mIsInitialDocumentInWindow for when this should be called.
998 void SetIsInitialDocument(bool aIsInitialDocument);
1000 void SetLoadedAsData(bool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
1003 * Normally we assert if a runnable labeled with one DocGroup touches data
1004 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1005 * means that we can touch that document from any DocGroup without asserting.
1007 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1010 * Get the bidi options for this document.
1011 * @see nsBidiUtils.h
1013 uint32_t GetBidiOptions() const { return mBidiOptions; }
1016 * Set the bidi options for this document. This just sets the bits;
1017 * callers are expected to take action as needed if they want this
1018 * change to actually change anything immediately.
1019 * @see nsBidiUtils.h
1021 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1024 * Set CSP flag for this document.
1026 void SetHasCSP(bool aHasCSP) { mHasCSP = aHasCSP; }
1029 * Set unsafe-inline CSP flag for this document.
1031 void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP) {
1032 mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
1036 * Set unsafe-eval CSP flag for this document.
1038 void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP) {
1039 mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
1043 * Returns true if the document holds a CSP
1044 * delivered through an HTTP Header.
1046 bool GetHasCSPDeliveredThroughHeader() {
1047 return mHasCSPDeliveredThroughHeader;
1051 * Return a promise which resolves to the content blocking events.
1053 typedef MozPromise<uint32_t, bool, true> GetContentBlockingEventsPromise;
1054 MOZ_MUST_USE RefPtr<GetContentBlockingEventsPromise>
1055 GetContentBlockingEvents();
1058 * Get the sandbox flags for this document.
1059 * @see nsSandboxFlags.h for the possible flags
1061 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1063 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1064 return mEmbedderPolicy;
1067 void SetEmbedderPolicy(
1068 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1069 mEmbedderPolicy = aCOEP;
1073 * Get string representation of sandbox flags (null if no flags are set)
1075 void GetSandboxFlagsAsString(nsAString& aFlags);
1078 * Set the sandbox flags for this document.
1079 * @see nsSandboxFlags.h for the possible flags
1081 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1084 * Called when the document was decoded as UTF-8 and decoder encountered no
1085 * errors.
1087 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1090 * Called to disable client access to cookies through the document.cookie API
1091 * from user JavaScript code.
1093 void DisableCookieAccess() { mDisableCookieAccess = true; }
1095 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1096 bool LinkHandlingEnabled() { return mLinksEnabled; }
1099 * Set compatibility mode for this document
1101 void SetCompatibilityMode(nsCompatibility aMode);
1104 * Called to disable client access to document.write() API from user
1105 * JavaScript code.
1107 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1110 * Whether a document.write() call is in progress.
1112 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1115 * Access HTTP header data (this may also get set from other
1116 * sources, like HTML META tags).
1118 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1119 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1122 * Create a new presentation shell that will use aContext for its
1123 * presentation context (presentation contexts <b>must not</b> be
1124 * shared among multiple presentation shells). The caller of this
1125 * method is responsible for calling BeginObservingDocument() on the
1126 * presshell if the presshell should observe document mutations.
1128 already_AddRefed<PresShell> CreatePresShell(nsPresContext* aContext,
1129 nsViewManager* aViewManager);
1130 void DeletePresShell();
1132 PresShell* GetPresShell() const {
1133 return GetBFCacheEntry() ? nullptr : mPresShell;
1136 inline PresShell* GetObservingPresShell() const;
1138 // Return whether the presshell for this document is safe to flush.
1139 bool IsSafeToFlush() const;
1141 inline nsPresContext* GetPresContext() const;
1143 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1145 // Instead using this method, what you probably want is
1146 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1147 void DisallowBFCaching() {
1148 NS_ASSERTION(!mBFCacheEntry, "We're already in the bfcache!");
1149 mBFCacheDisallowed = true;
1152 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1154 // Accepts null to clear the BFCache entry too.
1155 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1157 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1160 * Return the parent document of this document. Will return null
1161 * unless this document is within a compound document and has a
1162 * parent. Note that this parent chain may cross chrome boundaries.
1164 Document* GetInProcessParentDocument() const { return mParentDocument; }
1167 * Set the parent document of this document.
1169 void SetParentDocument(Document* aParent) {
1170 mParentDocument = aParent;
1171 if (aParent) {
1172 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1173 if (!mIsDevToolsDocument) {
1174 mIsDevToolsDocument = mParentDocument->IsDevToolsDocument();
1180 * Are plugins allowed in this document ?
1182 bool GetAllowPlugins();
1185 * Set the sub document for aContent to aSubDoc.
1187 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1190 * Get the sub document for aContent
1192 Document* GetSubDocumentFor(nsIContent* aContent) const;
1195 * Find the content node for which aDocument is a sub document.
1197 Element* FindContentForSubDocument(Document* aDocument) const;
1200 * Return the doctype for this document.
1202 DocumentType* GetDoctype() const;
1205 * Return the root element for this document.
1207 Element* GetRootElement() const;
1209 Selection* GetSelection(ErrorResult& aRv);
1211 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1212 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1214 bool UseRegularPrincipal() const;
1217 * Gets the event target to dispatch key events to if there is no focused
1218 * content in the document.
1220 virtual Element* GetUnfocusedKeyEventTarget();
1223 * Retrieve information about the viewport as a data structure.
1224 * This will return information in the viewport META data section
1225 * of the document. This can be used in lieu of ProcessViewportInfo(),
1226 * which places the viewport information in the document header instead
1227 * of returning it directly.
1229 * @param aDisplaySize size of the on-screen display area for this
1230 * document, in device pixels.
1232 * NOTE: If the site is optimized for mobile (via the doctype), this
1233 * will return viewport information that specifies default information.
1235 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1237 void AddMetaViewportElement(HTMLMetaElement* aElement,
1238 ViewportMetaData&& aData);
1239 void RemoveMetaViewportElement(HTMLMetaElement* aElement);
1241 // Returns a ViewportMetaData for this document.
1242 ViewportMetaData GetViewportMetaData() const;
1244 void UpdateForScrollAnchorAdjustment(nscoord aLength);
1247 * True iff this doc will ignore manual character encoding overrides.
1249 virtual bool WillIgnoreCharsetOverride() { return true; }
1252 * Return whether the document was created by a srcdoc iframe.
1254 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1257 * Sets whether the document was created by a srcdoc iframe.
1259 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1260 mIsSrcdocDocument = aIsSrcdocDocument;
1264 * Gets the srcdoc string from within the channel (assuming both exist).
1265 * Returns a void string if this isn't a srcdoc document or if
1266 * the channel has not been set.
1268 nsresult GetSrcdocData(nsAString& aSrcdocData);
1270 already_AddRefed<AnonymousContent> InsertAnonymousContent(
1271 Element& aElement, ErrorResult& aError);
1272 void RemoveAnonymousContent(AnonymousContent& aContent, ErrorResult& aError);
1274 * If aNode is a descendant of anonymous content inserted by
1275 * InsertAnonymousContent, this method returns the root element of the
1276 * inserted anonymous content (in other words, the clone of the aElement
1277 * that was passed to InsertAnonymousContent).
1279 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1280 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1281 return mAnonymousContents;
1284 TimeStamp GetPageUnloadingEventTimeStamp() const {
1285 if (!mParentDocument) {
1286 return mPageUnloadingEventTimeStamp;
1289 TimeStamp parentTimeStamp(
1290 mParentDocument->GetPageUnloadingEventTimeStamp());
1291 if (parentTimeStamp.IsNull()) {
1292 return mPageUnloadingEventTimeStamp;
1295 if (!mPageUnloadingEventTimeStamp ||
1296 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1297 return parentTimeStamp;
1300 return mPageUnloadingEventTimeStamp;
1303 void NotifyLayerManagerRecreated();
1306 * Add an SVG element to the list of elements that need
1307 * their mapped attributes resolved to a Servo declaration block.
1309 * These are weak pointers, please manually unschedule them when an element
1310 * is removed.
1312 void ScheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1313 mLazySVGPresElements.PutEntry(aSVG);
1316 // Unschedule an element scheduled by ScheduleFrameRequestCallback (e.g. for
1317 // when it is destroyed)
1318 void UnscheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1319 mLazySVGPresElements.RemoveEntry(aSVG);
1322 // Resolve all SVG pres attrs scheduled in ScheduleSVGForPresAttrEvaluation
1323 void ResolveScheduledSVGPresAttrs();
1325 Maybe<ClientInfo> GetClientInfo() const;
1326 Maybe<ClientState> GetClientState() const;
1327 Maybe<ServiceWorkerDescriptor> GetController() const;
1329 // Returns the size of the mBlockedNodesByClassifier array.
1331 // This array contains nodes that have been blocked to prevent user tracking,
1332 // fingerprinting, cryptomining, etc. They most likely have had their
1333 // nsIChannel canceled by the URL classifier (Safebrowsing).
1335 // A script can subsequently use GetBlockedNodesByClassifier()
1336 // to get a list of references to these nodes.
1338 // Note:
1339 // This expresses how many tracking nodes have been blocked for this document
1340 // since its beginning, not how many of them are still around in the DOM tree.
1341 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1342 // array but they are not removed when those nodes are removed from the tree
1343 // or even garbage collected.
1344 long BlockedNodeByClassifierCount() const {
1345 return mBlockedNodesByClassifier.Length();
1349 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1351 // This array contains nodes that have been blocked to prevent
1352 // user tracking. They most likely have had their nsIChannel
1353 // canceled by the URL classifier (Safebrowsing).
1355 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1357 // Helper method that returns true if the document has storage-access sandbox
1358 // flag.
1359 bool StorageAccessSandboxed() const;
1361 // Helper method that returns true if storage access API is enabled and
1362 // the passed flag has storage-access sandbox flag.
1363 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1365 // Returns the cookie jar settings for this and sub contexts.
1366 nsICookieJarSettings* CookieJarSettings();
1368 // Returns whether this document has the storage access permission.
1369 bool HasStorageAccessPermissionGranted();
1371 // Increments the document generation.
1372 inline void Changed() { ++mGeneration; }
1374 // Returns the current generation.
1375 inline int32_t GetGeneration() const { return mGeneration; }
1377 // Adds cached sizes values to aSizes if there's any
1378 // cached value and if the document generation hasn't
1379 // changed since the cache was created.
1380 // Returns true if sizes were added.
1381 bool GetCachedSizes(nsTabSizes* aSizes);
1383 // Sets the cache sizes for the current generation.
1384 void SetCachedSizes(nsTabSizes* aSizes);
1387 * Should be called when an element's editable changes as a result of
1388 * changing its contentEditable attribute/property.
1390 * The change should be +1 if the contentEditable attribute/property was
1391 * changed to true, -1 if it was changed to false.
1393 void ChangeContentEditableCount(Element*, int32_t aChange);
1394 void DeferredContentEditableCountChange(Element*);
1396 enum class EditingState : int8_t {
1397 eTearingDown = -2,
1398 eSettingUp = -1,
1399 eOff = 0,
1400 eDesignMode,
1401 eContentEditable
1405 * Returns the editing state of the document (not editable, contentEditable or
1406 * designMode).
1408 EditingState GetEditingState() const { return mEditingState; }
1411 * Returns whether the document is editable.
1413 bool IsEditingOn() const {
1414 return GetEditingState() == EditingState::eDesignMode ||
1415 GetEditingState() == EditingState::eContentEditable;
1418 class MOZ_STACK_CLASS nsAutoEditingState {
1419 public:
1420 nsAutoEditingState(Document* aDoc, EditingState aState)
1421 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1422 aDoc->mEditingState = aState;
1424 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1426 private:
1427 RefPtr<Document> mDoc;
1428 EditingState mSavedState;
1430 friend class nsAutoEditingState;
1433 * Set the editing state of the document. Don't use this if you want
1434 * to enable/disable editing, call EditingStateChanged() or
1435 * SetDesignMode().
1437 void SetEditingState(EditingState aState) { mEditingState = aState; }
1440 * Called when this Document's editor is destroyed.
1442 void TearingDownEditor();
1444 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1446 // Gets the next form number.
1448 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1449 // parser inserted form element.
1450 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1452 // Gets the next form control number.
1454 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1455 // parser inserted form control element.
1456 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1458 PreloadService& Preloads() { return mPreloadService; }
1460 bool HasThirdPartyChannel();
1462 protected:
1463 friend class nsUnblockOnloadEvent;
1465 nsresult InitCSP(nsIChannel* aChannel);
1466 nsresult InitCOEP(nsIChannel* aChannel);
1468 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1470 nsresult InitReferrerInfo(nsIChannel* aChannel);
1472 void PostUnblockOnloadEvent();
1474 void DoUnblockOnload();
1476 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1478 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1479 NotNull<const Encoding*>& aEncoding,
1480 nsHtml5TreeOpExecutor* aExecutor);
1482 void DispatchContentLoadedEvents();
1484 void DispatchPageTransition(EventTarget* aDispatchTarget,
1485 const nsAString& aType, bool aInFrameSwap,
1486 bool aPersisted, bool aOnlySystemGroup);
1488 // Call this before the document does something that will unbind all content.
1489 // That will stop us from doing a lot of work as each element is removed.
1490 void DestroyElementMaps();
1492 Element* GetRootElementInternal() const;
1493 void DoNotifyPossibleTitleChange();
1495 void SetPageUnloadingEventTimeStamp() {
1496 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1497 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1500 void CleanUnloadEventsTimeStamp() {
1501 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1502 mPageUnloadingEventTimeStamp = TimeStamp();
1506 * Clears any Servo element data stored on Elements in the document.
1508 void ClearStaleServoData();
1511 * Returns the top window root from the outer window.
1513 already_AddRefed<nsPIWindowRoot> GetWindowRoot();
1516 * Do the tree-disconnection that ResetToURI and document.open need to do.
1518 void DisconnectNodeTree();
1521 * Like IsEditingOn(), but will flush as needed first.
1523 bool IsEditingOnAfterFlush();
1526 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1527 * "CheckKeyPressEventModel" event to check whether we should dispatch
1528 * keypress events in confluent model or split model. This should be
1529 * called only when mEditingState is changed to eDesignMode or
1530 * eConentEditable at first time.
1532 void MaybeDispatchCheckKeyPressEventModelEvent();
1534 /* Midas implementation */
1535 nsCommandManager* GetMidasCommandManager();
1537 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1539 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1540 // of places, and I'm pretty sure the exact ExecCommand call it
1541 // makes cannot actually run script.
1542 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1544 void MaybeEditingStateChanged();
1546 private:
1547 class SelectorCacheKey {
1548 public:
1549 explicit SelectorCacheKey(const nsAString& aString) : mKey(aString) {
1550 MOZ_COUNT_CTOR(SelectorCacheKey);
1553 nsString mKey;
1554 nsExpirationState mState;
1556 nsExpirationState* GetExpirationState() { return &mState; }
1558 MOZ_COUNTED_DTOR(SelectorCacheKey)
1561 class SelectorCacheKeyDeleter;
1563 public:
1564 class SelectorCache final : public nsExpirationTracker<SelectorCacheKey, 4> {
1565 public:
1566 using SelectorList = UniquePtr<RawServoSelectorList>;
1568 explicit SelectorCache(nsIEventTarget* aEventTarget);
1570 void CacheList(const nsAString& aSelector, SelectorList aSelectorList) {
1571 MOZ_ASSERT(NS_IsMainThread());
1572 SelectorCacheKey* key = new SelectorCacheKey(aSelector);
1573 mTable.Put(key->mKey, std::move(aSelectorList));
1574 AddObject(key);
1577 void NotifyExpired(SelectorCacheKey* aSelector) final;
1579 // We do not call MarkUsed because it would just slow down lookups and
1580 // because we're OK expiring things after a few seconds even if they're
1581 // being used. Returns whether we actually had an entry for aSelector.
1583 // If we have an entry and the selector list returned has a null
1584 // RawServoSelectorList*, that indicates that aSelector has already been
1585 // parsed and is not a syntactically valid selector.
1586 SelectorList* GetList(const nsAString& aSelector) {
1587 return mTable.GetValue(aSelector);
1590 ~SelectorCache();
1592 private:
1593 nsDataHashtable<nsStringHashKey, SelectorList> mTable;
1596 SelectorCache& GetSelectorCache() {
1597 if (!mSelectorCache) {
1598 mSelectorCache =
1599 MakeUnique<SelectorCache>(EventTargetFor(TaskCategory::Other));
1601 return *mSelectorCache;
1603 // Get the root <html> element, or return null if there isn't one (e.g.
1604 // if the root isn't <html>)
1605 Element* GetHtmlElement() const;
1606 // Returns the first child of GetHtmlContent which has the given tag,
1607 // or nullptr if that doesn't exist.
1608 Element* GetHtmlChildElement(nsAtom* aTag);
1609 // Get the canonical <body> element, or return null if there isn't one (e.g.
1610 // if the root isn't <html> or if the <body> isn't there)
1611 HTMLBodyElement* GetBodyElement();
1612 // Get the canonical <head> element, or return null if there isn't one (e.g.
1613 // if the root isn't <html> or if the <head> isn't there)
1614 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1615 // Get the "body" in the sense of document.body: The first <body> or
1616 // <frameset> that's a child of a root <html>
1617 nsGenericHTMLElement* GetBody();
1618 // Set the "body" in the sense of document.body.
1619 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1620 // Get the "head" element in the sense of document.head.
1621 HTMLSharedElement* GetHead();
1623 ServoStyleSet* StyleSetForPresShellOrMediaQueryEvaluation() const {
1624 return mStyleSet.get();
1627 // ShadowRoot has APIs that can change styles. This notifies the shell that
1628 // stlyes applicable in the shadow tree have potentially changed.
1629 void RecordShadowStyleChange(ShadowRoot&);
1631 // Needs to be called any time the applicable style can has changed, in order
1632 // to schedule a style flush and setup all the relevant state.
1633 void ApplicableStylesChanged();
1635 // Whether we filled the style set with any style sheet. Only meant to be used
1636 // from DocumentOrShadowRoot::Traverse.
1637 bool StyleSetFilled() const { return mStyleSetFilled; }
1640 * Accessors to the collection of stylesheets owned by this document.
1641 * Style sheets are ordered, most significant last.
1644 void InsertSheetAt(size_t aIndex, StyleSheet&);
1647 * Add a stylesheet to the document
1649 * TODO(emilio): This is only used by parts of editor that are no longer in
1650 * use by m-c or c-c, so remove.
1652 void AddStyleSheet(StyleSheet* aSheet) {
1653 MOZ_ASSERT(aSheet);
1654 InsertSheetAt(SheetCount(), *aSheet);
1658 * Notify the document that the applicable state of the sheet changed
1659 * and that observers should be notified and style sets updated
1661 void StyleSheetApplicableStateChanged(StyleSheet&);
1663 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1665 enum additionalSheetType {
1666 eAgentSheet,
1667 eUserSheet,
1668 eAuthorSheet,
1669 AdditionalSheetTypeCount
1672 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1673 nsIURI* aSheetURI);
1674 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1675 StyleSheet* aSheet);
1676 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1678 StyleSheet* GetFirstAdditionalAuthorSheet() {
1679 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1683 * Returns the index that aSheet should be inserted at to maintain document
1684 * ordering.
1686 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1689 * Get this document's CSSLoader. This is guaranteed to not return null.
1691 css::Loader* CSSLoader() const { return mCSSLoader; }
1694 * Get this document's StyleImageLoader. This is guaranteed to not return
1695 * null.
1697 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1700 * Get the channel that was passed to StartDocumentLoad or Reset for this
1701 * document. Note that this may be null in some cases (eg if
1702 * StartDocumentLoad or Reset were never called)
1704 nsIChannel* GetChannel() const { return mChannel; }
1707 * Get this document's attribute stylesheet. May return null if
1708 * there isn't one.
1710 nsHTMLStyleSheet* GetAttributeStyleSheet() const { return mAttrStyleSheet; }
1713 * Get this document's inline style sheet. May return null if there
1714 * isn't one
1716 nsHTMLCSSStyleSheet* GetInlineStyleSheet() const {
1717 return mStyleAttrStyleSheet;
1720 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1723 * Get/set the object from which the context for the event/script handling can
1724 * be got. Normally GetScriptHandlingObject() returns the same object as
1725 * GetScriptGlobalObject(), but if the document is loaded as data,
1726 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1727 * aHasHadScriptHandlingObject is set true if document has had the object
1728 * for event/script handling. Do not process any events/script if the method
1729 * returns null, but aHasHadScriptHandlingObject is true.
1731 nsIScriptGlobalObject* GetScriptHandlingObject(
1732 bool& aHasHadScriptHandlingObject) const {
1733 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1734 return mScriptGlobalObject ? mScriptGlobalObject.get()
1735 : GetScriptHandlingObjectInternal();
1737 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1740 * Get the object that is used as the scope for all of the content
1741 * wrappers whose owner document is this document. Unlike the script global
1742 * object, this will only return null when the global object for this
1743 * document is truly gone. Use this object when you're trying to find a
1744 * content wrapper in XPConnect.
1746 nsIGlobalObject* GetScopeObject() const;
1747 void SetScopeObject(nsIGlobalObject* aGlobal);
1750 * Return the window containing the document (the outer window).
1752 nsPIDOMWindowOuter* GetWindow() const {
1753 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1756 bool IsInBackgroundWindow() const {
1757 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1758 return outer && outer->IsBackground();
1762 * Return the inner window used as the script compilation scope for
1763 * this document. If you're not absolutely sure you need this, use
1764 * GetWindow().
1766 nsPIDOMWindowInner* GetInnerWindow() const {
1767 return mRemovedFromDocShell ? nullptr : mWindow;
1771 * Return the outer window ID.
1773 uint64_t OuterWindowID() const {
1774 nsPIDOMWindowOuter* window = GetWindow();
1775 return window ? window->WindowID() : 0;
1779 * Return the inner window ID.
1781 uint64_t InnerWindowID() const {
1782 nsPIDOMWindowInner* window = GetInnerWindow();
1783 return window ? window->WindowID() : 0;
1787 * Return WindowGlobalChild that is associated with the inner window.
1789 WindowGlobalChild* GetWindowGlobalChild() {
1790 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1791 : nullptr;
1795 * Return WindowContext associated with the inner window.
1797 WindowContext* GetWindowContext() const {
1798 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1801 bool IsTopLevelWindowInactive() const;
1804 * Get the script loader for this document
1806 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1809 * Add/Remove an element to the document's id and name hashes
1811 void AddToIdTable(Element* aElement, nsAtom* aId);
1812 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1813 void AddToNameTable(Element* aElement, nsAtom* aName);
1814 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1817 * Returns all elements in the top layer in the insertion order.
1819 nsTArray<Element*> GetTopLayer() const;
1822 * Asynchronously requests that the document make aElement the fullscreen
1823 * element, and move into fullscreen mode. The current fullscreen element
1824 * (if any) is pushed onto the top layer, and it can be
1825 * returned to fullscreen status by calling RestorePreviousFullscreenState().
1827 * Note that requesting fullscreen in a document also makes the element which
1828 * contains this document in this document's parent document fullscreen. i.e.
1829 * the <iframe> or <browser> that contains this document is also mode
1830 * fullscreen. This happens recursively in all ancestor documents.
1832 void AsyncRequestFullscreen(UniquePtr<FullscreenRequest>);
1834 // Do the "fullscreen element ready check" from the fullscreen spec.
1835 // It returns true if the given element is allowed to go into fullscreen.
1836 // It is responsive to dispatch "fullscreenerror" event when necessary.
1837 bool FullscreenElementReadyCheck(FullscreenRequest&);
1839 // This is called asynchronously by Document::AsyncRequestFullscreen()
1840 // to move this document into fullscreen mode if allowed.
1841 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1842 bool applyFullScreenDirectly = false);
1844 private:
1845 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1846 bool applyFullScreenDirectly);
1847 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1848 bool applyFullScreenDirectly);
1850 public:
1851 // Removes all the elements with fullscreen flag set from the top layer, and
1852 // clears their fullscreen flag.
1853 void CleanupFullscreenState();
1855 // Pushes aElement onto the top layer
1856 void TopLayerPush(Element* aElement);
1858 // Removes the topmost element which have aPredicate return true from the top
1859 // layer. The removed element, if any, is returned.
1860 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicateFunc);
1862 // Pops the fullscreen element from the top layer and clears its
1863 // fullscreen flag.
1864 void UnsetFullscreenElement();
1866 // Pushes the given element into the top of top layer and set fullscreen
1867 // flag.
1868 void SetFullscreenElement(Element* aElement);
1870 // Cancel the dialog element if the document is blocked by the dialog
1871 void TryCancelDialog();
1873 void SetBlockedByModalDialog(HTMLDialogElement&);
1875 void UnsetBlockedByModalDialog(HTMLDialogElement&);
1878 * Called when a frame in a child process has entered fullscreen or when a
1879 * fullscreen frame in a child process changes to another origin.
1880 * aFrameElement is the frame element which contains the child-process
1881 * fullscreen document.
1883 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1886 * Called when a frame in a remote child document has rolled back fullscreen
1887 * so that all its top layer are empty; we must continue the
1888 * rollback in this parent process' doc tree branch which is fullscreen.
1889 * Note that only one branch of the document tree can have its documents in
1890 * fullscreen state at one time. We're in inconsistent state if a
1891 * fullscreen document has a parent and that parent isn't fullscreen. We
1892 * preserve this property across process boundaries.
1894 void RemoteFrameFullscreenReverted();
1897 * Restores the previous fullscreen element to fullscreen status. If there
1898 * is no former fullscreen element, this exits fullscreen, moving the
1899 * top-level browser window out of fullscreen mode.
1901 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1904 * Returns true if this document is a fullscreen leaf document, i.e. it
1905 * is in fullscreen mode and has no fullscreen children.
1907 bool IsFullscreenLeaf();
1910 * Returns the document which is at the root of this document's branch
1911 * in the in-process document tree. Returns nullptr if the document isn't
1912 * fullscreen.
1914 Document* GetFullscreenRoot();
1916 size_t CountFullscreenElements() const;
1919 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1920 * in this document.
1922 void SetFullscreenRoot(Document* aRoot);
1925 * Synchronously cleans up the fullscreen state on the given document.
1927 * Calling this without performing fullscreen transition could lead
1928 * to undesired effect (the transition happens after document state
1929 * flips), hence it should only be called either by nsGlobalWindow
1930 * when we have performed the transition, or when it is necessary to
1931 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1932 * should be called instead.
1934 * aDocument must not be null.
1936 static void ExitFullscreenInDocTree(Document* aDocument);
1939 * Ask the document to exit fullscreen state asynchronously.
1941 * Different from ExitFullscreenInDocTree(), this allows the window
1942 * to perform fullscreen transition first if any.
1944 * If aDocument is null, it will exit fullscreen from all documents
1945 * in all windows.
1947 static void AsyncExitFullscreen(Document* aDocument);
1950 * Handles any pending fullscreen in aDocument or its subdocuments.
1952 * Returns whether there is any fullscreen request handled.
1954 static bool HandlePendingFullscreenRequests(Document* aDocument);
1956 void RequestPointerLock(Element* aElement, CallerType);
1957 MOZ_CAN_RUN_SCRIPT bool SetPointerLock(Element* aElement, StyleCursorKind);
1959 MOZ_CAN_RUN_SCRIPT_BOUNDARY
1960 static void UnlockPointer(Document* aDoc = nullptr);
1962 // ScreenOrientation related APIs
1964 void ClearOrientationPendingPromise();
1965 bool SetOrientationPendingPromise(Promise* aPromise);
1966 Promise* GetOrientationPendingPromise() const {
1967 return mOrientationPendingPromise;
1970 //----------------------------------------------------------------------
1972 // Document notification API's
1975 * Add a new observer of document change notifications. Whenever
1976 * content is changed, appended, inserted or removed the observers are
1977 * informed. An observer that is already observing the document must
1978 * not be added without being removed first.
1980 void AddObserver(nsIDocumentObserver* aObserver);
1983 * Remove an observer of document change notifications. This will
1984 * return false if the observer cannot be found.
1986 bool RemoveObserver(nsIDocumentObserver* aObserver);
1988 // Observation hooks used to propagate notifications to document observers.
1989 // BeginUpdate must be called before any batch of modifications of the
1990 // content model or of style data, EndUpdate must be called afterward.
1991 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1992 void BeginUpdate();
1993 void EndUpdate();
1994 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
1996 void BeginLoad();
1997 virtual void EndLoad();
1999 enum ReadyState {
2000 READYSTATE_UNINITIALIZED = 0,
2001 READYSTATE_LOADING = 1,
2002 READYSTATE_INTERACTIVE = 3,
2003 READYSTATE_COMPLETE = 4
2005 // Set the readystate of the document. If aUpdateTimingInformation is true,
2006 // this will record relevant timestamps in the document's performance timing.
2007 // Some consumers (document.open is the only one right now, actually) don't
2008 // want to do that, though.
2009 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2010 ReadyState GetReadyStateEnum() { return mReadyState; }
2012 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2013 ReadyState aNewState);
2015 void NotifyAbortedLoad();
2017 // notify that a content node changed state. This must happen under
2018 // a scriptblocker but NOT within a begin/end update.
2019 void ContentStateChanged(nsIContent* aContent, EventStates aStateMask);
2021 // Update a set of document states that may have changed.
2022 // This should only be called by callers whose state is also reflected in the
2023 // implementation of Document::GetDocumentState.
2025 // aNotify controls whether we notify our DocumentStatesChanged observers.
2026 void UpdateDocumentStates(EventStates aStateMask, bool aNotify);
2028 void ResetDocumentDirection();
2030 // Observation hooks for style data to propagate notifications
2031 // to document observers
2032 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2033 void RuleAdded(StyleSheet&, css::Rule&);
2034 void RuleRemoved(StyleSheet&, css::Rule&);
2035 void SheetCloned(StyleSheet&) {}
2036 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2039 * Flush notifications for this document and its parent documents
2040 * (since those may affect the layout of this one).
2042 void FlushPendingNotifications(FlushType aType);
2045 * Another variant of the above FlushPendingNotifications. This function
2046 * takes a ChangesToFlush to specify whether throttled animations are flushed
2047 * or not.
2048 * If in doublt, use the above FlushPendingNotifications.
2050 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2051 void FlushPendingNotifications(ChangesToFlush aFlush);
2054 * Calls FlushPendingNotifications on any external resources this document
2055 * has. If this document has no external resources or is an external resource
2056 * itself this does nothing. This should only be called with
2057 * aType >= FlushType::Style.
2059 void FlushExternalResources(FlushType aType);
2061 // Triggers an update of <svg:use> element shadow trees.
2062 void UpdateSVGUseElementShadowTrees() {
2063 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2064 return;
2066 DoUpdateSVGUseElementShadowTrees();
2070 * Only to be used inside Gecko, you can't really do anything with the
2071 * pointer outside Gecko anyway.
2073 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2076 * Reset the document using the given channel and loadgroup. This works
2077 * like ResetToURI, but also sets the document's channel to aChannel.
2078 * The principal of the document will be set from the channel.
2080 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2083 * Reset this document to aURI, aLoadGroup, aPrincipal and
2084 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2085 * content principal based on aURI will be used.
2087 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2088 nsIPrincipal* aPrincipal,
2089 nsIPrincipal* aPartitionedPrincipal);
2092 * Set the container (docshell) for this document. Virtual so that
2093 * docshell can call it.
2095 virtual void SetContainer(nsDocShell* aContainer);
2098 * Get the container (docshell) for this document.
2100 nsISupports* GetContainer() const;
2103 * Get the container's load context for this document.
2105 nsILoadContext* GetLoadContext() const;
2108 * Get docshell the for this document.
2110 nsIDocShell* GetDocShell() const;
2113 * Set and get XML declaration. If aVersion is null there is no declaration.
2114 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2115 * was no standalone parameter in the declaration, that it was given as no,
2116 * or that it was given as yes.
2118 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2119 const int32_t aStandalone);
2120 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2121 nsAString& Standalone);
2124 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2125 * regular HTML document with Content-Type "text/html", image documents and
2126 * media documents). Returns false for XHTML and any other documents parsed
2127 * by the XML parser.
2129 bool IsHTMLDocument() const { return mType == eHTML; }
2130 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2131 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2132 bool IsSVGDocument() const { return mType == eSVG; }
2133 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2134 bool LoadsFullXULStyleSheetUpFront() {
2135 if (IsSVGDocument()) {
2136 return false;
2138 return AllowXULXBL();
2141 bool IsScriptEnabled();
2144 * Returns true if this document was created from a nsXULPrototypeDocument.
2146 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2148 * Returns the prototype the document was created from, or null if it was not
2149 * created from a prototype.
2151 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2153 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2154 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2155 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2156 // When a document is set as TopLevelContentDocument, it must be
2157 // allowpaymentrequest. We handle the false case while a document is
2158 // appended in SetSubDocumentFor
2159 SetAllowPaymentRequest(aIsTopLevelContentDocument);
2162 bool IsContentDocument() const { return mIsContentDocument; }
2163 void SetIsContentDocument(bool aIsContentDocument) {
2164 mIsContentDocument = aIsContentDocument;
2167 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2169 * Create an element with the specified name, prefix and namespace ID.
2170 * Returns null if element name parsing failed.
2172 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2173 int32_t aNamespaceID,
2174 const nsAString* aIs = nullptr);
2177 * Get the security info (i.e. SSL state etc) that the document got
2178 * from the channel/document that created the content of the
2179 * document.
2181 * @see nsIChannel
2183 nsISupports* GetSecurityInfo() { return mSecurityInfo; }
2186 * Get the channel that failed to load and resulted in an error page, if it
2187 * exists. This is only relevant to error pages.
2189 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2192 * This function checks if the document that is trying to access
2193 * GetNetErrorInfo is a trusted about net error page or not.
2195 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2198 * Get security info like error code for a failed channel. This
2199 * property is only exposed to about:neterror documents.
2201 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2204 * This function checks if the document that is trying to access
2205 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2207 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2210 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2211 * failed Channel. This property is only exposed for about:certerror
2212 * documents.
2214 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2215 ErrorResult& aRv);
2218 * Controls whether or not we allow TLS 1.0/1.1. Only exposed to error pages.
2220 bool AllowDeprecatedTls();
2221 void SetAllowDeprecatedTls(bool aResult);
2224 * Set the channel that failed to load and resulted in an error page.
2225 * This is only relevant to error pages.
2227 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2230 * Returns the default namespace ID used for elements created in this
2231 * document.
2233 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2235 void RemoveAllProperties();
2236 void RemoveAllPropertiesFor(nsINode* aNode);
2238 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2241 * Sets the ID used to identify this part of the multipart document
2243 void SetPartID(uint32_t aID) { mPartID = aID; }
2246 * Return the ID used to identify this part of the multipart document
2248 uint32_t GetPartID() const { return mPartID; }
2251 * Sanitize the document by resetting all input elements and forms that have
2252 * autocomplete=off to their default values.
2254 void Sanitize();
2257 * Enumerate all subdocuments.
2258 * The enumerator callback should return CallState::Continue to continue
2259 * enumerating, or CallState::Stop to stop. This will never get passed a null
2260 * aDocument.
2262 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2263 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2266 * Collect all the descendant documents for which |aCalback| returns true.
2267 * The callback function must not mutate any state for the given document.
2269 typedef bool (*nsDocTestFunc)(const Document* aDocument);
2270 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2271 nsDocTestFunc aCallback) const;
2274 * Check whether it is safe to cache the presentation of this document
2275 * and all of its subdocuments. This method checks the following conditions
2276 * recursively:
2277 * - Some document types, such as plugin documents, cannot be safely cached.
2278 * - If there are any pending requests, we don't allow the presentation
2279 * to be cached. Ideally these requests would be suspended and resumed,
2280 * but that is difficult in some cases, such as XMLHttpRequest.
2281 * - If there are any beforeunload or unload listeners, we must fire them
2282 * for correctness, but this likely puts the document into a state where
2283 * it would not function correctly if restored.
2285 * |aNewRequest| should be the request for a new document which will
2286 * replace this document in the docshell. The new document's request
2287 * will be ignored when checking for active requests. If there is no
2288 * request associated with the new document, this parameter may be null.
2290 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2291 * combination is when we try to BFCache aNewRequest
2293 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2294 uint16_t& aBFCacheCombo);
2296 virtual nsresult Init();
2299 * Notify the document that its associated ContentViewer is being destroyed.
2300 * This releases circular references so that the document can go away.
2301 * Destroy() is only called on documents that have a content viewer.
2303 virtual void Destroy();
2306 * Notify the document that its associated ContentViewer is no longer
2307 * the current viewer for the docshell. The document might still
2308 * be rendered in "zombie state" until the next document is ready.
2309 * The document should save form control state.
2311 void RemovedFromDocShell();
2314 * Get the layout history state that should be used to save and restore state
2315 * for nodes in this document. This may return null; if that happens state
2316 * saving and restoration is not possible.
2318 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2321 * Methods that can be used to prevent onload firing while an event that
2322 * should block onload is posted. onload is guaranteed to not fire until
2323 * either all calls to BlockOnload() have been matched by calls to
2324 * UnblockOnload() or the load has been stopped altogether (by the user
2325 * pressing the Stop button, say).
2327 void BlockOnload();
2329 * @param aFireSync whether to fire onload synchronously. If false,
2330 * onload will fire asynchronously after all onload blocks have been
2331 * removed. It will NOT fire from inside UnblockOnload. If true,
2332 * onload may fire from inside UnblockOnload.
2334 void UnblockOnload(bool aFireSync);
2336 // Only BlockOnload should call this!
2337 void AsyncBlockOnload();
2339 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2341 void UnblockDOMContentLoaded();
2344 * Notification that the page has been shown, for documents which are loaded
2345 * into a DOM window. This corresponds to the completion of document load,
2346 * or to the page's presentation being restored into an existing DOM window.
2347 * This notification fires applicable DOM events to the content window. See
2348 * PageTransitionEvent.webidl for a description of the |aPersisted|
2349 * parameter. If aDispatchStartTarget is null, the pageshow event is
2350 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2351 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2352 * event is only dispatched to listeners in the system group.
2353 * Note: if aDispatchStartTarget isn't null, the showing state of the
2354 * document won't be altered.
2356 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2357 bool aOnlySystemGroup = false);
2360 * Notification that the page has been hidden, for documents which are loaded
2361 * into a DOM window. This corresponds to the unloading of the document, or
2362 * to the document's presentation being saved but removed from an existing
2363 * DOM window. This notification fires applicable DOM events to the content
2364 * window. See PageTransitionEvent.webidl for a description of the
2365 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2366 * event is dispatched on the ScriptGlobalObject for this document,
2367 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2368 * true, the event is only dispatched to listeners in the system group.
2369 * Note: if aDispatchStartTarget isn't null, the showing state of the
2370 * document won't be altered.
2372 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2373 bool aOnlySystemGroup = false);
2376 * We record the set of links in the document that are relevant to
2377 * style.
2380 * Notification that an element is a link that is relevant to style.
2382 void AddStyleRelevantLink(Link* aLink) {
2383 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2384 #ifdef DEBUG
2385 nsPtrHashKey<Link>* entry = mStyledLinks.GetEntry(aLink);
2386 NS_ASSERTION(!entry, "Document already knows about this Link!");
2387 mStyledLinksCleared = false;
2388 #endif
2389 mStyledLinks.PutEntry(aLink);
2393 * Notification that an element is a link and its URI might have been
2394 * changed or the element removed. If the element is still a link relevant
2395 * to style, then someone must ensure that AddStyleRelevantLink is
2396 * (eventually) called on it again.
2398 void ForgetLink(Link* aLink) {
2399 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2400 #ifdef DEBUG
2401 nsPtrHashKey<Link>* entry = mStyledLinks.GetEntry(aLink);
2402 NS_ASSERTION(entry || mStyledLinksCleared,
2403 "Document knows nothing about this Link!");
2404 #endif
2405 mStyledLinks.RemoveEntry(aLink);
2408 // Refreshes the hrefs of all the links in the document.
2409 void RefreshLinkHrefs();
2412 * Support for window.matchMedia()
2415 already_AddRefed<MediaQueryList> MatchMedia(const nsAString& aMediaQueryList,
2416 CallerType aCallerType);
2418 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2421 * Get the compatibility mode for this document
2423 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2426 * Check whether we've ever fired a DOMTitleChanged event for this
2427 * document.
2429 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2432 * To batch DOMSubtreeModified, document needs to be informed when
2433 * a mutation event might be dispatched, even if the event isn't actually
2434 * created because there are no listeners for it.
2436 * @param aTarget is the target for the mutation event.
2438 void MayDispatchMutationEvent(nsINode* aTarget) {
2439 if (mSubtreeModifiedDepth > 0) {
2440 mSubtreeModifiedTargets.AppendObject(aTarget);
2445 * Marks as not-going-to-be-collected for the given generation of
2446 * cycle collection.
2448 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2449 mMarkedCCGeneration = aGeneration;
2453 * Gets the cycle collector generation this document is marked for.
2455 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2458 * Returns whether this document is cookie averse. See
2459 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2461 bool IsCookieAverse() const {
2462 // If we are a document that "has no browsing context."
2463 if (!GetInnerWindow()) {
2464 return true;
2467 // If we are a document "whose URL's scheme is not a network scheme."
2468 // NB: Explicitly allow file: URIs to store cookies.
2470 return !NodePrincipal()->SchemeIs("http") &&
2471 !NodePrincipal()->SchemeIs("https") &&
2472 !NodePrincipal()->SchemeIs("ftp") &&
2473 !NodePrincipal()->SchemeIs("file");
2476 bool IsLoadedAsData() { return mLoadedAsData; }
2478 bool MayStartLayout() { return mMayStartLayout; }
2480 void SetMayStartLayout(bool aMayStartLayout);
2482 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2484 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2486 // In case of failure, the document really can't initialize the frame loader.
2487 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2488 // In case of failure, the caller must handle the error, for example by
2489 // finalizing frame loader asynchronously.
2490 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2491 // Removes the frame loader of aShell from the initialization list.
2492 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2495 * Check whether this document is a root document that is not an
2496 * external resource.
2498 bool IsRootDisplayDocument() const {
2499 return !mParentDocument && !mDisplayDocument;
2502 bool IsDocumentURISchemeChrome() const { return mDocURISchemeIsChrome; }
2504 bool IsInChromeDocShell() const {
2505 const Document* root = this;
2506 while (const Document* displayDoc = root->GetDisplayDocument()) {
2507 root = displayDoc;
2509 return root->mInChromeDocShell;
2512 bool IsDevToolsDocument() const { return mIsDevToolsDocument; }
2514 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2516 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2518 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2520 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2522 bool IsResourceDoc() const {
2523 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2524 mHasDisplayDocument; // Are we an external resource doc?
2528 * Get the document for which this document is an external resource. This
2529 * will be null if this document is not an external resource. Otherwise,
2530 * GetDisplayDocument() will return a non-null document, and
2531 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2533 Document* GetDisplayDocument() const { return mDisplayDocument; }
2536 * Set the display document for this document. aDisplayDocument must not be
2537 * null.
2539 void SetDisplayDocument(Document* aDisplayDocument) {
2540 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2541 "Shouldn't set mDisplayDocument on documents that already "
2542 "have a presentation or a docshell or a window");
2543 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2544 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2545 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2546 "Display documents should not nest");
2547 mDisplayDocument = aDisplayDocument;
2548 mHasDisplayDocument = !!aDisplayDocument;
2552 * Request an external resource document for aURI. This will return the
2553 * resource document if available. If one is not available yet, it will
2554 * start loading as needed, and the pending load object will be returned in
2555 * aPendingLoad so that the caller can register an observer to wait for the
2556 * load. If this function returns null and doesn't return a pending load,
2557 * that means that there is no resource document for this URI and won't be
2558 * one in the future.
2560 * @param aURI the URI to get
2561 * @param aReferrerInfo the referrerInfo of the request
2562 * @param aRequestingNode the node making the request
2563 * @param aPendingLoad the pending load for this request, if any
2565 Document* RequestExternalResource(nsIURI* aURI,
2566 nsIReferrerInfo* aReferrerInfo,
2567 nsINode* aRequestingNode,
2568 ExternalResourceLoad** aPendingLoad);
2571 * Enumerate the external resource documents associated with this document.
2572 * The enumerator callback should return CallState::Continue to continue
2573 * enumerating, or CallState::Stop to stop. This callback will never get
2574 * passed a null aDocument.
2576 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2578 dom::ExternalResourceMap& ExternalResourceMap() {
2579 return mExternalResourceMap;
2583 * Return whether the document is currently showing (in the sense of
2584 * OnPageShow() having been called already and OnPageHide() not having been
2585 * called yet.
2587 bool IsShowing() const { return mIsShowing; }
2589 * Return whether the document is currently visible (in the sense of
2590 * OnPageHide having been called and OnPageShow not yet having been called)
2592 bool IsVisible() const { return mVisible; }
2595 * Return whether the document and all its ancestors are visible in the sense
2596 * of pageshow / hide.
2598 bool IsVisibleConsideringAncestors() const;
2600 void SetSuppressedEventListener(EventListener* aListener);
2602 EventListener* GetSuppressedEventListener() {
2603 return mSuppressedEventListener;
2607 * Return true when this document is active, i.e., an active document
2608 * in a content viewer. Note that this will return true for bfcached
2609 * documents, so this does NOT match the "active document" concept in
2610 * the WHATWG spec - see IsCurrentActiveDocument.
2612 bool IsActive() const { return mDocumentContainer && !mRemovedFromDocShell; }
2615 * Return true if this is the current active document for its
2616 * docshell. Note that a docshell may have multiple active documents
2617 * due to the bfcache -- this should be used when you need to
2618 * differentiate the *current* active document from any active
2619 * documents.
2621 bool IsCurrentActiveDocument() const {
2622 nsPIDOMWindowInner* inner = GetInnerWindow();
2623 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2627 * Returns whether this document should perform image loads.
2629 bool ShouldLoadImages() const {
2630 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2631 // images can themselves have data: URL image references.
2632 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2633 IsStaticDocument();
2637 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2638 * the document's activity changes such as OnPageHide, visibility, activity.
2639 * The ActivityObserver objects can be nsIObjectLoadingContent or
2640 * nsIDocumentActivity or HTMLMEdiaElement.
2642 void RegisterActivityObserver(nsISupports* aSupports);
2643 bool UnregisterActivityObserver(nsISupports* aSupports);
2644 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2645 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2646 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2648 // Indicates whether mAnimationController has been (lazily) initialized.
2649 // If this returns true, we're promising that GetAnimationController()
2650 // will have a non-null return value.
2651 bool HasAnimationController() { return !!mAnimationController; }
2653 // Getter for this document's SMIL Animation Controller. Performs lazy
2654 // initialization, if this document supports animation and if
2655 // mAnimationController isn't yet initialized.
2657 // If HasAnimationController is true, this is guaranteed to return non-null.
2658 SMILAnimationController* GetAnimationController();
2660 // Gets the tracker for animations that are waiting to start.
2661 // Returns nullptr if there is no pending animation tracker for this document
2662 // which will be the case if there have never been any CSS animations or
2663 // transitions on elements in the document.
2664 PendingAnimationTracker* GetPendingAnimationTracker() {
2665 return mPendingAnimationTracker;
2668 // Gets the tracker for animations that are waiting to start and
2669 // creates it if it doesn't already exist. As a result, the return value
2670 // will never be nullptr.
2671 PendingAnimationTracker* GetOrCreatePendingAnimationTracker();
2674 * Prevents user initiated events from being dispatched to the document and
2675 * subdocuments.
2677 void SuppressEventHandling(uint32_t aIncrease = 1);
2680 * Unsuppress event handling.
2681 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2682 * asynchronously.
2684 void UnsuppressEventHandlingAndFireEvents(bool aFireEvents);
2686 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2688 bool IsEventHandlingEnabled() const {
2689 return !EventHandlingSuppressed() && mScriptGlobalObject;
2692 bool WouldScheduleFrameRequestCallbacks() const {
2693 // If this function changes to depend on some other variable, make sure to
2694 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2695 // where that variable can change.
2696 return mPresShell && IsEventHandlingEnabled();
2699 void DecreaseEventSuppression() {
2700 MOZ_ASSERT(mEventsSuppressed);
2701 --mEventsSuppressed;
2702 UpdateFrameRequestCallbackSchedulingState();
2706 * Note a ChannelEventQueue which has been suspended on the document's behalf
2707 * to prevent XHRs from running content scripts while event handling is
2708 * suppressed. The document is responsible for resuming the queue after
2709 * event handling is unsuppressed.
2711 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2714 * Returns true if a postMessage event should be suspended instead of running.
2715 * The document is responsible for running the event later, in the order they
2716 * were received.
2718 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2721 * Run any suspended postMessage events, or clear them.
2723 void FireOrClearPostMessageEvents(bool aFireEvents);
2725 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2728 * Flag whether we're about to fire the window's load event for this document.
2730 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2733 * Test whether we should be firing a load event for this document after a
2734 * document.close(). This is public and on Document, instead of being private
2735 * to Document, because we need to go through the normal docloader logic
2736 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2737 * semantics of firing the load event; we just don't want to fire the load
2738 * event if this tests true. So we need the docloader to be able to access
2739 * this state.
2741 * This method should only be called at the point when the load event is about
2742 * to be fired. It resets the "skip" flag, so it is not idempotent.
2744 bool SkipLoadEventAfterClose() {
2745 bool skip = mSkipLoadEventAfterClose;
2746 mSkipLoadEventAfterClose = false;
2747 return skip;
2751 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2753 void IncrementIgnoreDestructiveWritesCounter() {
2754 ++mIgnoreDestructiveWritesCounter;
2758 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2760 void DecrementIgnoreDestructiveWritesCounter() {
2761 --mIgnoreDestructiveWritesCounter;
2764 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2767 * Returns true if this document is allowed to contain XUL element and
2768 * use non-builtin XBL bindings.
2770 bool AllowXULXBL() {
2771 return mAllowXULXBL == eTriTrue
2772 ? true
2773 : mAllowXULXBL == eTriFalse ? false : InternalAllowXULXBL();
2777 * Returns true if this document is allowed to load DTDs from UI resources
2778 * no matter what.
2780 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2782 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2784 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2787 * Returns the template content owner document that owns the content of
2788 * HTMLTemplateElement.
2790 Document* GetTemplateContentsOwner();
2793 * Returns true if this document is a static clone of a normal document.
2795 * We create static clones for print preview and printing (possibly other
2796 * things in future).
2798 * Note that static documents are also "loaded as data" (if this method
2799 * returns true, IsLoadedAsData() will also return true).
2801 bool IsStaticDocument() const { return mIsStaticDocument; }
2804 * Clones the document along with any subdocuments, stylesheet, etc.
2806 * The resulting document and everything it contains (including any
2807 * sub-documents) are created purely via cloning. The returned documents and
2808 * any sub-documents are "loaded as data" documents to preserve the state as
2809 * it was during the clone process (we don't want external resources to load
2810 * and replace the cloned resources).
2812 * @param aCloneContainer The container for the clone document.
2814 virtual already_AddRefed<Document> CreateStaticClone(
2815 nsIDocShell* aCloneContainer);
2818 * If this document is a static clone, this returns the original
2819 * document.
2821 Document* GetOriginalDocument() const {
2822 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2823 return mOriginalDocument;
2827 * If this document is a static clone, let the original document know that
2828 * we're going away and then release our reference to it.
2830 void UnlinkOriginalDocumentIfStatic();
2833 * These are called by the parser as it encounters <picture> tags, the end of
2834 * said tags, and possible picture <source srcset> sources respectively. These
2835 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2836 * expected to be marked void.
2838 * NOTE that the parser does not attempt to track the current picture nesting
2839 * level or whether the given <source> tag is within a picture -- it is only
2840 * guaranteed to order these calls properly with respect to
2841 * ResolvePreLoadImage.
2844 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2846 void PreloadPictureClosed();
2848 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2849 const nsAString& aSizesAttr,
2850 const nsAString& aTypeAttr,
2851 const nsAString& aMediaAttr);
2854 * Called by the parser to resolve an image for preloading. The parser will
2855 * call the PreloadPicture* functions to inform us of possible <picture>
2856 * nesting and possible sources, which are used to inform URL selection
2857 * responsive <picture> or <img srcset> images. Unset attributes are expected
2858 * to be marked void.
2859 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2860 * true, false otherwise.
2862 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2863 const nsAString& aSrcAttr,
2864 const nsAString& aSrcsetAttr,
2865 const nsAString& aSizesAttr,
2866 bool* aIsImgSet);
2868 * Called by nsParser to preload images. Can be removed and code moved
2869 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2870 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2871 * be a void string if the attr is not present.
2872 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2873 * when this image is for loading <picture> or <img srcset> images.
2875 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2876 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2877 bool aLinkPreload);
2878 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2879 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2880 bool aLinkPreload);
2883 * Called by images to forget an image preload when they start doing
2884 * the real load.
2886 void ForgetImagePreload(nsIURI* aURI);
2889 * Called by nsParser to preload style sheets. aCrossOriginAttr should be a
2890 * void string if the attr is not present.
2892 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2893 const nsAString& aCrossOriginAttr,
2894 ReferrerPolicyEnum aReferrerPolicy,
2895 const nsAString& aIntegrity,
2896 bool aIsLinkPreload);
2899 * Called by the chrome registry to load style sheets.
2901 * This always does a synchronous load, and parses as a normal document sheet.
2903 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2906 * Returns true if the locale used for the document specifies a direction of
2907 * right to left. For chrome documents, this comes from the chrome registry.
2908 * This is used to determine the current state for the :-moz-locale-dir
2909 * pseudoclass so once can know whether a document is expected to be rendered
2910 * left-to-right or right-to-left.
2912 bool IsDocumentRightToLeft();
2915 * Called by Parser for link rel=preconnect
2917 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2919 enum DocumentTheme {
2920 Doc_Theme_Uninitialized, // not determined yet
2921 Doc_Theme_None,
2922 Doc_Theme_Neutral,
2923 Doc_Theme_Dark,
2924 Doc_Theme_Bright
2928 * Set the document's pending state object (as serialized using structured
2929 * clone).
2931 void SetStateObject(nsIStructuredCloneContainer* scContainer);
2934 * Set the document's pending state object to the same state object as
2935 * aDocument.
2937 void SetStateObjectFrom(Document* aDocument) {
2938 SetStateObject(aDocument->mStateObjectContainer);
2942 * Returns Doc_Theme_None if there is no lightweight theme specified,
2943 * Doc_Theme_Dark for a dark theme, Doc_Theme_Bright for a light theme, and
2944 * Doc_Theme_Neutral for any other theme. This is used to determine the state
2945 * of the pseudoclasses :-moz-lwtheme and :-moz-lwtheme-text.
2947 DocumentTheme GetDocumentLWTheme();
2948 DocumentTheme ThreadSafeGetDocumentLWTheme() const;
2949 void ResetDocumentLWTheme() { mDocLWTheme = Doc_Theme_Uninitialized; }
2951 // Whether we're a media document or not.
2952 enum class MediaDocumentKind {
2953 NotMedia,
2954 Video,
2955 Image,
2956 Plugin,
2959 virtual enum MediaDocumentKind MediaDocumentKind() const {
2960 return MediaDocumentKind::NotMedia;
2964 * Returns the document state.
2965 * Document state bits have the form NS_DOCUMENT_STATE_* and are declared in
2966 * Document.h.
2968 EventStates GetDocumentState() const { return mDocumentState; }
2970 nsISupports* GetCurrentContentSink();
2972 void SetAutoFocusElement(Element* aAutoFocusElement);
2973 void TriggerAutoFocus();
2974 void SetAutoFocusFired();
2975 bool IsAutoFocusFired();
2977 void SetScrollToRef(nsIURI* aDocumentURI);
2978 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
2979 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
2981 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
2982 mChangeScrollPosWhenScrollingToRef = aValue;
2985 using DocumentOrShadowRoot::GetElementById;
2986 using DocumentOrShadowRoot::GetElementsByClassName;
2987 using DocumentOrShadowRoot::GetElementsByTagName;
2988 using DocumentOrShadowRoot::GetElementsByTagNameNS;
2990 DocumentTimeline* Timeline();
2991 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
2993 SVGSVGElement* GetSVGRootElement() const;
2995 struct FrameRequest {
2996 FrameRequest(FrameRequestCallback& aCallback, int32_t aHandle);
2997 ~FrameRequest();
2999 // Comparator operators to allow RemoveElementSorted with an
3000 // integer argument on arrays of FrameRequest
3001 bool operator==(int32_t aHandle) const { return mHandle == aHandle; }
3002 bool operator<(int32_t aHandle) const { return mHandle < aHandle; }
3004 RefPtr<FrameRequestCallback> mCallback;
3005 int32_t mHandle;
3008 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3009 int32_t* aHandle);
3010 void CancelFrameRequestCallback(int32_t aHandle);
3013 * Returns true if the handle refers to a callback that was canceled that
3014 * we did not find in our list of callbacks (e.g. because it is one of those
3015 * in the set of callbacks currently queued to be run).
3017 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3020 * Put this document's frame request callbacks into the provided
3021 * list, and forget about them.
3023 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3026 * @return true if this document's frame request callbacks should be
3027 * throttled. We throttle requestAnimationFrame for documents which aren't
3028 * visible (e.g. scrolled out of the viewport).
3030 bool ShouldThrottleFrameRequests() const;
3032 // This returns true when the document tree is being teared down.
3033 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3035 dom::ImageTracker* ImageTracker();
3037 // AddPlugin adds a plugin-related element to mPlugins when the element is
3038 // added to the tree.
3039 void AddPlugin(nsIObjectLoadingContent* aPlugin) {
3040 MOZ_ASSERT(aPlugin);
3041 mPlugins.PutEntry(aPlugin);
3044 // RemovePlugin removes a plugin-related element to mPlugins when the
3045 // element is removed from the tree.
3046 void RemovePlugin(nsIObjectLoadingContent* aPlugin) {
3047 MOZ_ASSERT(aPlugin);
3048 mPlugins.RemoveEntry(aPlugin);
3051 // GetPlugins returns the plugin-related elements from
3052 // the frame and any subframes.
3053 void GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins);
3055 // Adds an element to mResponsiveContent when the element is
3056 // added to the tree.
3057 void AddResponsiveContent(HTMLImageElement* aContent) {
3058 MOZ_ASSERT(aContent);
3059 mResponsiveContent.PutEntry(aContent);
3062 // Removes an element from mResponsiveContent when the element is
3063 // removed from the tree.
3064 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3065 MOZ_ASSERT(aContent);
3066 mResponsiveContent.RemoveEntry(aContent);
3069 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3070 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3071 mSVGUseElementsNeedingShadowTreeUpdate.RemoveEntry(&aElement);
3074 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3075 return mSVGUseElementsNeedingShadowTreeUpdate.GetEntry(&aElement);
3078 using ShadowRootSet = nsTHashtable<nsPtrHashKey<ShadowRoot>>;
3080 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3081 mComposedShadowRoots.PutEntry(&aShadowRoot);
3084 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3085 mComposedShadowRoots.RemoveEntry(&aShadowRoot);
3088 // If you're considering using this, you probably want to use
3089 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3090 // sanity-checking.
3091 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3092 return mComposedShadowRoots.Contains(&aShadowRoot);
3095 const ShadowRootSet& ComposedShadowRoots() const {
3096 return mComposedShadowRoots;
3099 // WebIDL method for chrome code.
3100 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3102 // Notifies any responsive content added by AddResponsiveContent upon media
3103 // features values changing.
3104 void NotifyMediaFeatureValuesChanged();
3106 nsresult GetStateObject(nsIVariant** aResult);
3108 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3110 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3112 nsContentList* ImageMapList();
3114 // Add aLink to the set of links that need their status resolved.
3115 void RegisterPendingLinkUpdate(Link* aLink);
3117 // Update state on links in mLinksToUpdate.
3118 void FlushPendingLinkUpdates();
3120 #define DEPRECATED_OPERATION(_op) e##_op,
3121 enum DeprecatedOperations {
3122 #include "nsDeprecatedOperationList.h"
3123 eDeprecatedOperationCount
3125 #undef DEPRECATED_OPERATION
3126 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3127 void WarnOnceAbout(
3128 DeprecatedOperations aOperation, bool asError = false,
3129 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3131 #define DOCUMENT_WARNING(_op) e##_op,
3132 enum DocumentWarnings {
3133 #include "nsDocumentWarningList.h"
3134 eDocumentWarningCount
3136 #undef DOCUMENT_WARNING
3137 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3138 void WarnOnceAbout(
3139 DocumentWarnings aWarning, bool asError = false,
3140 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3142 // This method may fire a DOM event; if it does so it will happen
3143 // synchronously.
3144 void UpdateVisibilityState();
3146 // Posts an event to call UpdateVisibilityState.
3147 void PostVisibilityUpdateEvent();
3149 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3151 // Adds the size of a given node, which must not be a document node, to the
3152 // window sizes passed-in.
3153 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3155 // Note: Document is a sub-class of nsINode, which has a
3156 // SizeOfExcludingThis function. However, because Document objects can
3157 // only appear at the top of the DOM tree, we have a specialized measurement
3158 // function which returns multiple sizes.
3159 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3160 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3161 // because Document inherits from nsINode; see the comment above the
3162 // declaration of nsINode::SizeOfIncludingThis.
3163 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3165 void ConstructUbiNode(void* storage) override;
3167 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3169 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3171 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3173 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3175 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3177 void SetIsInSyncOperation(bool aSync) {
3178 if (aSync) {
3179 ++mInSyncOperationCount;
3180 } else {
3181 --mInSyncOperationCount;
3185 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3188 * Creates a new element in the HTML namespace with a local name given by
3189 * aTag.
3191 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3193 // WebIDL API
3194 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3195 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3196 ErrorResult& rv);
3197 DOMImplementation* GetImplementation(ErrorResult& rv);
3198 MOZ_MUST_USE nsresult GetURL(nsString& retval) const;
3199 MOZ_MUST_USE nsresult GetDocumentURI(nsString& retval) const;
3200 // Return the URI for the document.
3201 // The returned value may differ if the document is loaded via XHR, and
3202 // when accessed from chrome privileged script and
3203 // from content privileged script for compatibility.
3204 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3205 ErrorResult& aRv) const;
3206 void GetCompatMode(nsString& retval) const;
3207 void GetCharacterSet(nsAString& retval) const;
3208 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3209 // GetDoctype defined above
3210 Element* GetDocumentElement() const { return GetRootElement(); }
3212 enum ElementCallbackType {
3213 eConnected,
3214 eDisconnected,
3215 eAdopted,
3216 eAttributeChanged,
3217 eGetCustomInterface
3220 WindowContext* GetTopLevelWindowContext() const;
3222 Document* GetTopLevelContentDocument();
3223 const Document* GetTopLevelContentDocument() const;
3225 // Returns the associated app window if this is a top-level chrome document,
3226 // null otherwise.
3227 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3229 already_AddRefed<Element> CreateElement(
3230 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3231 ErrorResult& rv);
3232 already_AddRefed<Element> CreateElementNS(
3233 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3234 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3235 already_AddRefed<Element> CreateXULElement(
3236 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3237 ErrorResult& aRv);
3238 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3239 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3240 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3241 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3242 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3243 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3244 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3245 ErrorResult& rv) const;
3246 nsINode* AdoptNode(nsINode& aNode, ErrorResult& rv);
3247 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3248 CallerType aCallerType,
3249 ErrorResult& rv) const;
3250 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3251 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3252 uint32_t aWhatToShow,
3253 NodeFilter* aFilter,
3254 ErrorResult& rv) const;
3255 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3256 uint32_t aWhatToShow,
3257 NodeFilter* aFilter,
3258 ErrorResult& rv) const;
3259 // Deprecated WebIDL bits
3260 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3261 ErrorResult& rv);
3262 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3263 ErrorResult& rv);
3264 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3265 const nsAString& aQualifiedName,
3266 ErrorResult& rv);
3267 void GetInputEncoding(nsAString& aInputEncoding) const;
3268 already_AddRefed<Location> GetLocation() const;
3269 void GetDomain(nsAString& aDomain);
3270 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3271 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3272 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3273 void GetReferrer(nsAString& aReferrer) const;
3274 void GetLastModified(nsAString& aLastModified) const;
3275 void GetReadyState(nsAString& aReadyState) const;
3277 void GetTitle(nsAString& aTitle);
3278 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3279 void GetDir(nsAString& aDirection) const;
3280 void SetDir(const nsAString& aDirection);
3281 nsIHTMLCollection* Images();
3282 nsIHTMLCollection* Embeds();
3283 nsIHTMLCollection* Plugins() { return Embeds(); }
3284 nsIHTMLCollection* Links();
3285 nsIHTMLCollection* Forms();
3286 nsIHTMLCollection* Scripts();
3287 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3288 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3289 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3291 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3292 const mozilla::dom::Optional<nsAString>& /* unused */,
3293 mozilla::ErrorResult& aError);
3294 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3295 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3296 mozilla::ErrorResult& rv);
3297 void Close(mozilla::ErrorResult& rv);
3298 void Write(const mozilla::dom::Sequence<nsString>& aText,
3299 mozilla::ErrorResult& rv);
3300 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3301 mozilla::ErrorResult& rv);
3302 Nullable<WindowProxyHolder> GetDefaultView() const;
3303 Element* GetActiveElement();
3304 nsIContent* GetUnretargetedFocusedContent() const;
3305 bool HasFocus(ErrorResult& rv) const;
3306 void GetDesignMode(nsAString& aDesignMode);
3307 void SetDesignMode(const nsAString& aDesignMode,
3308 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3309 void SetDesignMode(const nsAString& aDesignMode,
3310 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3311 mozilla::ErrorResult& rv);
3312 MOZ_CAN_RUN_SCRIPT
3313 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3314 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3315 mozilla::ErrorResult& aRv);
3316 bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3317 nsIPrincipal& aSubjectPrincipal,
3318 mozilla::ErrorResult& aRv);
3319 bool QueryCommandIndeterm(const nsAString& aHTMLCommandName,
3320 mozilla::ErrorResult& aRv);
3321 bool QueryCommandState(const nsAString& aHTMLCommandName,
3322 mozilla::ErrorResult& aRv);
3323 bool QueryCommandSupported(const nsAString& aHTMLCommandName,
3324 mozilla::dom::CallerType aCallerType,
3325 mozilla::ErrorResult& aRv);
3326 MOZ_CAN_RUN_SCRIPT
3327 void QueryCommandValue(const nsAString& aHTMLCommandName, nsAString& aValue,
3328 mozilla::ErrorResult& aRv);
3329 nsIHTMLCollection* Applets();
3330 nsIHTMLCollection* Anchors();
3331 TimeStamp LastFocusTime() const;
3332 void SetLastFocusTime(const TimeStamp& aFocusTime);
3333 // Event handlers are all on nsINode already
3334 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3335 Element* GetCurrentScript();
3336 void ReleaseCapture() const;
3337 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3338 nsIURI* GetDocumentURIObject() const;
3339 // Not const because all the fullscreen goop is not const
3340 const char* GetFullscreenError(CallerType);
3341 bool FullscreenEnabled(CallerType aCallerType) {
3342 return !GetFullscreenError(aCallerType);
3345 Element* GetTopLayerTop();
3346 // Return the fullscreen element in the top layer
3347 Element* GetUnretargetedFullScreenElement();
3348 bool Fullscreen() { return !!GetFullscreenElement(); }
3349 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3350 void ExitPointerLock() { UnlockPointer(this); }
3351 void GetFgColor(nsAString& aFgColor);
3352 void SetFgColor(const nsAString& aFgColor);
3353 void GetLinkColor(nsAString& aLinkColor);
3354 void SetLinkColor(const nsAString& aLinkColor);
3355 void GetVlinkColor(nsAString& aAvlinkColor);
3356 void SetVlinkColor(const nsAString& aVlinkColor);
3357 void GetAlinkColor(nsAString& aAlinkColor);
3358 void SetAlinkColor(const nsAString& aAlinkColor);
3359 void GetBgColor(nsAString& aBgColor);
3360 void SetBgColor(const nsAString& aBgColor);
3361 void Clear() const {
3362 // Deprecated
3364 void CaptureEvents();
3365 void ReleaseEvents();
3367 mozilla::dom::HTMLAllCollection* All();
3369 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3370 static bool IsWebAnimationsEnabled(JSContext* aCx, JSObject* aObject);
3371 static bool IsWebAnimationsEnabled(CallerType aCallerType);
3372 static bool IsWebAnimationsGetAnimationsEnabled(JSContext* aCx,
3373 JSObject* aObject);
3374 static bool AreWebAnimationsImplicitKeyframesEnabled(JSContext* aCx,
3375 JSObject* aObject);
3376 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3377 JSObject* aObject);
3378 // Checks that the caller is either chrome or some addon.
3379 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3381 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3382 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3384 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3385 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3386 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3387 aSheetSet = mLastStyleSheetSet;
3389 const nsString& GetCurrentStyleSheetSet() const {
3390 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3391 : mLastStyleSheetSet;
3393 void SetPreferredStyleSheetSet(const nsAString&);
3394 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3395 aSheetSet = mPreferredStyleSheetSet;
3397 DOMStringList* StyleSheetSets();
3398 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3401 * Retrieve the location of the caret position (DOM node and character
3402 * offset within that node), given a point.
3404 * @param aX Horizontal point at which to determine the caret position, in
3405 * page coordinates.
3406 * @param aY Vertical point at which to determine the caret position, in
3407 * page coordinates.
3409 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3410 float aY);
3412 Element* GetScrollingElement();
3413 // A way to check whether a given element is what would get returned from
3414 // GetScrollingElement. It can be faster than comparing to the return value
3415 // of GetScrollingElement() due to being able to avoid flushes in various
3416 // cases. This method assumes that null is NOT passed.
3417 bool IsScrollingElement(Element* aElement);
3419 // QuerySelector and QuerySelectorAll already defined on nsINode
3421 XPathExpression* CreateExpression(const nsAString& aExpression,
3422 XPathNSResolver* aResolver,
3423 ErrorResult& rv);
3424 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3425 already_AddRefed<XPathResult> Evaluate(
3426 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3427 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3428 ErrorResult& rv);
3429 // Touch event handlers already on nsINode
3430 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3431 EventTarget* aTarget, int32_t aIdentifier,
3432 int32_t aPageX, int32_t aPageY,
3433 int32_t aScreenX, int32_t aScreenY,
3434 int32_t aClientX, int32_t aClientY,
3435 int32_t aRadiusX, int32_t aRadiusY,
3436 float aRotationAngle, float aForce);
3437 already_AddRefed<TouchList> CreateTouchList();
3438 already_AddRefed<TouchList> CreateTouchList(
3439 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3440 already_AddRefed<TouchList> CreateTouchList(
3441 const Sequence<OwningNonNull<Touch>>& aTouches);
3443 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3444 mStyleSheetChangeEventsEnabled = aValue;
3447 bool StyleSheetChangeEventsEnabled() const {
3448 return mStyleSheetChangeEventsEnabled;
3451 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3452 const BlockParsingOptions& aOptions,
3453 ErrorResult& aRv);
3455 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3457 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3459 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3460 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3461 void InitializeXULBroadcastManager();
3462 XULBroadcastManager* GetXULBroadcastManager() const {
3463 return mXULBroadcastManager;
3465 already_AddRefed<nsINode> GetPopupNode();
3466 void SetPopupNode(nsINode* aNode);
3467 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3468 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3469 already_AddRefed<nsINode> GetTooltipNode();
3470 void SetTooltipNode(nsINode* aNode) { /* do nothing */
3473 bool DontWarnAboutMutationEventsAndAllowSlowDOMMutations() {
3474 return mDontWarnAboutMutationEventsAndAllowSlowDOMMutations;
3476 void SetDontWarnAboutMutationEventsAndAllowSlowDOMMutations(
3477 bool aDontWarnAboutMutationEventsAndAllowSlowDOMMutations) {
3478 mDontWarnAboutMutationEventsAndAllowSlowDOMMutations =
3479 aDontWarnAboutMutationEventsAndAllowSlowDOMMutations;
3482 void MaybeWarnAboutZoom();
3484 // ParentNode
3485 nsIHTMLCollection* Children();
3486 uint32_t ChildElementCount();
3489 * Asserts IsHTMLOrXHTML, and can't return null.
3490 * Defined inline in nsHTMLDocument.h
3492 inline nsHTMLDocument* AsHTMLDocument();
3495 * Asserts IsSVGDocument, and can't return null.
3496 * Defined inline in SVGDocument.h
3498 inline SVGDocument* AsSVGDocument();
3501 * Given a node, get a weak reference to it and append that reference to
3502 * mBlockedNodesByClassifier. Can be used later on to look up a node in it.
3503 * (e.g., by the UI)
3505 void AddBlockedNodeByClassifier(nsINode* node) {
3506 if (!node) {
3507 return;
3510 nsWeakPtr weakNode = do_GetWeakReference(node);
3512 if (weakNode) {
3513 mBlockedNodesByClassifier.AppendElement(weakNode);
3517 gfxUserFontSet* GetUserFontSet();
3518 void FlushUserFontSet();
3519 void MarkUserFontSetDirty();
3520 FontFaceSet* GetFonts() { return mFontFaceSet; }
3522 // FontFaceSource
3523 FontFaceSet* Fonts();
3525 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3527 bool IsSynthesized();
3529 void ReportUseCounters();
3531 void SetUseCounter(UseCounter aUseCounter) {
3532 mUseCounters[aUseCounter] = true;
3535 const StyleUseCounters* GetStyleUseCounters() {
3536 return mStyleUseCounters.get();
3539 void PropagateUseCountersToPage();
3540 void PropagateUseCounters(Document* aParentDocument);
3542 // Called to track whether this document has had any interaction.
3543 // This is used to track whether we should permit "beforeunload".
3544 void SetUserHasInteracted();
3545 bool UserHasInteracted() { return mUserHasInteracted; }
3546 void ResetUserInteractionTimer();
3548 // This method would return current autoplay policy, it would be "allowed"
3549 // , "allowed-muted" or "disallowed".
3550 DocumentAutoplayPolicy AutoplayPolicy() const;
3552 // This should be called when this document receives events which are likely
3553 // to be user interaction with the document, rather than the byproduct of
3554 // interaction with the browser (i.e. a keypress to scroll the view port,
3555 // keyboard shortcuts, etc). This is used to decide whether we should
3556 // permit autoplay audible media. This also gesture activates all other
3557 // content documents in this tab.
3558 void NotifyUserGestureActivation();
3560 // This function is used for mochitest only.
3561 void ClearUserGestureActivation();
3563 // Return true if NotifyUserGestureActivation() has been called on any
3564 // document in the document tree.
3565 bool HasBeenUserGestureActivated();
3567 // Return true if there is transient user gesture activation and it hasn't yet
3568 // timed out.
3569 bool HasValidTransientUserGestureActivation();
3571 // Return true.
3572 bool ConsumeTransientUserGestureActivation();
3574 BrowsingContext* GetBrowsingContext() const;
3576 // This document is a WebExtension page, it might be a background page, a
3577 // popup, a visible tab, a visible iframe ...e.t.c.
3578 bool IsExtensionPage() const;
3580 bool HasScriptsBlockedBySandbox();
3582 void ReportHasScrollLinkedEffect();
3583 bool HasScrollLinkedEffect() const { return mHasScrollLinkedEffect; }
3585 #ifdef DEBUG
3586 void AssertDocGroupMatchesKey() const;
3587 #endif
3589 DocGroup* GetDocGroup() const {
3590 #ifdef DEBUG
3591 AssertDocGroupMatchesKey();
3592 #endif
3593 return mDocGroup;
3596 DocGroup* GetDocGroupOrCreate();
3599 * If we're a sub-document, the parent document's layout can affect our style
3600 * and layout (due to the viewport size, viewport units, media queries...).
3602 * This function returns true if our parent document and our child document
3603 * can observe each other. If they cannot, then we don't need to synchronously
3604 * update the parent document layout every time the child document may need
3605 * up-to-date layout information.
3607 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3608 return GetInProcessParentDocument() &&
3609 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3612 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3613 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3614 "Intersection observer already in the list");
3615 mIntersectionObservers.PutEntry(aObserver);
3618 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3619 mIntersectionObservers.RemoveEntry(aObserver);
3622 bool HasIntersectionObservers() const {
3623 return !mIntersectionObservers.IsEmpty();
3626 void UpdateIntersectionObservations();
3627 void ScheduleIntersectionObserverNotification();
3628 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3630 DOMIntersectionObserver* GetLazyLoadImageObserver() {
3631 return mLazyLoadImageObserver;
3633 DOMIntersectionObserver& EnsureLazyLoadImageObserver();
3635 // Dispatch a runnable related to the document.
3636 nsresult Dispatch(TaskCategory aCategory,
3637 already_AddRefed<nsIRunnable>&& aRunnable) final;
3639 virtual nsISerialEventTarget* EventTargetFor(
3640 TaskCategory aCategory) const override;
3642 virtual AbstractThread* AbstractMainThreadFor(
3643 TaskCategory aCategory) override;
3645 // The URLs passed to this function should match what
3646 // JS::DescribeScriptedCaller() returns, since this API is used to
3647 // determine whether some code is being called from a tracking script.
3648 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3649 // The JSContext passed to this method represents the context that we want to
3650 // determine if it belongs to a tracker.
3651 bool IsScriptTracking(JSContext* aCx) const;
3653 // For more information on Flash classification, see
3654 // toolkit/components/url-classifier/flash-block-lists.rst
3655 FlashClassification DocumentFlashClassification();
3657 // ResizeObserver usage.
3658 void AddResizeObserver(ResizeObserver&);
3659 void RemoveResizeObserver(ResizeObserver&);
3660 void ScheduleResizeObserversNotification() const;
3662 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3663 PermissionDelegateHandler* GetPermissionDelegateHandler();
3666 * Localization
3668 * For more information on DocumentL10n see
3669 * intl/l10n/docs/fluent_tutorial.rst
3672 public:
3674 * This is a public method exposed on Document WebIDL
3675 * to chrome only documents.
3677 DocumentL10n* GetL10n();
3680 * This method should be called when the container
3681 * of l10n resources parsing is completed.
3683 * It triggers initial async fetch of the resources
3684 * as early as possible.
3686 * In HTML case this is </head>.
3687 * In XUL case this is </linkset>.
3689 void OnL10nResourceContainerParsed();
3692 * This method should be called when a link element
3693 * with rel="localization" is being added to the
3694 * l10n resource container element.
3696 void LocalizationLinkAdded(Element* aLinkElement);
3699 * This method should be called when a link element
3700 * with rel="localization" is being removed.
3702 void LocalizationLinkRemoved(Element* aLinkElement);
3705 * This method should be called as soon as the
3706 * parsing of the document is completed.
3708 * In HTML/XHTML this happens when we finish parsing
3709 * the document element.
3710 * In XUL it happens at `DoneWalking`, during
3711 * `MozBeforeInitialXULLayout`.
3713 void OnParsingCompleted();
3716 * This method is called when the initial translation
3717 * of the document is completed.
3719 * It unblocks the load event if translation was blocking it.
3721 * If the `aL10nCached` is set to `true`, and the document has
3722 * a prototype, it will set the `isL10nCached` flag on it.
3724 void InitialTranslationCompleted(bool aL10nCached);
3727 * Returns whether the document allows localization.
3729 bool AllowsL10n() const;
3731 protected:
3732 RefPtr<DocumentL10n> mDocumentL10n;
3735 * Return true when you want a document without explicitly specified viewport
3736 * dimensions/scale to be treated as if "width=device-width" had in fact been
3737 * specified.
3739 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3741 private:
3742 bool IsErrorPage() const;
3744 void EnsureL10n();
3746 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3747 // mUseCounters.
3748 void SetCssUseCounterBits();
3750 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3751 const nsAString& aHeightString,
3752 bool aIsAutoScale);
3754 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3755 // represents the scale property and returns the scale value if it's valid.
3756 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
3758 // Parse scale values in |aViewportMetaData| and set the values in
3759 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3760 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
3762 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3763 // stored in parent iframe or container's browsingContext (cross process)
3764 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
3766 FlashClassification DocumentFlashClassificationInternal();
3768 // The application cache that this document is associated with, if
3769 // any. This can change during the lifetime of the document.
3770 nsCOMPtr<nsIApplicationCache> mApplicationCache;
3772 public:
3773 bool IsThirdPartyForFlashClassifier();
3775 private:
3776 void DoCacheAllKnownLangPrefs();
3777 void RecomputeLanguageFromCharset();
3778 bool GetSHEntryHasUserInteraction();
3780 public:
3781 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
3783 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
3785 void SetSHEntryHasUserInteraction(bool aHasInteraction);
3787 already_AddRefed<nsAtom> GetContentLanguageAsAtomForStyle() const;
3788 already_AddRefed<nsAtom> GetLanguageForStyle() const;
3791 * Fetch the user's font preferences for the given aLanguage's
3792 * language group.
3794 const LangGroupFontPrefs* GetFontPrefsForLang(
3795 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
3797 void ForceCacheLang(nsAtom* aLanguage) {
3798 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
3799 return;
3801 GetFontPrefsForLang(aLanguage);
3804 void CacheAllKnownLangPrefs() {
3805 if (!mMayNeedFontPrefsUpdate) {
3806 return;
3808 DoCacheAllKnownLangPrefs();
3811 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
3813 uint32_t GetServoRestyleRootDirtyBits() const {
3814 MOZ_ASSERT(mServoRestyleRoot);
3815 MOZ_ASSERT(mServoRestyleRootDirtyBits);
3816 return mServoRestyleRootDirtyBits;
3819 void ClearServoRestyleRoot() {
3820 mServoRestyleRoot = nullptr;
3821 mServoRestyleRootDirtyBits = 0;
3824 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3825 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3827 bool ShouldThrowOnDynamicMarkupInsertion() {
3828 return mThrowOnDynamicMarkupInsertionCounter;
3831 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3832 ++mThrowOnDynamicMarkupInsertionCounter;
3835 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3836 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3837 --mThrowOnDynamicMarkupInsertionCounter;
3840 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
3842 void IncrementIgnoreOpensDuringUnloadCounter() {
3843 ++mIgnoreOpensDuringUnloadCounter;
3846 void DecrementIgnoreOpensDuringUnloadCounter() {
3847 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3848 --mIgnoreOpensDuringUnloadCounter;
3851 bool AllowPaymentRequest() const { return mAllowPaymentRequest; }
3853 void SetAllowPaymentRequest(bool aAllowPaymentRequest) {
3854 mAllowPaymentRequest = aAllowPaymentRequest;
3857 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
3859 bool ModuleScriptsEnabled();
3862 * Find the (non-anonymous) content in this document for aFrame. It will
3863 * be aFrame's content node if that content is in this document and not
3864 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
3865 * element containing the subdocument containing aFrame, and/or find the
3866 * nearest non-anonymous ancestor in this document.
3867 * Returns null if there is no such element.
3869 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
3871 void ReportShadowDOMUsage();
3873 // Sets flags for media autoplay telemetry.
3874 void SetDocTreeHadAudibleMedia();
3876 dom::XPathEvaluator* XPathEvaluator();
3878 void MaybeInitializeFinalizeFrameLoaders();
3880 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
3881 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
3884 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
3886 nsIPermissionDelegateHandler* PermDelegateHandler();
3888 // CSS prefers-color-scheme media feature for this document.
3889 enum class IgnoreRFP { No, Yes };
3890 StylePrefersColorScheme PrefersColorScheme(IgnoreRFP = IgnoreRFP::No) const;
3892 // Returns true if we use overlay scrollbars on the system wide or on the
3893 // given document.
3894 static bool UseOverlayScrollbars(const Document* aDocument);
3896 static bool HasRecentlyStartedForegroundLoads();
3898 static bool AutomaticStorageAccessPermissionCanBeGranted(
3899 nsIPrincipal* aPrincipal);
3901 already_AddRefed<Promise> AddCertException(bool aIsTemporary);
3903 // Subframes need to be static cloned after the main document has been
3904 // embedded within a script global. A `PendingFrameStaticClone` is a static
3905 // clone which has not yet been performed.
3907 // The getter returns a direct reference to an internal array which is
3908 // manipulated from within printing code.
3909 struct PendingFrameStaticClone {
3910 PendingFrameStaticClone() = default;
3911 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
3912 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
3913 ~PendingFrameStaticClone();
3915 RefPtr<nsFrameLoaderOwner> mElement;
3916 RefPtr<nsFrameLoader> mStaticCloneOf;
3918 nsTArray<PendingFrameStaticClone> TakePendingFrameStaticClones();
3919 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
3920 nsFrameLoader* aStaticCloneOf);
3922 bool ShouldAvoidNativeTheme() const;
3924 protected:
3925 void DoUpdateSVGUseElementShadowTrees();
3927 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
3928 nsIPrincipal* aPrincipal);
3930 void EnsureOnloadBlocker();
3932 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
3934 // Returns true if the scheme for the url for this document is "about".
3935 bool IsAboutPage() const;
3937 bool ContainsEMEContent();
3938 bool ContainsMSEContent();
3941 * Returns the title element of the document as defined by the HTML
3942 * specification, or null if there isn't one. For documents whose root
3943 * element is an <svg:svg>, this is the first <svg:title> element that's a
3944 * child of the root. For other documents, it's the first HTML title element
3945 * in the document.
3947 Element* GetTitleElement();
3949 void RecordNavigationTiming(ReadyState aReadyState);
3951 // Recomputes the visibility state but doesn't set the new value.
3952 dom::VisibilityState ComputeVisibilityState() const;
3954 // Since we wouldn't automatically play media from non-visited page, we need
3955 // to notify window when the page was first visited.
3956 void MaybeActiveMediaComponents();
3958 // Apply the fullscreen state to the document, and trigger related
3959 // events. It returns false if the fullscreen element ready check
3960 // fails and nothing gets changed.
3961 bool ApplyFullscreen(UniquePtr<FullscreenRequest>);
3963 bool GetUseCounter(UseCounter aUseCounter) {
3964 return mUseCounters[aUseCounter];
3967 void SetChildDocumentUseCounter(UseCounter aUseCounter) {
3968 if (!mChildDocumentUseCounters[aUseCounter]) {
3969 mChildDocumentUseCounters[aUseCounter] = true;
3973 bool GetChildDocumentUseCounter(UseCounter aUseCounter) {
3974 return mChildDocumentUseCounters[aUseCounter];
3977 void RemoveDocStyleSheetsFromStyleSets();
3978 void ResetStylesheetsToURI(nsIURI* aURI);
3979 void FillStyleSet();
3980 void FillStyleSetUserAndUASheets();
3981 void FillStyleSetDocumentSheets();
3982 void CompatibilityModeChanged();
3983 bool NeedsQuirksSheet() const {
3984 // SVG documents never load quirk.css.
3985 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
3986 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
3988 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
3989 void RemoveContentEditableStyleSheets();
3990 void AddStyleSheetToStyleSets(StyleSheet&);
3991 void RemoveStyleSheetFromStyleSets(StyleSheet&);
3992 void NotifyStyleSheetApplicableStateChanged();
3993 // Just like EnableStyleSheetsForSet, but doesn't check whether
3994 // aSheetSet is null and allows the caller to control whether to set
3995 // aSheetSet as the preferred set in the CSSLoader.
3996 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
3997 bool aUpdateCSSLoader);
3999 already_AddRefed<nsIURI> GetDomainURI();
4000 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4001 const nsACString& aHostString);
4002 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4003 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4005 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4006 mozilla::ErrorResult& aRv);
4007 // A version of WriteCommon used by WebIDL bindings
4008 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4009 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4011 void* GenerateParserKey(void);
4013 private:
4014 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4015 // parameter.
4016 enum class ExecCommandParam : uint8_t {
4017 // Always ignore it.
4018 Ignore,
4019 // Treat the given parameter as-is. If the command requires it, use it.
4020 // Otherwise, ignore it.
4021 String,
4022 // Always treat it as boolean parameter.
4023 Boolean,
4024 // Always treat it as boolean, but inverted.
4025 InvertedBoolean,
4028 typedef mozilla::EditorCommand*(GetEditorCommandFunc)();
4030 struct InternalCommandData {
4031 const char* mXULCommandName;
4032 mozilla::Command mCommand; // uint8_t
4033 // How ConvertToInternalCommand() to treats aValue.
4034 // Its callers don't need to check this.
4035 ExecCommandParam mExecCommandParam; // uint8_t
4036 GetEditorCommandFunc* mGetEditorCommandFunc;
4038 InternalCommandData()
4039 : mXULCommandName(nullptr),
4040 mCommand(mozilla::Command::DoNothing),
4041 mExecCommandParam(ExecCommandParam::Ignore),
4042 mGetEditorCommandFunc(nullptr) {}
4043 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4044 ExecCommandParam aExecCommandParam,
4045 GetEditorCommandFunc aGetEditorCommandFunc)
4046 : mXULCommandName(aXULCommandName),
4047 mCommand(aCommand),
4048 mExecCommandParam(aExecCommandParam),
4049 mGetEditorCommandFunc(aGetEditorCommandFunc) {}
4051 bool IsAvailableOnlyWhenEditable() const {
4052 return mCommand != mozilla::Command::Cut &&
4053 mCommand != mozilla::Command::Copy &&
4054 mCommand != mozilla::Command::Paste;
4056 bool IsCutOrCopyCommand() const {
4057 return mCommand == mozilla::Command::Cut ||
4058 mCommand == mozilla::Command::Copy;
4060 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4064 * Helper method to initialize sInternalCommandDataHashtable.
4066 static void EnsureInitializeInternalCommandDataHashtable();
4069 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4070 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4071 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4072 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4073 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4074 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4075 * returns a copy of instance created with default constructor. I.e., its
4076 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4077 * is unsupported in such case.
4079 * @param aHTMLCommandName Command name in HTML, e.g., used by
4080 * execCommand().
4081 * @param aValue The value which is set to the 3rd parameter
4082 * of execCommand().
4083 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4084 * Will be set to adjusted value for executing
4085 * the internal command.
4086 * @return Returns a copy of instance created with the
4087 * default constructor if there is no
4088 * corresponding internal command for
4089 * aHTMLCommandName or aValue is invalid for
4090 * found internal command when aAdjustedValue
4091 * is not nullptr. Otherwise, returns a copy of
4092 * instance registered in
4093 * sInternalCommandDataHashtable.
4095 static InternalCommandData ConvertToInternalCommand(
4096 const nsAString& aHTMLCommandName,
4097 const nsAString& aValue = EmptyString(),
4098 nsAString* aAdjustedValue = nullptr);
4101 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4102 * Since it's a bit field, not a bool member, therefore, we cannot use
4103 * AutoRestorer for it.
4105 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4106 public:
4107 AutoRunningExecCommandMarker() = delete;
4108 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4109 delete;
4110 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4111 MOZ_CAN_RUN_SCRIPT explicit AutoRunningExecCommandMarker(
4112 Document& aDocument)
4113 : mDocument(aDocument),
4114 mHasBeenRunning(aDocument.mIsRunningExecCommand) {
4115 aDocument.mIsRunningExecCommand = true;
4117 ~AutoRunningExecCommandMarker() {
4118 if (!mHasBeenRunning) {
4119 mDocument.mIsRunningExecCommand = false;
4123 private:
4124 Document& mDocument;
4125 bool mHasBeenRunning;
4128 // Mapping table from HTML command name to internal command.
4129 typedef nsDataHashtable<nsStringCaseInsensitiveHashKey, InternalCommandData>
4130 InternalCommandDataHashtable;
4131 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4133 mutable std::bitset<eDeprecatedOperationCount> mDeprecationWarnedAbout;
4134 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4136 // Lazy-initialization to have mDocGroup initialized in prior to the
4137 // SelectorCaches.
4138 UniquePtr<SelectorCache> mSelectorCache;
4139 UniquePtr<ServoStyleSet> mStyleSet;
4141 protected:
4142 friend class nsDocumentOnStack;
4144 void IncreaseStackRefCnt() { ++mStackRefCnt; }
4146 void DecreaseStackRefCnt() {
4147 if (--mStackRefCnt == 0 && mNeedsReleaseAfterStackRefCntRelease) {
4148 mNeedsReleaseAfterStackRefCntRelease = false;
4149 NS_RELEASE_THIS();
4153 // Never ever call this. Only call GetWindow!
4154 nsPIDOMWindowOuter* GetWindowInternal() const;
4156 // Never ever call this. Only call GetScriptHandlingObject!
4157 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4159 // Never ever call this. Only call AllowXULXBL!
4160 bool InternalAllowXULXBL();
4163 * These methods should be called before and after dispatching
4164 * a mutation event.
4165 * To make this easy and painless, use the mozAutoSubtreeModified helper
4166 * class.
4168 void WillDispatchMutationEvent(nsINode* aTarget);
4169 void MutationEventDispatched(nsINode* aTarget);
4170 friend class mozAutoSubtreeModified;
4172 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4174 void SetContentTypeInternal(const nsACString& aType);
4176 nsCString GetContentTypeInternal() const { return mContentType; }
4178 // Update our frame request callback scheduling state, if needed. This will
4179 // schedule or unschedule them, if necessary, and update
4180 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4181 // mPresShell is becoming null; in that case it will be used to get hold of
4182 // the relevant refresh driver.
4183 void UpdateFrameRequestCallbackSchedulingState(
4184 PresShell* aOldPresShell = nullptr);
4186 // Helper for GetScrollingElement/IsScrollingElement.
4187 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4189 void MaybeAllowStorageForOpenerAfterUserInteraction();
4191 void MaybeStoreUserInteractionAsPermission();
4193 // Helpers for GetElementsByName.
4194 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4195 nsAtom* aAtom, void* aData);
4196 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4198 void MaybeResolveReadyForIdle();
4200 typedef MozPromise<bool, bool, true>
4201 AutomaticStorageAccessPermissionGrantPromise;
4202 MOZ_MUST_USE RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4203 AutomaticStorageAccessPermissionCanBeGranted();
4205 static void AddToplevelLoadingDocument(Document* aDoc);
4206 static void RemoveToplevelLoadingDocument(Document* aDoc);
4207 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4208 friend class cycleCollection;
4210 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4211 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4213 nsString mLastModified;
4215 nsCOMPtr<nsIURI> mDocumentURI;
4216 nsCOMPtr<nsIURI> mOriginalURI;
4217 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4218 nsCOMPtr<nsIURI> mDocumentBaseURI;
4219 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4221 // The base domain of the document for third-party checks.
4222 nsCString mBaseDomain;
4224 // A lazily-constructed URL data for style system to resolve URL value.
4225 RefPtr<URLExtraData> mCachedURLData;
4226 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfo;
4228 nsWeakPtr mDocumentLoadGroup;
4230 bool mBlockAllMixedContent;
4231 bool mBlockAllMixedContentPreloads;
4232 bool mUpgradeInsecureRequests;
4233 bool mUpgradeInsecurePreloads;
4235 bool mDontWarnAboutMutationEventsAndAllowSlowDOMMutations;
4237 WeakPtr<nsDocShell> mDocumentContainer;
4239 NotNull<const Encoding*> mCharacterSet;
4240 int32_t mCharacterSetSource;
4242 // This is just a weak pointer; the parent document owns its children.
4243 Document* mParentDocument;
4245 // A reference to the element last returned from GetRootElement().
4246 Element* mCachedRootElement;
4248 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4249 // which in turn holds a strong reference to this mNodeInfoManager.
4250 nsNodeInfoManager* mNodeInfoManager;
4251 RefPtr<css::Loader> mCSSLoader;
4252 RefPtr<css::ImageLoader> mStyleImageLoader;
4253 RefPtr<nsHTMLStyleSheet> mAttrStyleSheet;
4254 RefPtr<nsHTMLCSSStyleSheet> mStyleAttrStyleSheet;
4256 // Tracking for images in the document.
4257 RefPtr<dom::ImageTracker> mImageTracker;
4259 // A hashtable of ShadowRoots belonging to the composed doc.
4261 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4262 ShadowRootSet mComposedShadowRoots;
4264 using SVGUseElementSet = nsTHashtable<nsPtrHashKey<SVGUseElement>>;
4266 // The set of <svg:use> elements that need a shadow tree reclone because the
4267 // tree they map to has changed.
4268 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4270 // The set of all object, embed, video/audio elements or
4271 // nsIObjectLoadingContent or DocumentActivity for which this is
4272 // the owner document. (They might not be in the document.)
4274 // These are non-owning pointers, the elements are responsible for removing
4275 // themselves when they go away.
4276 UniquePtr<nsTHashtable<nsPtrHashKey<nsISupports>>> mActivityObservers;
4278 // A hashtable of styled links keyed by address pointer.
4279 nsTHashtable<nsPtrHashKey<Link>> mStyledLinks;
4280 #ifdef DEBUG
4281 // Indicates whether mStyledLinks was cleared or not. This is used to track
4282 // state so we can provide useful assertions to consumers of ForgetLink and
4283 // AddStyleRelevantLink.
4284 bool mStyledLinksCleared;
4285 #endif
4287 // The array of all links that need their status resolved. Links must add
4288 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4289 // document.
4290 static const size_t kSegmentSize = 128;
4292 typedef SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>
4293 LinksToUpdateList;
4295 LinksToUpdateList mLinksToUpdate;
4297 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4298 RefPtr<SMILAnimationController> mAnimationController;
4300 // Table of element properties for this document.
4301 nsPropertyTable mPropertyTable;
4303 // Our cached .children collection
4304 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4306 // Various DOM lists
4307 RefPtr<nsContentList> mImages;
4308 RefPtr<nsContentList> mEmbeds;
4309 RefPtr<nsContentList> mLinks;
4310 RefPtr<nsContentList> mForms;
4311 RefPtr<nsContentList> mScripts;
4312 nsCOMPtr<nsIHTMLCollection> mApplets;
4313 RefPtr<nsContentList> mAnchors;
4315 // container for per-context fonts (downloadable, SVG, etc.)
4316 RefPtr<FontFaceSet> mFontFaceSet;
4318 // Last time this document or a one of its sub-documents was focused. If
4319 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4320 TimeStamp mLastFocusTime;
4322 EventStates mDocumentState;
4324 RefPtr<Promise> mReadyForIdle;
4326 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4328 UniquePtr<ResizeObserverController> mResizeObserverController;
4330 // Permission Delegate Handler, lazily-initialized in
4331 // GetPermissionDelegateHandler
4332 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4334 // True if BIDI is enabled.
4335 bool mBidiEnabled : 1;
4336 // True if we may need to recompute the language prefs for this document.
4337 bool mMayNeedFontPrefsUpdate : 1;
4338 // True if a MathML element has ever been owned by this document.
4339 bool mMathMLEnabled : 1;
4341 // True if this document is the initial document for a window. This should
4342 // basically be true only for documents that exist in newly-opened windows or
4343 // documents created to satisfy a GetDocument() on a window when there's no
4344 // document in it.
4345 bool mIsInitialDocumentInWindow : 1;
4347 bool mIgnoreDocGroupMismatches : 1;
4349 // True if we're loaded as data and therefor has any dangerous stuff, such
4350 // as scripts and plugins, disabled.
4351 bool mLoadedAsData : 1;
4353 // If true, whoever is creating the document has gotten it to the
4354 // point where it's safe to start layout on it.
4355 bool mMayStartLayout : 1;
4357 // True iff we've ever fired a DOMTitleChanged event for this document
4358 bool mHaveFiredTitleChange : 1;
4360 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4361 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4362 // before the initial load completes and when we're in bfcache or unloaded,
4363 // true otherwise.
4364 bool mIsShowing : 1;
4366 // State for IsVisible(). mVisible starts off true. It becomes false when
4367 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4368 // it's false only when we're in bfcache or unloaded.
4369 bool mVisible : 1;
4371 // True if our content viewer has been removed from the docshell
4372 // (it may still be displayed, but in zombie state). Form control data
4373 // has been saved.
4374 bool mRemovedFromDocShell : 1;
4376 // True iff DNS prefetch is allowed for this document. Note that if the
4377 // document has no window, DNS prefetch won't be performed no matter what.
4378 bool mAllowDNSPrefetch : 1;
4380 // True when this document is a static clone of a normal document
4381 bool mIsStaticDocument : 1;
4383 // True while this document is being cloned to a static document.
4384 bool mCreatingStaticClone : 1;
4386 // True iff the document is being unlinked or deleted.
4387 bool mInUnlinkOrDeletion : 1;
4389 // True if document has ever had script handling object.
4390 bool mHasHadScriptHandlingObject : 1;
4392 // True if we're an SVG document being used as an image.
4393 bool mIsBeingUsedAsImage : 1;
4395 // True if our current document URI's scheme is chrome://
4396 bool mDocURISchemeIsChrome : 1;
4398 // True if we're loaded in a chrome docshell.
4399 bool mInChromeDocShell : 1;
4401 // True if our current document is a DevTools document. Either the url is
4402 // about:devtools-toolbox or the parent document already has
4403 // mIsDevToolsDocument set to true.
4404 // This is used to avoid applying High Contrast mode to DevTools documents.
4405 // See Bug 1575766.
4406 bool mIsDevToolsDocument : 1;
4408 // True is this document is synthetic : stand alone image, video, audio
4409 // file, etc.
4410 bool mIsSyntheticDocument : 1;
4412 // True is there is a pending runnable which will call
4413 // FlushPendingLinkUpdates().
4414 bool mHasLinksToUpdateRunnable : 1;
4416 // True if we're flushing pending link updates.
4417 bool mFlushingPendingLinkUpdates : 1;
4419 // True if a DOMMutationObserver is perhaps attached to a node in the
4420 // document.
4421 bool mMayHaveDOMMutationObservers : 1;
4423 // True if an nsIAnimationObserver is perhaps attached to a node in the
4424 // document.
4425 bool mMayHaveAnimationObservers : 1;
4427 // True if a document load has a CSP attached.
4428 bool mHasCSP : 1;
4430 // True if a document load has a CSP with unsafe-eval attached.
4431 bool mHasUnsafeEvalCSP : 1;
4433 // True if a document load has a CSP with unsafe-inline attached.
4434 bool mHasUnsafeInlineCSP : 1;
4436 // True if the document has a CSP delivered throuh a header
4437 bool mHasCSPDeliveredThroughHeader : 1;
4439 // True if DisallowBFCaching has been called on this document.
4440 bool mBFCacheDisallowed : 1;
4442 bool mHasHadDefaultView : 1;
4444 // Whether style sheet change events will be dispatched for this document
4445 bool mStyleSheetChangeEventsEnabled : 1;
4447 // Whether the document was created by a srcdoc iframe.
4448 bool mIsSrcdocDocument : 1;
4450 // Whether this document has a display document and thus is considered to
4451 // be a resource document. Normally this is the same as !!mDisplayDocument,
4452 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4453 // valid in the document's destructor.
4454 bool mHasDisplayDocument : 1;
4456 // Is the current mFontFaceSet valid?
4457 bool mFontFaceSetDirty : 1;
4459 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4460 // (e.g. we're not being parsed at all).
4461 bool mDidFireDOMContentLoaded : 1;
4463 // True if ReportHasScrollLinkedEffect() has been called.
4464 bool mHasScrollLinkedEffect : 1;
4466 // True if we have frame request callbacks scheduled with the refresh driver.
4467 // This should generally be updated only via
4468 // UpdateFrameRequestCallbackSchedulingState.
4469 bool mFrameRequestCallbacksScheduled : 1;
4471 bool mIsTopLevelContentDocument : 1;
4473 bool mIsContentDocument : 1;
4475 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4476 bool mDidCallBeginLoad : 1;
4478 // True if the document is allowed to use PaymentRequest.
4479 bool mAllowPaymentRequest : 1;
4481 // True if the encoding menu should be disabled.
4482 bool mEncodingMenuDisabled : 1;
4484 // False if we've disabled link handling for elements inside this document,
4485 // true otherwise.
4486 bool mLinksEnabled : 1;
4488 // True if this document is for an SVG-in-OpenType font.
4489 bool mIsSVGGlyphsDocument : 1;
4491 // True if the document is being destroyed.
4492 bool mInDestructor : 1;
4494 // True if the document has been detached from its content viewer.
4495 bool mIsGoingAway : 1;
4497 bool mInXBLUpdate : 1;
4499 bool mNeedsReleaseAfterStackRefCntRelease : 1;
4501 // Whether we have filled our style set with all the stylesheets.
4502 bool mStyleSetFilled : 1;
4504 // Whether we have a quirks mode stylesheet in the style set.
4505 bool mQuirkSheetAdded : 1;
4507 // Whether we have a contenteditable.css stylesheet in the style set.
4508 bool mContentEditableSheetAdded : 1;
4510 // Whether we have a designmode.css stylesheet in the style set.
4511 bool mDesignModeSheetAdded : 1;
4513 // Keeps track of whether we have a pending
4514 // 'style-sheet-applicable-state-changed' notification.
4515 bool mSSApplicableStateNotificationPending : 1;
4517 // True if this document has ever had an HTML or SVG <title> element
4518 // bound to it
4519 bool mMayHaveTitleElement : 1;
4521 bool mDOMLoadingSet : 1;
4522 bool mDOMInteractiveSet : 1;
4523 bool mDOMCompleteSet : 1;
4524 bool mAutoFocusFired : 1;
4526 bool mScrolledToRefAlready : 1;
4527 bool mChangeScrollPosWhenScrollingToRef : 1;
4529 bool mDelayFrameLoaderInitialization : 1;
4531 bool mSynchronousDOMContentLoaded : 1;
4533 // Set to true when the document is possibly controlled by the ServiceWorker.
4534 // Used to prevent multiple requests to ServiceWorkerManager.
4535 bool mMaybeServiceWorkerControlled : 1;
4537 // These member variables cache information about the viewport so we don't
4538 // have to recalculate it each time.
4539 bool mAllowZoom : 1;
4540 bool mValidScaleFloat : 1;
4541 bool mValidMinScale : 1;
4542 bool mValidMaxScale : 1;
4543 bool mWidthStrEmpty : 1;
4545 // Parser aborted. True if the parser of this document was forcibly
4546 // terminated instead of letting it finish at its own pace.
4547 bool mParserAborted : 1;
4549 // Whether we have reported use counters for this document with Telemetry yet.
4550 // Normally this is only done at document destruction time, but for image
4551 // documents (SVG documents) that are not guaranteed to be destroyed, we
4552 // report use counters when the image cache no longer has any imgRequestProxys
4553 // pointing to them. We track whether we ever reported use counters so
4554 // that we only report them once for the document.
4555 bool mReportedUseCounters : 1;
4557 bool mHasReportedShadowDOMUsage : 1;
4559 // Whether an event triggered by the refresh driver was delayed because this
4560 // document has suppressed events.
4561 bool mHasDelayedRefreshEvent : 1;
4563 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4564 // to have the right semantics. See
4565 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4566 // flag that is set while the window's 'load' event is firing if this document
4567 // is the window's document.
4568 bool mLoadEventFiring : 1;
4570 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4571 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4572 // What we have instead is a flag that is set if completion of our document
4573 // via document.close() should skip firing the load event. Note that this
4574 // flag is only relevant for HTML documents, but lives here for reasons that
4575 // are documented above on SkipLoadEventAfterClose().
4576 bool mSkipLoadEventAfterClose : 1;
4578 // When false, the .cookies property is completely disabled
4579 bool mDisableCookieAccess : 1;
4581 // When false, the document.write() API is disabled.
4582 bool mDisableDocWrite : 1;
4584 // Has document.write() been called with a recursion depth higher than
4585 // allowed?
4586 bool mTooDeepWriteRecursion : 1;
4589 * Temporary flag that is set in EndUpdate() to ignore
4590 * MaybeEditingStateChanged() script runners from a nested scope.
4592 bool mPendingMaybeEditingStateChanged : 1;
4594 // mHasBeenEditable is set to true when mEditingState is firstly set to
4595 // eDesignMode or eContentEditable.
4596 bool mHasBeenEditable : 1;
4598 // Whether we've warned about the CSS zoom property.
4600 // We don't use the general deprecated operation mechanism for this because we
4601 // also record this as a `CountedUnknownProperty`.
4602 bool mHasWarnedAboutZoom : 1;
4604 // While we're handling an execCommand call, set to true.
4605 bool mIsRunningExecCommand : 1;
4607 // True if we should change the readystate to complete after we fire
4608 // DOMContentLoaded. This happens when we abort a load and
4609 // nsDocumentViewer::EndLoad runs while we still have things blocking
4610 // DOMContentLoaded. We wait for those to complete, and then update the
4611 // readystate when they finish.
4612 bool mSetCompleteAfterDOMContentLoaded : 1;
4614 uint8_t mPendingFullscreenRequests;
4616 uint8_t mXMLDeclarationBits;
4618 // Currently active onload blockers.
4619 uint32_t mOnloadBlockCount;
4621 // Onload blockers which haven't been activated yet.
4622 uint32_t mAsyncOnloadBlockCount;
4624 // Tracks if we are currently processing any document.write calls (either
4625 // implicit or explicit). Note that if a write call writes out something which
4626 // would block the parser, then mWriteLevel will be incorrect until the parser
4627 // finishes processing that script.
4628 uint32_t mWriteLevel;
4630 uint32_t mContentEditableCount;
4631 EditingState mEditingState;
4633 // Compatibility mode
4634 nsCompatibility mCompatMode;
4636 // Our readyState
4637 ReadyState mReadyState;
4639 // Ancestor's loading state
4640 bool mAncestorIsLoading;
4642 // Our visibility state
4643 dom::VisibilityState mVisibilityState;
4645 enum Type {
4646 eUnknown, // should never be used
4647 eHTML,
4648 eXHTML,
4649 eGenericXML,
4650 eSVG
4653 Type mType;
4655 uint8_t mDefaultElementType;
4657 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4659 Tri mAllowXULXBL;
4661 bool mSkipDTDSecurityChecks;
4663 // The document's script global object, the object from which the
4664 // document can get its script context and scope. This is the
4665 // *inner* window object.
4666 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4668 // If mIsStaticDocument is true, mOriginalDocument points to the original
4669 // document.
4670 RefPtr<Document> mOriginalDocument;
4672 // The bidi options for this document. What this bitfield means is
4673 // defined in nsBidiUtils.h
4674 uint32_t mBidiOptions;
4676 // The sandbox flags on the document. These reflect the value of the sandbox
4677 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4678 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4679 // possible flags.
4680 uint32_t mSandboxFlags;
4682 // The embedder policy obtained from parsing the HTTP response header or from
4683 // our opener if this is the initial about:blank document.
4684 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4686 nsCString mContentLanguage;
4688 // The channel that got passed to Document::StartDocumentLoad(), if any.
4689 nsCOMPtr<nsIChannel> mChannel;
4691 // The CSP for every load lives in the Client within the LoadInfo. For all
4692 // document-initiated subresource loads we can use that cached version of the
4693 // CSP so we do not have to deserialize the CSP from the Client all the time.
4694 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4695 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4697 private:
4698 nsCString mContentType;
4700 protected:
4701 // The document's security info
4702 nsCOMPtr<nsISupports> mSecurityInfo;
4704 // The channel that failed to load and resulted in an error page.
4705 // This only applies to error pages. Might be null.
4706 nsCOMPtr<nsIChannel> mFailedChannel;
4708 // if this document is part of a multipart document,
4709 // the ID can be used to distinguish it from the other parts.
4710 uint32_t mPartID;
4712 // Cycle collector generation in which we're certain that this document
4713 // won't be collected
4714 uint32_t mMarkedCCGeneration;
4716 PresShell* mPresShell;
4718 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4719 uint32_t mSubtreeModifiedDepth;
4721 // All images in process of being preloaded. This is a hashtable so
4722 // we can remove them as the real image loads start; that way we
4723 // make sure to not keep the image load going when no one cares
4724 // about it anymore.
4725 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4727 // A list of preconnects initiated by the preloader. This prevents
4728 // the same uri from being used more than once, and allows the dom
4729 // builder to not repeat the work of the preloader.
4730 nsDataHashtable<nsURIHashKey, bool> mPreloadedPreconnects;
4732 // Current depth of picture elements from parser
4733 uint32_t mPreloadPictureDepth;
4735 // Set if we've found a URL for the current picture
4736 nsString mPreloadPictureFoundSource;
4738 // If we're an external resource document, this will be non-null and will
4739 // point to our "display document": the one that all resource lookups should
4740 // go to.
4741 RefPtr<Document> mDisplayDocument;
4743 uint32_t mEventsSuppressed;
4745 // Any XHR ChannelEventQueues that were suspended on this document while
4746 // events were suppressed.
4747 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
4749 // Any postMessage events that were suspended on this document while events
4750 // were suppressed.
4751 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
4753 RefPtr<EventListener> mSuppressedEventListener;
4756 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
4758 uint32_t mIgnoreDestructiveWritesCounter;
4761 * The current frame request callback handle
4763 int32_t mFrameRequestCallbackCounter;
4765 // Count of live static clones of this document.
4766 uint32_t mStaticCloneCount;
4768 // If the document is currently printing (or in print preview) this will point
4769 // to the current static clone of this document. This is weak since the clone
4770 // also has a reference to this document.
4771 WeakPtr<Document> mLatestStaticClone;
4773 // Array of nodes that have been blocked to prevent user tracking.
4774 // They most likely have had their nsIChannel canceled by the URL
4775 // classifier. (Safebrowsing)
4777 // Weak nsINode pointers are used to allow nodes to disappear.
4778 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
4780 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
4781 // updated on every set of mScriptGlobalObject.
4782 nsPIDOMWindowInner* mWindow;
4784 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
4786 nsTArray<FrameRequest> mFrameRequestCallbacks;
4788 // The set of frame request callbacks that were canceled but which we failed
4789 // to find in mFrameRequestCallbacks.
4790 HashSet<int32_t> mCanceledFrameRequestCallbacks;
4792 // This object allows us to evict ourself from the back/forward cache. The
4793 // pointer is non-null iff we're currently in the bfcache.
4794 nsIBFCacheEntry* mBFCacheEntry;
4796 // Our base target.
4797 nsString mBaseTarget;
4799 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
4800 nsCOMPtr<nsIVariant> mStateObjectCached;
4802 uint32_t mInSyncOperationCount;
4804 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
4806 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
4808 uint32_t mBlockDOMContentLoaded;
4810 // Our live MediaQueryLists
4811 LinkedList<MediaQueryList> mDOMMediaQueryLists;
4813 // Array of observers
4814 nsTObserverArray<nsIDocumentObserver*> mObservers;
4816 // Flags for use counters used directly by this document.
4817 std::bitset<eUseCounter_Count> mUseCounters;
4818 // Flags for use counters used by any child documents of this document.
4819 std::bitset<eUseCounter_Count> mChildDocumentUseCounters;
4821 // The CSS property use counters.
4822 UniquePtr<StyleUseCounters> mStyleUseCounters;
4824 // Whether the user has interacted with the document or not:
4825 bool mUserHasInteracted;
4827 // We constantly update the user-interaction anti-tracking permission at any
4828 // user-interaction using a timer. This boolean value is set to true when this
4829 // timer is scheduled.
4830 bool mHasUserInteractionTimerScheduled;
4832 TimeStamp mPageUnloadingEventTimeStamp;
4834 RefPtr<DocGroup> mDocGroup;
4836 RefPtr<nsCommandManager> mMidasCommandManager;
4838 // The set of all the tracking script URLs. URLs are added to this set by
4839 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
4840 // existing in the set means the corresponding script isn't a tracking script.
4841 nsTHashtable<nsCStringHashKey> mTrackingScripts;
4843 // Pointer to our parser if we're currently in the process of being
4844 // parsed into.
4845 nsCOMPtr<nsIParser> mParser;
4847 // If the document was created from the the prototype cache there will be a
4848 // reference to the prototype document to allow tracing.
4849 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
4851 nsrefcnt mStackRefCnt;
4853 // Weak reference to our sink for in case we no longer have a parser. This
4854 // will allow us to flush out any pending stuff from the sink even if
4855 // EndLoad() has already happened.
4856 nsWeakPtr mWeakSink;
4858 // Our update nesting level
4859 uint32_t mUpdateNestLevel;
4861 // HTTPS-Only Mode Status
4862 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
4863 uint32_t mHttpsOnlyStatus;
4865 enum ViewportType : uint8_t {
4866 DisplayWidthHeight,
4867 Specified,
4868 Unknown,
4871 ViewportType mViewportType;
4873 // viewport-fit described by
4874 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
4875 ViewportFitType mViewportFit;
4877 PLDHashTable* mSubDocuments;
4879 DocHeaderData* mHeaderData;
4881 // For determining if this is a flash document which should be
4882 // blocked based on its principal.
4883 FlashClassification mFlashClassification;
4885 // Do not use this value directly. Call the |IsThirdPartyForFlashClassifier()|
4886 // method, which caches its result here.
4887 Maybe<bool> mIsThirdPartyForFlashClassifier;
4889 nsRevocableEventPtr<nsRunnableMethod<Document, void, false>>
4890 mPendingTitleChangeEvent;
4892 RefPtr<nsDOMNavigationTiming> mTiming;
4894 // Recorded time of change to 'loading' state.
4895 TimeStamp mLoadingTimeStamp;
4897 nsWeakPtr mAutoFocusElement;
4899 nsCString mScrollToRef;
4901 nscoord mScrollAnchorAdjustmentLength;
4902 int32_t mScrollAnchorAdjustmentCount;
4904 // Weak reference to the scope object (aka the script global object)
4905 // that, unlike mScriptGlobalObject, is never unset once set. This
4906 // is a weak reference to avoid leaks due to circular references.
4907 nsWeakPtr mScopeObject;
4909 // Array of intersection observers
4910 nsTHashtable<nsPtrHashKey<DOMIntersectionObserver>> mIntersectionObservers;
4912 RefPtr<DOMIntersectionObserver> mLazyLoadImageObserver;
4914 // Stack of top layer elements.
4915 nsTArray<nsWeakPtr> mTopLayer;
4917 // The root of the doc tree in which this document is in. This is only
4918 // non-null when this document is in fullscreen mode.
4919 nsWeakPtr mFullscreenRoot;
4921 RefPtr<DOMImplementation> mDOMImplementation;
4923 RefPtr<nsContentList> mImageMaps;
4925 // A set of responsive images keyed by address pointer.
4926 nsTHashtable<nsPtrHashKey<HTMLImageElement>> mResponsiveContent;
4928 // Tracking for plugins in the document.
4929 nsTHashtable<nsPtrHashKey<nsIObjectLoadingContent>> mPlugins;
4931 RefPtr<DocumentTimeline> mDocumentTimeline;
4932 LinkedList<DocumentTimeline> mTimelines;
4934 RefPtr<dom::ScriptLoader> mScriptLoader;
4936 // Tracker for animations that are waiting to start.
4937 // nullptr until GetOrCreatePendingAnimationTracker is called.
4938 RefPtr<PendingAnimationTracker> mPendingAnimationTracker;
4940 // A document "without a browsing context" that owns the content of
4941 // HTMLTemplateElement.
4942 RefPtr<Document> mTemplateContentsOwner;
4944 dom::ExternalResourceMap mExternalResourceMap;
4946 // ScreenOrientation "pending promise" as described by
4947 // http://www.w3.org/TR/screen-orientation/
4948 RefPtr<Promise> mOrientationPendingPromise;
4950 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
4951 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
4952 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
4954 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
4956 // The layout history state that should be used by nodes in this
4957 // document. We only actually store a pointer to it when:
4958 // 1) We have no script global object.
4959 // 2) We haven't had Destroy() called on us yet.
4960 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
4962 struct MetaViewportElementAndData;
4963 // An array of <meta name="viewport"> elements and their data.
4964 nsTArray<MetaViewportElementAndData> mMetaViewports;
4966 // These member variables cache information about the viewport so we don't
4967 // have to recalculate it each time.
4968 LayoutDeviceToScreenScale mScaleMinFloat;
4969 LayoutDeviceToScreenScale mScaleMaxFloat;
4970 LayoutDeviceToScreenScale mScaleFloat;
4971 CSSToLayoutDeviceScale mPixelRatio;
4973 CSSCoord mMinWidth;
4974 CSSCoord mMaxWidth;
4975 CSSCoord mMinHeight;
4976 CSSCoord mMaxHeight;
4978 RefPtr<EventListenerManager> mListenerManager;
4980 nsCOMPtr<nsIRequest> mOnloadBlocker;
4982 // Gecko-internal sheets used for extensions and such.
4983 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
4984 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
4986 // Member to store out last-selected stylesheet set.
4987 nsString mLastStyleSheetSet;
4988 nsString mPreferredStyleSheetSet;
4990 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
4992 // We lazily calculate declaration blocks for SVG elements with mapped
4993 // attributes in Servo mode. This list contains all elements which need lazy
4994 // resolution.
4995 nsTHashtable<nsPtrHashKey<SVGElement>> mLazySVGPresElements;
4997 nsTHashtable<nsRefPtrHashKey<nsAtom>> mLanguagesUsed;
4999 // TODO(emilio): Is this hot enough to warrant to be cached?
5000 RefPtr<nsAtom> mLanguageFromCharset;
5002 // Restyle root for servo's style system.
5004 // We store this as an nsINode, rather than as an Element, so that we can
5005 // store the Document node as the restyle root if the entire document (along
5006 // with all document-level native-anonymous content) needs to be restyled.
5008 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5009 // root corresponds to.
5010 nsCOMPtr<nsINode> mServoRestyleRoot;
5011 uint32_t mServoRestyleRootDirtyBits;
5013 // Used in conjunction with the create-an-element-for-the-token algorithm to
5014 // prevent custom element constructors from being able to use document.open(),
5015 // document.close(), and document.write() when they are invoked by the parser.
5016 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5018 // Count of unload/beforeunload/pagehide operations in progress.
5019 uint32_t mIgnoreOpensDuringUnloadCounter;
5021 nsCOMPtr<nsIDOMXULCommandDispatcher>
5022 mCommandDispatcher; // [OWNER] of the focus tracker
5024 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5025 RefPtr<XULPersist> mXULPersist;
5026 RefPtr<ChromeObserver> mChromeObserver;
5028 RefPtr<HTMLAllCollection> mAll;
5030 // document lightweight theme for use with :-moz-lwtheme,
5031 // :-moz-lwtheme-brighttext and :-moz-lwtheme-darktext
5032 DocumentTheme mDocLWTheme;
5034 // Pres shell resolution saved before entering fullscreen mode.
5035 float mSavedResolution;
5037 // Pres shell resolution saved before creating a MobileViewportManager.
5038 float mSavedResolutionBeforeMVM;
5040 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5042 bool mHasStoragePermission;
5044 // Document generation. Gets incremented everytime it changes.
5045 int32_t mGeneration;
5047 // Cached TabSizes values for the document.
5048 int32_t mCachedTabSizeGeneration;
5049 nsTabSizes mCachedTabSizes;
5051 // This is equal to document's principal but with an isolation key. See
5052 // StoragePrincipalHelper.h to know more.
5053 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5055 // The cached storage principal for this document.
5056 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5057 // which is required due to its CloneDocHelper() call site. :-(
5058 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5060 // The principal to use for the content blocking allow list.
5061 nsCOMPtr<nsIPrincipal> mContentBlockingAllowListPrincipal;
5063 // See GetNextFormNumber and GetNextControlNumber.
5064 int32_t mNextFormNumber;
5065 int32_t mNextControlNumber;
5067 // Scope preloads per document. This is used by speculative loading as well.
5068 PreloadService mPreloadService;
5070 public:
5071 // Needs to be public because the bindings code pokes at it.
5072 js::ExpandoAndGeneration mExpandoAndGeneration;
5074 bool HasPendingInitialTranslation();
5076 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5077 mL10nProtoElements;
5079 void TraceProtos(JSTracer* aTrc);
5081 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5082 void SetSavedResolutionBeforeMVM(float aResolution) {
5083 mSavedResolutionBeforeMVM = aResolution;
5087 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5090 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5091 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5092 * object is deleted.
5094 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5095 public:
5097 * @param aSubTreeOwner The document in which a subtree will be modified.
5098 * @param aTarget The target of the possible DOMSubtreeModified event.
5099 * Can be nullptr, in which case mozAutoSubtreeModified
5100 * is just used to batch DOM mutations.
5102 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5103 UpdateTarget(aSubtreeOwner, aTarget);
5106 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5108 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5109 if (mSubtreeOwner) {
5110 mSubtreeOwner->MutationEventDispatched(mTarget);
5113 mTarget = aTarget;
5114 mSubtreeOwner = aSubtreeOwner;
5115 if (mSubtreeOwner) {
5116 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5120 private:
5121 nsCOMPtr<nsINode> mTarget;
5122 RefPtr<Document> mSubtreeOwner;
5125 class MOZ_STACK_CLASS nsAutoSyncOperation {
5126 public:
5127 explicit nsAutoSyncOperation(Document* aDocument);
5128 ~nsAutoSyncOperation();
5130 private:
5131 nsTArray<RefPtr<Document>> mDocuments;
5132 uint32_t mMicroTaskLevel;
5135 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5136 public:
5137 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5138 : mDocument(aDocument) {
5139 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5142 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5143 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5146 private:
5147 Document* mDocument;
5150 class MOZ_RAII IgnoreOpensDuringUnload final {
5151 public:
5152 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5153 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5156 ~IgnoreOpensDuringUnload() {
5157 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5160 private:
5161 Document* mDoc;
5164 bool IsInActiveTab(Document* aDoc);
5166 } // namespace dom
5167 } // namespace mozilla
5169 // XXX These belong somewhere else
5170 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5171 bool aLoadedAsData = false);
5173 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5174 bool aLoadedAsData = false,
5175 bool aIsPlainDocument = false);
5177 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult);
5179 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult);
5181 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult);
5183 // Enum for requesting a particular type of document when creating a doc
5184 enum DocumentFlavor {
5185 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5186 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5187 DocumentFlavorSVG, // SVGDocument
5188 DocumentFlavorXML, // XMLDocument
5189 DocumentFlavorPlain, // Just a Document
5192 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5193 // -- this method will not attempt to get a principal based on aDocumentURI.
5194 // Also, both aDocumentURI and aBaseURI must not be null.
5195 nsresult NS_NewDOMDocument(
5196 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5197 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5198 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5199 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5201 nsresult NS_NewPluginDocument(mozilla::dom::Document** aInstancePtrResult);
5203 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5204 mozilla::dom::Document* ownerDoc = OwnerDoc();
5206 return ownerDoc != this ? ownerDoc : nullptr;
5209 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5211 inline bool ShouldUseNACScope(const nsINode* aNode) {
5212 return aNode->IsInNativeAnonymousSubtree();
5215 inline bool ShouldUseUAWidgetScope(const nsINode* aNode) {
5216 return aNode->HasBeenInUAWidget();
5219 inline mozilla::dom::ParentObject nsINode::GetParentObject() const {
5220 mozilla::dom::ParentObject p(OwnerDoc());
5221 // Note that mReflectionScope is a no-op for chrome, and other places
5222 // where we don't check this value.
5223 if (ShouldUseNACScope(this)) {
5224 p.mReflectionScope = mozilla::dom::ReflectionScope::NAC;
5225 } else if (ShouldUseUAWidgetScope(this)) {
5226 p.mReflectionScope = mozilla::dom::ReflectionScope::UAWidget;
5228 return p;
5231 inline mozilla::dom::Document* nsINode::AsDocument() {
5232 MOZ_ASSERT(IsDocument());
5233 return static_cast<mozilla::dom::Document*>(this);
5236 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5237 MOZ_ASSERT(IsDocument());
5238 return static_cast<const mozilla::dom::Document*>(this);
5241 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5242 return static_cast<nsINode*>(aDoc);
5245 #endif /* mozilla_dom_Document_h___ */