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