Source code

Revision control

Other Tools

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___
8
9
#include "mozilla/EventStates.h" // for EventStates
10
#include "mozilla/FlushType.h" // for enum
11
#include "mozilla/Pair.h" // for Pair
12
#include "mozilla/Saturate.h" // for SaturateUint32
13
#include "nsAutoPtr.h" // for member
14
#include "nsCOMArray.h" // for member
15
#include "nsCompatibility.h" // for member
16
#include "nsCOMPtr.h" // for member
17
#include "nsICookieSettings.h"
18
#include "nsGkAtoms.h" // for static class members
19
#include "nsIApplicationCache.h"
20
#include "nsIApplicationCacheContainer.h"
21
#include "nsIContentViewer.h"
22
#include "nsIDOMXULCommandDispatcher.h"
23
#include "nsIInterfaceRequestor.h"
24
#include "nsILoadContext.h"
25
#include "nsILoadGroup.h" // for member (in nsCOMPtr)
26
#include "nsINode.h" // for base class
27
#include "nsIParser.h"
28
#include "nsIChannelEventSink.h"
29
#include "nsIProgressEventSink.h"
30
#include "nsIRadioGroupContainer.h"
31
#include "nsIScriptObjectPrincipal.h"
32
#include "nsIScriptGlobalObject.h" // for member (in nsCOMPtr)
33
#include "nsIServiceManager.h"
34
#include "nsIURI.h" // for use in inline functions
35
#include "nsIUUIDGenerator.h"
36
#include "nsIWebProgressListener.h" // for nsIWebProgressListener
37
#include "nsIWeakReferenceUtils.h" // for nsWeakPtr
38
#include "nsPIDOMWindow.h" // for use in inline functions
39
#include "nsPropertyTable.h" // for member
40
#include "nsStringFwd.h"
41
#include "nsStubMutationObserver.h"
42
#include "nsTHashtable.h" // for member
43
#include "nsURIHashKey.h"
44
#include "mozilla/net/ReferrerPolicy.h" // for member
45
#include "mozilla/UseCounter.h"
46
#include "mozilla/WeakPtr.h"
47
#include "mozilla/StaticPresData.h"
48
#include "Units.h"
49
#include "nsContentListDeclarations.h"
50
#include "nsExpirationTracker.h"
51
#include "nsClassHashtable.h"
52
#include "ReferrerInfo.h"
53
#include "mozilla/Attributes.h"
54
#include "mozilla/CORSMode.h"
55
#include "mozilla/dom/BrowsingContext.h"
56
#include "mozilla/dom/ContentBlockingLog.h"
57
#include "mozilla/dom/DispatcherTrait.h"
58
#include "mozilla/dom/DocumentOrShadowRoot.h"
59
#include "mozilla/HashTable.h"
60
#include "mozilla/LinkedList.h"
61
#include "mozilla/NotNull.h"
62
#include "mozilla/SegmentedVector.h"
63
#include "mozilla/ServoBindingTypes.h"
64
#include "mozilla/StyleSheet.h"
65
#include "mozilla/TimeStamp.h"
66
#include "mozilla/UniquePtr.h"
67
#include "mozilla/dom/FailedCertSecurityInfoBinding.h"
68
#include <bitset> // for member
69
70
// windows.h #defines CreateEvent
71
#ifdef CreateEvent
72
# undef CreateEvent
73
#endif
74
75
#ifdef MOZILLA_INTERNAL_API
76
# include "mozilla/dom/DocumentBinding.h"
77
#else
78
namespace mozilla {
79
namespace dom {
80
class ElementCreationOptionsOrString;
81
} // namespace dom
82
} // namespace mozilla
83
#endif // MOZILLA_INTERNAL_API
84
85
class gfxUserFontSet;
86
class imgIRequest;
87
class nsBindingManager;
88
class nsCachableElementsByNameNodeList;
89
class nsContentList;
90
class nsIDocShell;
91
class nsDocShell;
92
class nsDOMNavigationTiming;
93
class nsFrameLoader;
94
class nsGlobalWindowInner;
95
class nsHtml5TreeOpExecutor;
96
class nsHTMLCSSStyleSheet;
97
class nsHTMLDocument;
98
class nsHTMLStyleSheet;
99
class nsGenericHTMLElement;
100
class nsAtom;
101
class nsIBFCacheEntry;
102
class nsIChannel;
103
class nsIContent;
104
class nsIContentSecurityPolicy;
105
class nsIContentSink;
106
class nsIDocShell;
107
class nsIDocShellTreeItem;
108
class nsIDocumentEncoder;
109
class nsIDocumentObserver;
110
class nsIHTMLCollection;
111
class nsILayoutHistoryState;
112
class nsILoadContext;
113
class nsIObjectLoadingContent;
114
class nsIObserver;
115
class nsIPrincipal;
116
class nsIRequest;
117
class nsIRunnable;
118
class nsISecurityConsoleMessage;
119
class nsIStreamListener;
120
class nsIStructuredCloneContainer;
121
class nsIURI;
122
class nsIVariant;
123
class nsViewManager;
124
class nsPresContext;
125
class nsRange;
126
class nsSimpleContentList;
127
class nsTextNode;
128
class nsWindowSizes;
129
class nsDOMCaretPosition;
130
class nsViewportInfo;
131
class nsIGlobalObject;
132
class nsIXULWindow;
133
class nsXULPrototypeDocument;
134
struct nsFont;
135
136
namespace mozilla {
137
class AbstractThread;
138
class CSSStyleSheet;
139
class EditorCommand;
140
class Encoding;
141
class ErrorResult;
142
class EventStates;
143
class EventListenerManager;
144
class FullscreenExit;
145
class FullscreenRequest;
146
class PendingAnimationTracker;
147
class PresShell;
148
class ServoStyleSet;
149
class SMILAnimationController;
150
enum class StyleCursorKind : uint8_t;
151
template <typename>
152
class OwningNonNull;
153
struct URLExtraData;
154
155
namespace css {
156
class Loader;
157
class ImageLoader;
158
class Rule;
159
} // namespace css
160
161
namespace dom {
162
class Animation;
163
class AnonymousContent;
164
class Attr;
165
class XULBroadcastManager;
166
class XULPersist;
167
class ClientInfo;
168
class ClientState;
169
class CDATASection;
170
class Comment;
171
struct CustomElementDefinition;
172
class DocGroup;
173
class DocumentL10n;
174
class DocumentFragment;
175
class DocumentTimeline;
176
class DocumentType;
177
class DOMImplementation;
178
class DOMIntersectionObserver;
179
class DOMStringList;
180
class Element;
181
struct ElementCreationOptions;
182
class Event;
183
class EventTarget;
184
class FeaturePolicy;
185
class FontFaceSet;
186
class FrameRequestCallback;
187
class ImageTracker;
188
class HTMLAllCollection;
189
class HTMLBodyElement;
190
class HTMLSharedElement;
191
class HTMLImageElement;
192
struct LifecycleCallbackArgs;
193
class Link;
194
class Location;
195
class MediaQueryList;
196
class GlobalObject;
197
class NodeFilter;
198
class NodeIterator;
199
enum class OrientationType : uint8_t;
200
class ProcessingInstruction;
201
class Promise;
202
class ScriptLoader;
203
class Selection;
204
class ServiceWorkerDescriptor;
205
class StyleSheetList;
206
class SVGDocument;
207
class SVGElement;
208
class SVGSVGElement;
209
class SVGUseElement;
210
class Touch;
211
class TouchList;
212
class TreeWalker;
213
class XPathEvaluator;
214
class XPathExpression;
215
class XPathNSResolver;
216
class XPathResult;
217
class XULDocument;
218
template <typename>
219
class Sequence;
220
221
class nsDocumentOnStack;
222
class nsUnblockOnloadEvent;
223
224
template <typename, typename>
225
class CallbackObjectHolder;
226
227
enum class CallerType : uint32_t;
228
229
enum BFCacheStatus {
230
NOT_ALLOWED = 1 << 0, // Status 0
231
EVENT_HANDLING_SUPPRESSED = 1 << 1, // Status 1
232
SUSPENDED = 1 << 2, // Status 2
233
UNLOAD_LISTENER = 1 << 3, // Status 3
234
REQUEST = 1 << 4, // Status 4
235
ACTIVE_GET_USER_MEDIA = 1 << 5, // Status 5
236
ACTIVE_PEER_CONNECTION = 1 << 6, // Status 6
237
CONTAINS_EME_CONTENT = 1 << 7, // Status 7
238
CONTAINS_MSE_CONTENT = 1 << 8, // Status 8
239
HAS_ACTIVE_SPEECH_SYNTHESIS = 1 << 9, // Status 9
240
HAS_USED_VR = 1 << 10, // Status 10
241
};
242
243
} // namespace dom
244
} // namespace mozilla
245
246
namespace mozilla {
247
namespace net {
248
class ChannelEventQueue;
249
} // namespace net
250
} // namespace mozilla
251
252
// Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
253
#define NS_IDOCUMENT_IID \
254
{ \
255
0xce1f7627, 0x7109, 0x4977, { \
256
0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
257
} \
258
}
259
260
namespace mozilla {
261
namespace dom {
262
263
class Document;
264
class DOMStyleSheetSetList;
265
class ResizeObserver;
266
class ResizeObserverController;
267
class PostMessageEvent;
268
269
// Document states
270
271
// RTL locale: specific to the XUL localedir attribute
272
#define NS_DOCUMENT_STATE_RTL_LOCALE NS_DEFINE_EVENT_STATE_MACRO(0)
273
// Window activation status
274
#define NS_DOCUMENT_STATE_WINDOW_INACTIVE NS_DEFINE_EVENT_STATE_MACRO(1)
275
276
class DocHeaderData {
277
public:
278
DocHeaderData(nsAtom* aField, const nsAString& aData)
279
: mField(aField), mData(aData), mNext(nullptr) {}
280
281
~DocHeaderData(void) { delete mNext; }
282
283
RefPtr<nsAtom> mField;
284
nsString mData;
285
DocHeaderData* mNext;
286
};
287
288
class ExternalResourceMap {
289
typedef bool (*SubDocEnumFunc)(Document* aDocument, void* aData);
290
291
public:
292
/**
293
* A class that represents an external resource load that has begun but
294
* doesn't have a document yet. Observers can be registered on this object,
295
* and will be notified after the document is created. Observers registered
296
* after the document has been created will NOT be notified. When observers
297
* are notified, the subject will be the newly-created document, the topic
298
* will be "external-resource-document-created", and the data will be null.
299
* If document creation fails for some reason, observers will still be
300
* notified, with a null document pointer.
301
*/
302
class ExternalResourceLoad : public nsISupports {
303
public:
304
virtual ~ExternalResourceLoad() = default;
305
306
void AddObserver(nsIObserver* aObserver) {
307
MOZ_ASSERT(aObserver, "Must have observer");
308
mObservers.AppendElement(aObserver);
309
}
310
311
const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
312
313
protected:
314
AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
315
};
316
317
ExternalResourceMap();
318
319
/**
320
* Request an external resource document. This does exactly what
321
* Document::RequestExternalResource is documented to do.
322
*/
323
Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
324
nsINode* aRequestingNode,
325
Document* aDisplayDocument,
326
ExternalResourceLoad** aPendingLoad);
327
328
/**
329
* Enumerate the resource documents. See
330
* Document::EnumerateExternalResources.
331
*/
332
void EnumerateResources(SubDocEnumFunc aCallback, void* aData);
333
334
/**
335
* Traverse ourselves for cycle-collection
336
*/
337
void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
338
339
/**
340
* Shut ourselves down (used for cycle-collection unlink), as well
341
* as for document destruction.
342
*/
343
void Shutdown() {
344
mPendingLoads.Clear();
345
mMap.Clear();
346
mHaveShutDown = true;
347
}
348
349
bool HaveShutDown() const { return mHaveShutDown; }
350
351
// Needs to be public so we can traverse them sanely
352
struct ExternalResource {
353
~ExternalResource();
354
RefPtr<Document> mDocument;
355
nsCOMPtr<nsIContentViewer> mViewer;
356
nsCOMPtr<nsILoadGroup> mLoadGroup;
357
};
358
359
// Hide all our viewers
360
void HideViewers();
361
362
// Show all our viewers
363
void ShowViewers();
364
365
protected:
366
class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
367
~PendingLoad() {}
368
369
public:
370
explicit PendingLoad(Document* aDisplayDocument)
371
: mDisplayDocument(aDisplayDocument) {}
372
373
NS_DECL_ISUPPORTS
374
NS_DECL_NSISTREAMLISTENER
375
NS_DECL_NSIREQUESTOBSERVER
376
377
/**
378
* Start aURI loading. This will perform the necessary security checks and
379
* so forth.
380
*/
381
nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
382
nsINode* aRequestingNode);
383
/**
384
* Set up an nsIContentViewer based on aRequest. This is guaranteed to
385
* put null in *aViewer and *aLoadGroup on all failures.
386
*/
387
nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
388
nsILoadGroup** aLoadGroup);
389
390
private:
391
RefPtr<Document> mDisplayDocument;
392
nsCOMPtr<nsIStreamListener> mTargetListener;
393
nsCOMPtr<nsIURI> mURI;
394
};
395
friend class PendingLoad;
396
397
class LoadgroupCallbacks final : public nsIInterfaceRequestor {
398
~LoadgroupCallbacks() {}
399
400
public:
401
explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
402
: mCallbacks(aOtherCallbacks) {}
403
NS_DECL_ISUPPORTS
404
NS_DECL_NSIINTERFACEREQUESTOR
405
private:
406
// The only reason it's safe to hold a strong ref here without leaking is
407
// that the notificationCallbacks on a loadgroup aren't the docshell itself
408
// but a shim that holds a weak reference to the docshell.
409
nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
410
411
// Use shims for interfaces that docshell implements directly so that we
412
// don't hand out references to the docshell. The shims should all allow
413
// getInterface back on us, but other than that each one should only
414
// implement one interface.
415
416
// XXXbz I wish we could just derive the _allcaps thing from _i
417
#define DECL_SHIM(_i, _allcaps) \
418
class _i##Shim final : public nsIInterfaceRequestor, public _i { \
419
~_i##Shim() {} \
420
\
421
public: \
422
_i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
423
: mIfReq(aIfreq), mRealPtr(aRealPtr) { \
424
NS_ASSERTION(mIfReq, "Expected non-null here"); \
425
NS_ASSERTION(mRealPtr, "Expected non-null here"); \
426
} \
427
NS_DECL_ISUPPORTS \
428
NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
429
NS_FORWARD_##_allcaps(mRealPtr->) private \
430
: nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
431
nsCOMPtr<_i> mRealPtr; \
432
};
433
434
DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
435
DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
436
DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
437
DECL_SHIM(nsIApplicationCacheContainer, NSIAPPLICATIONCACHECONTAINER)
438
#undef DECL_SHIM
439
};
440
441
/**
442
* Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
443
* when this is called if the URI didn't result in an XML document. This
444
* function makes sure to remove the pending load for aURI, if any, from our
445
* hashtable, and to notify its observers, if any.
446
*/
447
nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
448
nsILoadGroup* aLoadGroup,
449
Document* aDisplayDocument);
450
451
nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
452
nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
453
bool mHaveShutDown;
454
};
455
456
//----------------------------------------------------------------------
457
458
// Document interface. This is implemented by all document objects in
459
// Gecko.
460
class Document : public nsINode,
461
public DocumentOrShadowRoot,
462
public nsSupportsWeakReference,
463
public nsIRadioGroupContainer,
464
public nsIScriptObjectPrincipal,
465
public nsIApplicationCacheContainer,
466
public nsStubMutationObserver,
467
public DispatcherTrait,
468
public SupportsWeakPtr<Document> {
469
protected:
470
explicit Document(const char* aContentType);
471
virtual ~Document();
472
473
Document(const Document&) = delete;
474
Document& operator=(const Document&) = delete;
475
476
public:
477
typedef dom::ExternalResourceMap::ExternalResourceLoad ExternalResourceLoad;
478
typedef net::ReferrerPolicy ReferrerPolicyEnum;
479
480
/**
481
* Called when XPCOM shutdown.
482
*/
483
static void Shutdown();
484
485
MOZ_DECLARE_WEAKREFERENCE_TYPENAME(Document)
486
487
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
488
489
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
490
491
NS_DECL_ADDSIZEOFEXCLUDINGTHIS
492
493
NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
494
nsINode)
495
496
#define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
497
do { \
498
NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(mObservers, nsIDocumentObserver, \
499
func_, params_); \
500
/* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
501
looks bogus. */ \
502
if (PresShell* presShell = GetObservingPresShell()) { \
503
presShell->func_ params_; \
504
} \
505
} while (0)
506
507
// nsIApplicationCacheContainer
508
NS_DECL_NSIAPPLICATIONCACHECONTAINER
509
510
// nsIRadioGroupContainer
511
NS_IMETHOD WalkRadioGroup(const nsAString& aName, nsIRadioVisitor* aVisitor,
512
bool aFlushContent) final {
513
return DocumentOrShadowRoot::WalkRadioGroup(aName, aVisitor, aFlushContent);
514
}
515
516
void SetCurrentRadioButton(const nsAString& aName,
517
HTMLInputElement* aRadio) final {
518
DocumentOrShadowRoot::SetCurrentRadioButton(aName, aRadio);
519
}
520
521
HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) final {
522
return DocumentOrShadowRoot::GetCurrentRadioButton(aName);
523
}
524
525
NS_IMETHOD
526
GetNextRadioButton(const nsAString& aName, const bool aPrevious,
527
HTMLInputElement* aFocusedRadio,
528
HTMLInputElement** aRadioOut) final {
529
return DocumentOrShadowRoot::GetNextRadioButton(aName, aPrevious,
530
aFocusedRadio, aRadioOut);
531
}
532
void AddToRadioGroup(const nsAString& aName, HTMLInputElement* aRadio) final {
533
DocumentOrShadowRoot::AddToRadioGroup(aName, aRadio);
534
}
535
void RemoveFromRadioGroup(const nsAString& aName,
536
HTMLInputElement* aRadio) final {
537
DocumentOrShadowRoot::RemoveFromRadioGroup(aName, aRadio);
538
}
539
uint32_t GetRequiredRadioCount(const nsAString& aName) const final {
540
return DocumentOrShadowRoot::GetRequiredRadioCount(aName);
541
}
542
void RadioRequiredWillChange(const nsAString& aName,
543
bool aRequiredAdded) final {
544
DocumentOrShadowRoot::RadioRequiredWillChange(aName, aRequiredAdded);
545
}
546
bool GetValueMissingState(const nsAString& aName) const final {
547
return DocumentOrShadowRoot::GetValueMissingState(aName);
548
}
549
void SetValueMissingState(const nsAString& aName, bool aValue) final {
550
return DocumentOrShadowRoot::SetValueMissingState(aName, aValue);
551
}
552
553
nsIPrincipal* EffectiveStoragePrincipal() const;
554
555
// nsIScriptObjectPrincipal
556
nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
557
558
nsIPrincipal* GetEffectiveStoragePrincipal() final {
559
return EffectiveStoragePrincipal();
560
}
561
562
// You should probably not be using this function, since it performs no
563
// checks to ensure that the intrinsic storage principal should really be
564
// used here. It is only designed to be used in very specific circumstances,
565
// such as when inheriting the document/storage principal.
566
nsIPrincipal* IntrinsicStoragePrincipal() const {
567
return mIntrinsicStoragePrincipal;
568
}
569
570
// EventTarget
571
void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
572
EventListenerManager* GetOrCreateListenerManager() override;
573
EventListenerManager* GetExistingListenerManager() const override;
574
575
// This helper class must be set when we dispatch beforeunload and unload
576
// events in order to avoid unterminate sync XHRs.
577
class MOZ_RAII PageUnloadingEventTimeStamp {
578
RefPtr<Document> mDocument;
579
bool mSet;
580
581
public:
582
explicit PageUnloadingEventTimeStamp(Document* aDocument)
583
: mDocument(aDocument), mSet(false) {
584
MOZ_ASSERT(aDocument);
585
if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
586
mDocument->SetPageUnloadingEventTimeStamp();
587
mSet = true;
588
}
589
}
590
591
~PageUnloadingEventTimeStamp() {
592
if (mSet) {
593
mDocument->CleanUnloadEventsTimeStamp();
594
}
595
}
596
};
597
598
/**
599
* Let the document know that we're starting to load data into it.
600
* @param aCommand The parser command. Must not be null.
601
* XXXbz It's odd to have that here.
602
* @param aChannel The channel the data will come from. The channel must be
603
* able to report its Content-Type.
604
* @param aLoadGroup The loadgroup this document should use from now on.
605
* Note that the document might not be the only thing using
606
* this loadgroup.
607
* @param aContainer The container this document is in. This may be null.
608
* XXXbz maybe we should make it more explicit (eg make the
609
* container an nsIWebNavigation or nsIDocShell or
610
* something)?
611
* @param [out] aDocListener the listener to pump data from the channel into.
612
* Generally this will be the parser this document
613
* sets up, or some sort of data-handler for media
614
* documents.
615
* @param aReset whether the document should call Reset() on itself. If this
616
* is false, the document will NOT set its principal to the
617
* channel's owner, will not clear any event listeners that are
618
* already set on it, etc.
619
* @param aSink The content sink to use for the data. If this is null and
620
* the document needs a content sink, it will create one based
621
* on whatever it knows about the data it's going to load.
622
* This MUST be null if the underlying document is an HTML
623
* document. Even in the XML case, please don't add new calls
624
* with non-null sink.
625
*
626
* Once this has been called, the document will return false for
627
* MayStartLayout() until SetMayStartLayout(true) is called on it. Making
628
* sure this happens is the responsibility of the caller of
629
* StartDocumentLoad().
630
*
631
* This function has an implementation, and does some setup, but does NOT set
632
* *aDocListener; this is the job of subclasses.
633
*/
634
virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
635
nsILoadGroup* aLoadGroup,
636
nsISupports* aContainer,
637
nsIStreamListener** aDocListener,
638
bool aReset,
639
nsIContentSink* aSink = nullptr) = 0;
640
void StopDocumentLoad();
641
642
virtual void SetSuppressParserErrorElement(bool aSuppress) {}
643
virtual bool SuppressParserErrorElement() { return false; }
644
645
virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
646
virtual bool SuppressParserErrorConsoleMessages() { return false; }
647
648
// nsINode
649
bool IsNodeOfType(uint32_t aFlags) const final;
650
nsresult InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
651
bool aNotify) override;
652
void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
653
nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
654
return NS_ERROR_NOT_IMPLEMENTED;
655
}
656
nsresult CloneDocHelper(Document* clone) const;
657
658
Document* GetLatestStaticClone() const { return mLatestStaticClone; }
659
660
/**
661
* Signal that the document title may have changed
662
* (see Document::GetTitle).
663
* @param aBoundTitleElement true if an HTML or SVG <title> element
664
* has just been bound to the document.
665
*/
666
virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
667
668
/**
669
* Return the URI for the document. May return null. If it ever stops being
670
* able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
671
* also never return null.
672
*
673
* The value returned corresponds to the "document's address" in
674
* HTML5. As such, it may change over the lifetime of the document, for
675
* instance as a result of the user navigating to a fragment identifier on
676
* the page, or as a result to a call to pushState() or replaceState().
677
*
679
*/
680
nsIURI* GetDocumentURI() const { return mDocumentURI; }
681
682
/**
683
* Return the original URI of the document. This is the same as the
684
* document's URI unless that has changed from its original value (for
685
* example, due to history.pushState() or replaceState() being invoked on the
686
* document).
687
*
688
* This method corresponds to the "creation URL" in HTML5 and, once set,
689
* doesn't change over the lifetime of the document.
690
*
692
*/
693
nsIURI* GetOriginalURI() const { return mOriginalURI; }
694
695
/**
696
* Return the base domain of the document. This has been computed using
697
* mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
698
* checks. When the URI of the document changes, this value is recomputed.
699
*/
700
nsCString GetBaseDomain() const { return mBaseDomain; }
701
702
/**
703
* Set the URI for the document. This also sets the document's original URI,
704
* if it's null.
705
*/
706
void SetDocumentURI(nsIURI* aURI);
707
708
/**
709
* Set the URI for the document loaded via XHR, when accessed from
710
* chrome privileged script.
711
*/
712
void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
713
714
/**
715
* Set the base URI for the document loaded via XHR, when accessed from
716
* chrome privileged script.
717
*/
718
void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
719
720
/**
721
* The CSP in general is stored in the ClientInfo, but we also cache
722
* the CSP on the document so subresources loaded within a document
723
* can query that cached CSP instead of having to deserialize the CSP
724
* from the Client.
725
*
726
* Please note that at the time of CSP parsing the Client is not
727
* available yet, hence we sync CSP of document and Client when the
728
* Client becomes available within nsGlobalWindowInner::EnsureClientSource().
729
*/
730
nsIContentSecurityPolicy* GetCsp() const;
731
void SetCsp(nsIContentSecurityPolicy* aCSP);
732
733
nsIContentSecurityPolicy* GetPreloadCsp() const;
734
void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
735
736
void GetCspJSON(nsString& aJSON);
737
738
/**
739
* Set referrer policy and upgrade-insecure-requests flags
740
*/
741
void ApplySettingsFromCSP(bool aSpeculative);
742
743
already_AddRefed<nsIParser> CreatorParserOrNull() {
744
nsCOMPtr<nsIParser> parser = mParser;
745
return parser.forget();
746
}
747
748
/**
749
* ReferrerInfo getter for Document.webidl.
750
*/
751
nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
752
753
nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
754
755
nsIReferrerInfo* GetPreloadReferrerInfo() const {
756
return mPreloadReferrerInfo;
757
}
758
/**
759
* Return the referrer policy of the document. Return "default" if there's no
760
* valid meta referrer tag found in the document.
761
* Referrer policy should be inherited from parent if the iframe is srcdoc
762
*/
763
ReferrerPolicyEnum GetReferrerPolicy() const;
764
765
/**
766
* GetReferrerPolicy() for Document.webidl.
767
*/
768
uint32_t ReferrerPolicy() const { return GetReferrerPolicy(); }
769
770
/**
771
* If true, this flag indicates that all mixed content subresource
772
* loads for this document (and also embeded browsing contexts) will
773
* be blocked.
774
*/
775
bool GetBlockAllMixedContent(bool aPreload) const {
776
if (aPreload) {
777
return mBlockAllMixedContentPreloads;
778
}
779
return mBlockAllMixedContent;
780
}
781
782
/**
783
* If true, this flag indicates that all subresource loads for this
784
* document need to be upgraded from http to https.
785
* This flag becomes true if the CSP of the document itself, or any
786
* of the document's ancestors up to the toplevel document makes use
787
* of the CSP directive 'upgrade-insecure-requests'.
788
*/
789
bool GetUpgradeInsecureRequests(bool aPreload) const {
790
if (aPreload) {
791
return mUpgradeInsecurePreloads;
792
}
793
return mUpgradeInsecureRequests;
794
}
795
796
void SetReferrerInfo(nsIReferrerInfo* aReferrerInfo) {
797
mReferrerInfo = aReferrerInfo;
798
}
799
800
/*
801
* Referrer policy from <meta name="referrer" content=`policy`>
802
* will have higher priority than referrer policy from Referrer-Policy
803
* header. So override the old ReferrerInfo if we get one from meta
804
*/
805
void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
806
bool aPreload) {
807
net::ReferrerPolicy policy =
808
mozilla::net::ReferrerPolicyFromString(aMetaReferrer);
809
// The empty string "" corresponds to no referrer policy, causing a fallback
810
// to a referrer policy defined elsewhere.
811
if (policy == mozilla::net::RP_Unset) {
812
return;
813
}
814
815
MOZ_ASSERT(mReferrerInfo);
816
MOZ_ASSERT(mPreloadReferrerInfo);
817
818
if (aPreload) {
819
mPreloadReferrerInfo =
820
static_cast<mozilla::dom::ReferrerInfo*>((mPreloadReferrerInfo).get())
821
->CloneWithNewPolicy(policy);
822
} else {
823
mReferrerInfo =
824
static_cast<mozilla::dom::ReferrerInfo*>((mReferrerInfo).get())
825
->CloneWithNewPolicy(policy);
826
}
827
}
828
829
/**
830
* Set the principals responsible for this document. Chances are, you do not
831
* want to be using this.
832
*/
833
void SetPrincipals(nsIPrincipal* aPrincipal, nsIPrincipal* aStoragePrincipal);
834
835
/**
836
* Get the list of ancestor principals for a document. This is the same as
837
* the ancestor list for the document's docshell the last time SetContainer()
838
* was called with a non-null argument. See the documentation for the
839
* corresponding getter in docshell for how this list is determined. We store
840
* a copy of the list, because we may lose the ability to reach our docshell
841
* before people stop asking us for this information.
842
*/
843
const nsTArray<nsCOMPtr<nsIPrincipal>>& AncestorPrincipals() const {
844
return mAncestorPrincipals;
845
}
846
847
/**
848
* Get the list of ancestor outerWindowIDs for a document that correspond to
849
* the ancestor principals (see above for more details).
850
*/
851
const nsTArray<uint64_t>& AncestorOuterWindowIDs() const {
852
return mAncestorOuterWindowIDs;
853
}
854
855
/**
856
* Return the LoadGroup for the document. May return null.
857
*/
858
already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
859
nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
860
return group.forget();
861
}
862
863
/**
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.
866
*
867
* XXXbz: This doesn't implement the bits for about:blank yet.
868
*/
869
nsIURI* GetFallbackBaseURI() const {
870
if (mIsSrcdocDocument && mParentDocument) {
871
return mParentDocument->GetDocBaseURI();
872
}
873
return mDocumentURI;
874
}
875
876
/**
877
* Return the referrer from document URI as defined in the Referrer Policy
878
* specification.
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
883
*/
884
885
nsIURI* GetDocumentURIAsReferrer() const {
886
if (mIsSrcdocDocument && mParentDocument) {
887
return mParentDocument->GetDocumentURIAsReferrer();
888
}
889
return mDocumentURI;
890
}
891
892
/**
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.
898
*/
899
nsIURI* GetDocBaseURI() const {
900
if (mDocumentBaseURI) {
901
return mDocumentBaseURI;
902
}
903
return GetFallbackBaseURI();
904
}
905
906
nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
907
908
void SetBaseURI(nsIURI* aURI);
909
910
/**
911
* Return the URL data which style system needs for resolving url value.
912
* This method attempts to use the cached object in mCachedURLData, but
913
* if the base URI, document URI, or principal has changed since last
914
* call to this function, or the function is called the first time for
915
* the document, a new one is created.
916
*/
917
URLExtraData* DefaultStyleAttrURLData();
918
919
/**
920
* Get/Set the base target of a link in a document.
921
*/
922
void GetBaseTarget(nsAString& aBaseTarget) const {
923
aBaseTarget = mBaseTarget;
924
}
925
926
void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
927
928
/**
929
* Return a standard name for the document's character set.
930
*/
931
NotNull<const Encoding*> GetDocumentCharacterSet() const {
932
return mCharacterSet;
933
}
934
935
/**
936
* Set the document's character encoding.
937
*/
938
void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
939
940
int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
941
942
// This method MUST be called before SetDocumentCharacterSet if
943
// you're planning to call both.
944
void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
945
mCharacterSetSource = aCharsetSource;
946
}
947
948
/**
949
* Get the Content-Type of this document.
950
*/
951
void GetContentType(nsAString& aContentType);
952
953
/**
954
* Set the Content-Type of this document.
955
*/
956
virtual void SetContentType(const nsAString& aContentType);
957
958
/**
959
* Return the language of this document.
960
*/
961
void GetContentLanguage(nsAString& aContentLanguage) const {
962
CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
963
}
964
965
// The states BidiEnabled and MathMLEnabled should persist across multiple
966
// views (screen, print) of the same document.
967
968
/**
969
* Check if the document contains bidi data.
970
* If so, we have to apply the Unicode Bidi Algorithm.
971
*/
972
bool GetBidiEnabled() const { return mBidiEnabled; }
973
974
/**
975
* Indicate the document contains bidi data.
976
* Currently, we cannot disable bidi, because once bidi is enabled,
977
* it affects a frame model irreversibly, and plays even though
978
* the document no longer contains bidi data.
979
*/
980
void SetBidiEnabled() { mBidiEnabled = true; }
981
982
void SetMathMLEnabled() { mMathMLEnabled = true; }
983
984
/**
985
* Ask this document whether it's the initial document in its window.
986
*/
987
bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
988
989
/**
990
* Tell this document that it's the initial document in its window. See
991
* comments on mIsInitialDocumentInWindow for when this should be called.
992
*/
993
void SetIsInitialDocument(bool aIsInitialDocument);
994
995
void SetLoadedAsData(bool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
996
void SetLoadedAsInteractiveData(bool aLoadedAsInteractiveData) {
997
mLoadedAsInteractiveData = aLoadedAsInteractiveData;
998
}
999
1000
/**
1001
* Normally we assert if a runnable labeled with one DocGroup touches data
1002
* from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1003
* means that we can touch that document from any DocGroup without asserting.
1004
*/
1005
void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1006
1007
/**
1008
* Get the bidi options for this document.
1009
* @see nsBidiUtils.h
1010
*/
1011
uint32_t GetBidiOptions() const { return mBidiOptions; }
1012
1013
/**
1014
* Set the bidi options for this document. This just sets the bits;
1015
* callers are expected to take action as needed if they want this
1016
* change to actually change anything immediately.
1017
* @see nsBidiUtils.h
1018
*/
1019
void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1020
1021
/**
1022
* Get the has mixed active content loaded flag for this document.
1023
*/
1024
bool GetHasMixedActiveContentLoaded() { return mHasMixedActiveContentLoaded; }
1025
1026
/**
1027
* Set the has mixed active content loaded flag for this document.
1028
*/
1029
void SetHasMixedActiveContentLoaded(bool aHasMixedActiveContentLoaded) {
1030
mHasMixedActiveContentLoaded = aHasMixedActiveContentLoaded;
1031
}
1032
1033
/**
1034
* Get mixed active content blocked flag for this document.
1035
*/
1036
bool GetHasMixedActiveContentBlocked() {
1037
return mHasMixedActiveContentBlocked;
1038
}
1039
1040
/**
1041
* Set the mixed active content blocked flag for this document.
1042
*/
1043
void SetHasMixedActiveContentBlocked(bool aHasMixedActiveContentBlocked) {
1044
mHasMixedActiveContentBlocked = aHasMixedActiveContentBlocked;
1045
}
1046
1047
/**
1048
* Get the has mixed display content loaded flag for this document.
1049
*/
1050
bool GetHasMixedDisplayContentLoaded() {
1051
return mHasMixedDisplayContentLoaded;
1052
}
1053
1054
/**
1055
* Set the has mixed display content loaded flag for this document.
1056
*/
1057
void SetHasMixedDisplayContentLoaded(bool aHasMixedDisplayContentLoaded) {
1058
mHasMixedDisplayContentLoaded = aHasMixedDisplayContentLoaded;
1059
}
1060
1061
/**
1062
* Get mixed display content blocked flag for this document.
1063
*/
1064
bool GetHasMixedDisplayContentBlocked() {
1065
return mHasMixedDisplayContentBlocked;
1066
}
1067
1068
/**
1069
* Set the mixed display content blocked flag for this document.
1070
*/
1071
void SetHasMixedDisplayContentBlocked(bool aHasMixedDisplayContentBlocked) {
1072
mHasMixedDisplayContentBlocked = aHasMixedDisplayContentBlocked;
1073
}
1074
1075
/**
1076
* Set the mixed content object subrequest flag for this document.
1077
*/
1078
void SetHasMixedContentObjectSubrequest(
1079
bool aHasMixedContentObjectSubrequest) {
1080
mHasMixedContentObjectSubrequest = aHasMixedContentObjectSubrequest;
1081
}
1082
1083
/**
1084
* Set CSP flag for this document.
1085
*/
1086
void SetHasCSP(bool aHasCSP) { mHasCSP = aHasCSP; }
1087
1088
/**
1089
* Set unsafe-inline CSP flag for this document.
1090
*/
1091
void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP) {
1092
mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
1093
}
1094
1095
/**
1096
* Set unsafe-eval CSP flag for this document.
1097
*/
1098
void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP) {
1099
mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
1100
}
1101
1102
/**
1103
* Get the content blocking log.
1104
*/
1105
ContentBlockingLog* GetContentBlockingLog() { return &mContentBlockingLog; }
1106
1107
/**
1108
* Get tracking content blocked flag for this document.
1109
*/
1110
bool GetHasTrackingContentBlocked() {
1111
return mContentBlockingLog.HasBlockedAnyOfType(
1112
nsIWebProgressListener::STATE_BLOCKED_TRACKING_CONTENT);
1113
}
1114
1115
/**
1116
* Get fingerprinting content blocked flag for this document.
1117
*/
1118
bool GetHasFingerprintingContentBlocked() {
1119
return mContentBlockingLog.HasBlockedAnyOfType(
1120
nsIWebProgressListener::STATE_BLOCKED_FINGERPRINTING_CONTENT);
1121
}
1122
1123
/**
1124
* Get cryptomining content blocked flag for this document.
1125
*/
1126
bool GetHasCryptominingContentBlocked() {
1127
return mContentBlockingLog.HasBlockedAnyOfType(
1128
nsIWebProgressListener::STATE_BLOCKED_CRYPTOMINING_CONTENT);
1129
}
1130
1131
/**
1132
* Get socialtracking content blocked flag for this document.
1133
*/
1134
bool GetHasSocialTrackingContentBlocked() {
1135
return mContentBlockingLog.HasBlockedAnyOfType(
1136
nsIWebProgressListener::STATE_BLOCKED_SOCIALTRACKING_CONTENT);
1137
}
1138
1139
/**
1140
* Get all cookies blocked flag for this document.
1141
*/
1142
bool GetHasAllCookiesBlocked() {
1143
return mContentBlockingLog.HasBlockedAnyOfType(
1144
nsIWebProgressListener::STATE_COOKIES_BLOCKED_ALL);
1145
}
1146
1147
/**
1148
* Get tracking cookies blocked flag for this document.
1149
*/
1150
bool GetHasTrackingCookiesBlocked() {
1151
return mContentBlockingLog.HasBlockedAnyOfType(
1152
nsIWebProgressListener::STATE_COOKIES_BLOCKED_TRACKER);
1153
}
1154
1155
/**
1156
* Get third-party cookies blocked flag for this document.
1157
*/
1158
bool GetHasForeignCookiesBlocked() {
1159
return mContentBlockingLog.HasBlockedAnyOfType(
1160
nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN);
1161
}
1162
1163
/**
1164
* Get cookies blocked by site permission flag for this document.
1165
*/
1166
bool GetHasCookiesBlockedByPermission() {
1167
return mContentBlockingLog.HasBlockedAnyOfType(
1168
nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION);
1169
}
1170
1171
/**
1172
* Set the tracking content blocked flag for this document.
1173
*/
1174
void SetHasTrackingContentBlocked(bool aHasTrackingContentBlocked,
1175
const nsACString& aOriginBlocked) {
1176
RecordContentBlockingLog(
1177
aOriginBlocked, nsIWebProgressListener::STATE_BLOCKED_TRACKING_CONTENT,
1178
aHasTrackingContentBlocked);
1179
}
1180
1181
/**
1182
* Set the fingerprinting content blocked flag for this document.
1183
*/
1184
void SetHasFingerprintingContentBlocked(bool aHasFingerprintingContentBlocked,
1185
const nsACString& aOriginBlocked) {
1186
RecordContentBlockingLog(
1187
aOriginBlocked,
1188
nsIWebProgressListener::STATE_BLOCKED_FINGERPRINTING_CONTENT,
1189
aHasFingerprintingContentBlocked);
1190
}
1191
1192
/**
1193
* Set the cryptomining content blocked flag for this document.
1194
*/
1195
void SetHasCryptominingContentBlocked(bool aHasCryptominingContentBlocked,
1196
const nsACString& aOriginBlocked) {
1197
RecordContentBlockingLog(
1198
aOriginBlocked,
1199
nsIWebProgressListener::STATE_BLOCKED_CRYPTOMINING_CONTENT,
1200
aHasCryptominingContentBlocked);
1201
}
1202
1203
/**
1204
* Set the socialtracking content blocked flag for this document.
1205
*/
1206
void SetHasSocialTrackingContentBlocked(bool aHasSocialTrackingContentBlocked,
1207
const nsACString& aOriginBlocked) {
1208
RecordContentBlockingLog(
1209
aOriginBlocked,
1210
nsIWebProgressListener::STATE_BLOCKED_SOCIALTRACKING_CONTENT,
1211
aHasSocialTrackingContentBlocked);
1212
}
1213
1214
/**
1215
* Set the all cookies blocked flag for this document.
1216
*/
1217
void SetHasAllCookiesBlocked(bool aHasAllCookiesBlocked,
1218
const nsACString& aOriginBlocked) {
1219
RecordContentBlockingLog(aOriginBlocked,
1220
nsIWebProgressListener::STATE_COOKIES_BLOCKED_ALL,
1221
aHasAllCookiesBlocked);
1222
}
1223
1224
/**
1225
* Set the tracking cookies blocked flag for this document.
1226
*/
1227
void SetHasTrackingCookiesBlocked(
1228
bool aHasTrackingCookiesBlocked, const nsACString& aOriginBlocked,
1229
const Maybe<AntiTrackingCommon::StorageAccessGrantedReason>& aReason,
1230
const nsTArray<nsCString>& aTrackingFullHashes) {
1231
RecordContentBlockingLog(
1232
aOriginBlocked, nsIWebProgressListener::STATE_COOKIES_BLOCKED_TRACKER,
1233
aHasTrackingCookiesBlocked, aReason, aTrackingFullHashes);
1234
}
1235
1236
/**
1237
* Set the third-party cookies blocked flag for this document.
1238
*/
1239
void SetHasForeignCookiesBlocked(bool aHasForeignCookiesBlocked,
1240
const nsACString& aOriginBlocked) {
1241
RecordContentBlockingLog(
1242
aOriginBlocked, nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN,
1243
aHasForeignCookiesBlocked);
1244
}
1245
1246
/**
1247
* Set the cookies blocked by site permission flag for this document.
1248
*/
1249
void SetHasCookiesBlockedByPermission(bool aHasCookiesBlockedByPermission,
1250
const nsACString& aOriginBlocked) {
1251
RecordContentBlockingLog(
1252
aOriginBlocked,
1253
nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION,
1254
aHasCookiesBlockedByPermission);
1255
}
1256
1257
/**
1258
* Set the cookies loaded flag for this document.
1259
*/
1260
void SetHasCookiesLoaded(bool aHasCookiesLoaded,
1261
const nsACString& aOriginLoaded) {
1262
RecordContentBlockingLog(aOriginLoaded,
1263
nsIWebProgressListener::STATE_COOKIES_LOADED,
1264
aHasCookiesLoaded);
1265
}
1266
1267
/**
1268
* Get cookies loaded flag for this document.
1269
*/
1270
bool GetHasCookiesLoaded() {
1271
return mContentBlockingLog.HasBlockedAnyOfType(
1272
nsIWebProgressListener::STATE_COOKIES_LOADED);
1273
}
1274
1275
/**
1276
* Get tracking content loaded flag for this document.
1277
*/
1278
bool GetHasTrackingContentLoaded() {
1279
return mContentBlockingLog.HasBlockedAnyOfType(
1280
nsIWebProgressListener::STATE_LOADED_TRACKING_CONTENT);
1281
}
1282
1283
/**
1284
* Set the tracking content loaded flag for this document.
1285
*/
1286
void SetHasTrackingContentLoaded(bool aHasTrackingContentLoaded,
1287
const nsACString& aOriginBlocked) {
1288
RecordContentBlockingLog(
1289
aOriginBlocked, nsIWebProgressListener::STATE_LOADED_TRACKING_CONTENT,
1290
aHasTrackingContentLoaded);
1291
}
1292
1293
/**
1294
* Get fingerprinting content loaded flag for this document.
1295
*/
1296
bool GetHasFingerprintingContentLoaded() {
1297
return mContentBlockingLog.HasBlockedAnyOfType(
1298
nsIWebProgressListener::STATE_LOADED_FINGERPRINTING_CONTENT);
1299
}
1300
1301
/**
1302
* Set the fingerprinting content loaded flag for this document.
1303
*/
1304
void SetHasFingerprintingContentLoaded(bool aHasFingerprintingContentLoaded,
1305
const nsACString& aOriginBlocked) {
1306
RecordContentBlockingLog(
1307
aOriginBlocked,
1308
nsIWebProgressListener::STATE_LOADED_FINGERPRINTING_CONTENT,
1309
aHasFingerprintingContentLoaded);
1310
}
1311
1312
/**
1313
* Get cryptomining content loaded flag for this document.
1314
*/
1315
bool GetHasCryptominingContentLoaded() {
1316
return mContentBlockingLog.HasBlockedAnyOfType(
1317
nsIWebProgressListener::STATE_LOADED_CRYPTOMINING_CONTENT);
1318
}
1319
1320
/**
1321
* Set the cryptomining content loaded flag for this document.
1322
*/
1323
void SetHasCryptominingContentLoaded(bool aHasCryptominingContentLoaded,
1324
const nsACString& aOriginBlocked) {
1325
RecordContentBlockingLog(
1326
aOriginBlocked,
1327
nsIWebProgressListener::STATE_LOADED_CRYPTOMINING_CONTENT,
1328
aHasCryptominingContentLoaded);
1329
}
1330
1331
/**
1332
* Get socialtracking content loaded flag for this document.
1333
*/
1334
bool GetHasSocialTrackingContentLoaded() {
1335
return mContentBlockingLog.HasBlockedAnyOfType(
1336
nsIWebProgressListener::STATE_LOADED_SOCIALTRACKING_CONTENT);
1337
}
1338
1339
/**
1340
* Set the socialtracking content loaded flag for this document.
1341
*/
1342
void SetHasSocialTrackingContentLoaded(bool aHasSocialTrackingContentLoaded,
1343
const nsACString& aOriginBlocked) {
1344
RecordContentBlockingLog(
1345
aOriginBlocked,
1346
nsIWebProgressListener::STATE_LOADED_SOCIALTRACKING_CONTENT,
1347
aHasSocialTrackingContentLoaded);
1348
}
1349
1350
/**
1351
* Get the sandbox flags for this document.
1352
* @see nsSandboxFlags.h for the possible flags
1353
*/
1354
uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1355
1356
/**
1357
* Get string representation of sandbox flags (null if no flags are set)
1358
*/
1359
void GetSandboxFlagsAsString(nsAString& aFlags);
1360
1361
/**
1362
* Set the sandbox flags for this document.
1363
* @see nsSandboxFlags.h for the possible flags
1364
*/
1365
void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1366
1367
/**
1368
* Called when the document was decoded as UTF-8 and decoder encountered no
1369
* errors.
1370
*/
1371
void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1372
1373
/**
1374
* Called to disable client access to cookies through the document.cookie API
1375
* from user JavaScript code.
1376
*/
1377
void DisableCookieAccess() { mDisableCookieAccess = true; }
1378
1379
void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1380
bool LinkHandlingEnabled() { return mLinksEnabled; }
1381
1382
/**
1383
* Set compatibility mode for this document
1384
*/
1385
void SetCompatibilityMode(nsCompatibility aMode);
1386
1387
/**
1388
* Called to disable client access to document.write() API from user
1389
* JavaScript code.
1390
*/
1391
void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1392
1393
/**
1394
* Whether a document.write() call is in progress.
1395
*/
1396
bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1397
1398
/**
1399
* Access HTTP header data (this may also get set from other
1400
* sources, like HTML META tags).
1401
*/
1402
void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1403
void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1404
1405
/**
1406
* Create a new presentation shell that will use aContext for its
1407
* presentation context (presentation contexts <b>must not</b> be
1408
* shared among multiple presentation shells). The caller of this
1409
* method is responsible for calling BeginObservingDocument() on the
1410
* presshell if the presshell should observe document mutations.
1411
*/
1412
already_AddRefed<PresShell> CreatePresShell(nsPresContext* aContext,
1413
nsViewManager* aViewManager);
1414
void DeletePresShell();
1415
1416
PresShell* GetPresShell() const {
1417
return GetBFCacheEntry() ? nullptr : mPresShell;
1418
}
1419
1420
inline PresShell* GetObservingPresShell() const;
1421
1422
// Return whether the presshell for this document is safe to flush.
1423
bool IsSafeToFlush() const;
1424
1425
inline nsPresContext* GetPresContext() const;
1426
1427
bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1428
1429
// Instead using this method, what you probably want is
1430
// RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1431
void DisallowBFCaching() {
1432
NS_ASSERTION(!mBFCacheEntry, "We're already in the bfcache!");
1433
mBFCacheDisallowed = true;
1434
}
1435
1436
bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1437
1438
// Accepts null to clear the BFCache entry too.
1439
void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1440
1441
nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1442
1443
/**
1444
* Return the parent document of this document. Will return null
1445
* unless this document is within a compound document and has a
1446
* parent. Note that this parent chain may cross chrome boundaries.
1447
*/
1448
Document* GetParentDocument() const { return mParentDocument; }
1449
1450
/**
1451
* Set the parent document of this document.
1452
*/
1453
void SetParentDocument(Document* aParent) {
1454
mParentDocument = aParent;
1455
if (aParent) {
1456
mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1457
}
1458
}
1459
1460
/**
1461
* Are plugins allowed in this document ?
1462
*/
1463
bool GetAllowPlugins();
1464
1465
/**
1466
* Set the sub document for aContent to aSubDoc.
1467
*/
1468
nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1469
1470
/**
1471
* Get the sub document for aContent
1472
*/
1473
Document* GetSubDocumentFor(nsIContent* aContent) const;
1474
1475
/**
1476
* Find the content node for which aDocument is a sub document.
1477
*/
1478
Element* FindContentForSubDocument(Document* aDocument) const;
1479
1480
/**
1481
* Return the doctype for this document.
1482
*/
1483
DocumentType* GetDoctype() const;
1484
1485
/**
1486
* Return the root element for this document.
1487
*/
1488
Element* GetRootElement() const;
1489
1490
Selection* GetSelection(ErrorResult& aRv);
1491
1492
already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1493
already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1494
1495
/**
1496
* Gets the event target to dispatch key events to if there is no focused
1497
* content in the document.
1498
*/
1499
virtual Element* GetUnfocusedKeyEventTarget();
1500
1501
/**
1502
* Retrieve information about the viewport as a data structure.
1503
* This will return information in the viewport META data section
1504
* of the document. This can be used in lieu of ProcessViewportInfo(),
1505
* which places the viewport information in the document header instead
1506
* of returning it directly.
1507
*
1508
* @param aDisplaySize size of the on-screen display area for this
1509
* document, in device pixels.
1510
*
1511
* NOTE: If the site is optimized for mobile (via the doctype), this
1512
* will return viewport information that specifies default information.
1513
*/
1514
nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1515
1516
void UpdateForScrollAnchorAdjustment(nscoord aLength);
1517
1518
/**
1519
* True iff this doc will ignore manual character encoding overrides.
1520
*/
1521
virtual bool WillIgnoreCharsetOverride() { return true; }
1522
1523
/**
1524
* Return whether the document was created by a srcdoc iframe.
1525
*/
1526
bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1527
1528
/**
1529
* Sets whether the document was created by a srcdoc iframe.
1530
*/
1531
void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1532
mIsSrcdocDocument = aIsSrcdocDocument;
1533
}
1534
1535
/*
1536
* Gets the srcdoc string from within the channel (assuming both exist).
1537
* Returns a void string if this isn't a srcdoc document or if
1538
* the channel has not been set.
1539
*/
1540
nsresult GetSrcdocData(nsAString& aSrcdocData);
1541
1542
already_AddRefed<AnonymousContent> InsertAnonymousContent(
1543
Element& aElement, ErrorResult& aError);
1544
void RemoveAnonymousContent(AnonymousContent& aContent, ErrorResult& aError);
1545
/**
1546
* If aNode is a descendant of anonymous content inserted by
1547
* InsertAnonymousContent, this method returns the root element of the
1548
* inserted anonymous content (in other words, the clone of the aElement
1549
* that was passed to InsertAnonymousContent).
1550
*/
1551
Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1552
nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1553
return mAnonymousContents;
1554
}
1555
1556
TimeStamp GetPageUnloadingEventTimeStamp() const {
1557
if (!mParentDocument) {
1558
return mPageUnloadingEventTimeStamp;
1559
}
1560
1561
TimeStamp parentTimeStamp(
1562
mParentDocument->GetPageUnloadingEventTimeStamp());
1563
if (parentTimeStamp.IsNull()) {
1564
return mPageUnloadingEventTimeStamp;
1565
}
1566
1567
if (!mPageUnloadingEventTimeStamp ||
1568
parentTimeStamp < mPageUnloadingEventTimeStamp) {
1569
return parentTimeStamp;
1570
}
1571
1572
return mPageUnloadingEventTimeStamp;
1573
}
1574
1575
void NotifyLayerManagerRecreated();
1576
1577
/**
1578
* Add an SVG element to the list of elements that need
1579
* their mapped attributes resolved to a Servo declaration block.
1580
*
1581
* These are weak pointers, please manually unschedule them when an element
1582
* is removed.
1583
*/
1584
void ScheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1585
mLazySVGPresElements.PutEntry(aSVG);
1586
}
1587
1588
// Unschedule an element scheduled by ScheduleFrameRequestCallback (e.g. for
1589
// when it is destroyed)
1590
void UnscheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1591
mLazySVGPresElements.RemoveEntry(aSVG);
1592
}
1593
1594
// Resolve all SVG pres attrs scheduled in ScheduleSVGForPresAttrEvaluation
1595
void ResolveScheduledSVGPresAttrs();
1596
1597
Maybe<ClientInfo> GetClientInfo() const;
1598
Maybe<ClientState> GetClientState() const;
1599
Maybe<ServiceWorkerDescriptor> GetController() const;
1600
1601
// Returns the size of the mBlockedNodesByClassifier array.
1602
//
1603
// This array contains nodes that have been blocked to prevent user tracking,
1604
// fingerprinting, cryptomining, etc. They most likely have had their
1605
// nsIChannel canceled by the URL classifier (Safebrowsing).
1606
//
1607
// A script can subsequently use GetBlockedNodesByClassifier()
1608
// to get a list of references to these nodes.
1609
//
1610
// Note:
1611
// This expresses how many tracking nodes have been blocked for this document
1612
// since its beginning, not how many of them are still around in the DOM tree.
1613
// Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1614
// array but they are not removed when those nodes are removed from the tree
1615
// or even garbage collected.
1616
long BlockedNodeByClassifierCount() const {
1617
return mBlockedNodesByClassifier.Length();
1618
}
1619
1620
//
1621
// Returns strong references to mBlockedNodesByClassifier. (Document.h)
1622
//
1623
// This array contains nodes that have been blocked to prevent
1624
// user tracking. They most likely have had their nsIChannel
1625
// canceled by the URL classifier (Safebrowsing).
1626
//
1627
already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1628
1629
// Helper method that returns true if the document has storage-access sandbox
1630
// flag.
1631
bool StorageAccessSandboxed() const;
1632
1633
// Returns the cookie settings for this and sub contexts.
1634
nsICookieSettings* CookieSettings();
1635
1636
// Increments the document generation.
1637
inline void Changed() { ++mGeneration; }
1638
1639
// Returns the current generation.
1640
inline int32_t GetGeneration() const { return mGeneration; }
1641
1642
// Adds cached sizes values to aSizes if there's any
1643
// cached value and if the document generation hasn't
1644
// changed since the cache was created.
1645
// Returns true if sizes were added.
1646
bool GetCachedSizes(nsTabSizes* aSizes);
1647
1648
// Sets the cache sizes for the current generation.
1649
void SetCachedSizes(nsTabSizes* aSizes);
1650
1651
/**
1652
* Should be called when an element's editable changes as a result of
1653
* changing its contentEditable attribute/property.
1654
*
1655
* @param aElement the element for which the contentEditable
1656
* attribute/property was changed
1657
* @param aChange +1 if the contentEditable attribute/property was changed to
1658
* true, -1 if it was changed to false
1659
*/
1660
nsresult ChangeContentEditableCount(nsIContent* aElement, int32_t aChange);
1661
void DeferredContentEditableCountChange(nsIContent* aElement);
1662
1663
enum class EditingState : int8_t {
1664
eTearingDown = -2,
1665
eSettingUp = -1,
1666
eOff = 0,
1667
eDesignMode,
1668
eContentEditable
1669
};
1670
1671
/**
1672
* Returns the editing state of the document (not editable, contentEditable or
1673
* designMode).
1674
*/
1675
EditingState GetEditingState() const { return mEditingState; }
1676
1677
/**
1678
* Returns whether the document is editable.
1679
*/
1680
bool IsEditingOn() const {
1681
return GetEditingState() == EditingState::eDesignMode ||
1682
GetEditingState() == EditingState::eContentEditable;
1683
}
1684
1685
class MOZ_STACK_CLASS nsAutoEditingState {
1686
public:
1687
nsAutoEditingState(Document* aDoc, EditingState aState)
1688
: mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1689
aDoc->mEditingState = aState;
1690
}
1691
~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1692
1693
private:
1694
RefPtr<Document> mDoc;
1695
EditingState mSavedState;
1696
};
1697
friend class nsAutoEditingState;
1698
1699
/**
1700
* Set the editing state of the document. Don't use this if you want
1701
* to enable/disable editing, call EditingStateChanged() or
1702
* SetDesignMode().
1703
*/
1704
nsresult SetEditingState(EditingState aState);
1705
1706
/**
1707
* Called when this Document's editor is destroyed.
1708
*/
1709
void TearingDownEditor();
1710
1711
void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1712
1713
// Gets the next form number.
1714
//
1715
// Used by nsContentUtils::GenerateStateKey to get a unique number for each
1716
// parser inserted form element.
1717
int32_t GetNextFormNumber() { return mNextFormNumber++; }
1718
1719
// Gets the next form control number.
1720
//
1721
// Used by nsContentUtils::GenerateStateKey to get a unique number for each
1722
// parser inserted form control element.
1723
int32_t GetNextControlNumber() { return mNextControlNumber++; }
1724
1725
protected:
1726
friend class nsUnblockOnloadEvent;
1727
1728
nsresult InitCSP(nsIChannel* aChannel);
1729
1730
nsresult InitFeaturePolicy(nsIChannel* aChannel);
1731
1732
nsresult InitReferrerInfo(nsIChannel* aChannel);
1733
1734
void PostUnblockOnloadEvent();
1735
1736
void DoUnblockOnload();
1737
1738
void MaybeEndOutermostXBLUpdate();
1739
1740
void RetrieveRelevantHeaders(nsIChannel* aChannel);
1741
1742
void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1743
NotNull<const Encoding*>& aEncoding,
1744
nsHtml5TreeOpExecutor* aExecutor);
1745
1746
void DispatchContentLoadedEvents();
1747
1748
void DispatchPageTransition(EventTarget* aDispatchTarget,
1749
const nsAString& aType, bool aPersisted,
1750
bool aOnlySystemGroup = false);
1751
1752
// Call this before the document does something that will unbind all content.
1753
// That will stop us from doing a lot of work as each element is removed.
1754
void DestroyElementMaps();
1755
1756
Element* GetRootElementInternal() const;
1757
void DoNotifyPossibleTitleChange();
1758
1759
void SetPageUnloadingEventTimeStamp() {
1760
MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1761
mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1762
}
1763
1764
void CleanUnloadEventsTimeStamp() {
1765
MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1766
mPageUnloadingEventTimeStamp = TimeStamp();
1767
}
1768
1769
/**
1770
* Clears any Servo element data stored on Elements in the document.
1771
*/
1772
void ClearStaleServoData();
1773
1774
/**
1775
* Returns the top window root from the outer window.
1776
*/
1777
already_AddRefed<nsPIWindowRoot> GetWindowRoot();
1778
1779
/**
1780
* Do the tree-disconnection that ResetToURI and document.open need to do.
1781
*/
1782
void DisconnectNodeTree();
1783
1784
/**
1785
* Like IsEditingOn(), but will flush as needed first.
1786
*/
1787
bool IsEditingOnAfterFlush();
1788
1789
/**
1790
* MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1791
* "CheckKeyPressEventModel" event to check whether we should dispatch
1792
* keypress events in confluent model or split model. This should be
1793
* called only when mEditingState is changed to eDesignMode or
1794
* eConentEditable at first time.
1795
*/
1796
void MaybeDispatchCheckKeyPressEventModelEvent();
1797
1798
/* Midas implementation */
1799
nsCommandManager* GetMidasCommandManager();
1800
1801
nsresult TurnEditingOff();
1802
1803
// MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1804
// of places, and I'm pretty sure the exact ExecCommand call it
1805
// makes cannot actually run script.
1806
MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1807
1808
void MaybeEditingStateChanged();
1809
1810
private:
1811
class SelectorCacheKey {
1812
public:
1813
explicit SelectorCacheKey(const nsAString& aString) : mKey(aString) {
1814
MOZ_COUNT_CTOR(SelectorCacheKey);
1815
}
1816
1817
nsString mKey;
1818
nsExpirationState mState;
1819
1820
nsExpirationState* GetExpirationState() { return &mState; }
1821
1822
~SelectorCacheKey() { MOZ_COUNT_DTOR(SelectorCacheKey); }
1823
};
1824
1825
class SelectorCacheKeyDeleter;
1826
1827
public:
1828
class SelectorCache final : public nsExpirationTracker<SelectorCacheKey, 4> {
1829
public:
1830
using SelectorList = UniquePtr<RawServoSelectorList>;
1831
1832
explicit SelectorCache(nsIEventTarget* aEventTarget);
1833
1834
void CacheList(const nsAString& aSelector, SelectorList aSelectorList) {
1835
MOZ_ASSERT(NS_IsMainThread());
1836
SelectorCacheKey* key = new SelectorCacheKey(aSelector);
1837
mTable.Put(key->mKey, std::move(aSelectorList));
1838
AddObject(key);
1839
}
1840
1841
void NotifyExpired(SelectorCacheKey* aSelector) final;
1842
1843
// We do not call MarkUsed because it would just slow down lookups and
1844
// because we're OK expiring things after a few seconds even if they're
1845
// being used. Returns whether we actually had an entry for aSelector.
1846
//
1847
// If we have an entry and the selector list returned has a null
1848
// RawServoSelectorList*, that indicates that aSelector has already been
1849
// parsed and is not a syntactically valid selector.
1850
SelectorList* GetList(const nsAString& aSelector) {
1851
return mTable.GetValue(aSelector);
1852
}
1853
1854
~SelectorCache();
1855
1856
private:
1857
nsDataHashtable<nsStringHashKey, SelectorList> mTable;
1858
};
1859
1860
SelectorCache& GetSelectorCache() {
1861
if (!mSelectorCache) {
1862
mSelectorCache =
1863
MakeUnique<SelectorCache>(EventTargetFor(TaskCategory::Other));
1864
}
1865
return *mSelectorCache;
1866
}
1867
// Get the root <html> element, or return null if there isn't one (e.g.
1868
// if the root isn't <html>)
1869
Element* GetHtmlElement() const;
1870
// Returns the first child of GetHtmlContent which has the given tag,
1871
// or nullptr if that doesn't exist.
1872
Element* GetHtmlChildElement(nsAtom* aTag);
1873
// Get the canonical <body> element, or return null if there isn't one (e.g.
1874
// if the root isn't <html> or if the <body> isn't there)
1875
HTMLBodyElement* GetBodyElement();
1876
// Get the canonical <head> element, or return null if there isn't one (e.g.
1877
// if the root isn't <html> or if the <head> isn't there)
1878
Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1879
// Get the "body" in the sense of document.body: The first <body> or
1880
// <frameset> that's a child of a root <html>
1881
nsGenericHTMLElement* GetBody();
1882
// Set the "body" in the sense of document.body.
1883
void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1884
// Get the "head" element in the sense of document.head.
1885
HTMLSharedElement* GetHead();
1886
1887
ServoStyleSet* StyleSetForPresShellOrMediaQueryEvaluation() const {
1888
return mStyleSet.get();
1889
}
1890
1891
// ShadowRoot has APIs that can change styles. This notifies the shell that
1892
// stlyes applicable in the shadow tree have potentially changed.