Bug 1852740: add tests for the `fetchpriority` attribute in Link headers. r=necko...
[gecko.git] / dom / base / nsContentUtils.h
blob530f5cb346e9a4a2d72c8b3fff50bc46c4d0a817
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* A namespace class for static content utilities. */
9 #ifndef nsContentUtils_h___
10 #define nsContentUtils_h___
12 #if defined(XP_WIN)
13 # include <float.h>
14 #endif
16 #if defined(SOLARIS)
17 # include <ieeefp.h>
18 #endif
20 #include <cstddef>
21 #include <cstdint>
22 #include <functional>
23 #include <tuple>
24 #include <utility>
25 #include "ErrorList.h"
26 #include "Units.h"
27 #include "js/Id.h"
28 #include "js/RegExpFlags.h"
29 #include "js/RootingAPI.h"
30 #include "mozilla/AlreadyAddRefed.h"
31 #include "mozilla/Assertions.h"
32 #include "mozilla/Attributes.h"
33 #include "mozilla/BasicEvents.h"
34 #include "mozilla/CORSMode.h"
35 #include "mozilla/CallState.h"
36 #include "mozilla/Maybe.h"
37 #include "mozilla/RefPtr.h"
38 #include "mozilla/TimeStamp.h"
39 #include "mozilla/UniquePtr.h"
40 #include "mozilla/dom/BindingDeclarations.h"
41 #include "mozilla/dom/FromParser.h"
42 #include "mozilla/fallible.h"
43 #include "mozilla/gfx/Point.h"
44 #include "nsCOMPtr.h"
45 #include "nsIContentPolicy.h"
46 #include "nsINode.h"
47 #include "nsIScriptError.h"
48 #include "nsIThread.h"
49 #include "nsLiteralString.h"
50 #include "nsMargin.h"
51 #include "nsPIDOMWindow.h"
52 #include "nsRFPService.h"
53 #include "nsStringFwd.h"
54 #include "nsTArray.h"
55 #include "nsTLiteralString.h"
56 #include "prtime.h"
58 #if defined(XP_WIN)
59 // Undefine LoadImage to prevent naming conflict with Windows.
60 # undef LoadImage
61 #endif
63 class JSObject;
64 class imgICache;
65 class imgIContainer;
66 class imgINotificationObserver;
67 class imgIRequest;
68 class imgLoader;
69 class imgRequestProxy;
70 class nsAtom;
71 class nsAttrValue;
72 class nsAutoScriptBlockerSuppressNodeRemoved;
73 class nsContentList;
74 class nsCycleCollectionTraversalCallback;
75 class nsDocShell;
76 class nsGlobalWindowInner;
77 class nsHtml5StringParser;
78 class nsIArray;
79 class nsIBidiKeyboard;
80 class nsIChannel;
81 class nsIConsoleService;
82 class nsIContent;
83 class nsIDocShell;
84 class nsIDocShellTreeItem;
85 class nsIDocumentLoaderFactory;
86 class nsIDragSession;
87 class nsIFile;
88 class nsIFragmentContentSink;
89 class nsIFrame;
90 class nsIHttpChannel;
91 class nsIIOService;
92 class nsIImageLoadingContent;
93 class nsIInterfaceRequestor;
94 class nsILoadGroup;
95 class nsILoadInfo;
96 class nsIObserver;
97 class nsIPluginTag;
98 class nsIPrincipal;
99 class nsIReferrerInfo;
100 class nsIRequest;
101 class nsIRunnable;
102 class nsIScreen;
103 class nsIScriptContext;
104 class nsIScriptSecurityManager;
105 class nsISerialEventTarget;
106 class nsIStringBundle;
107 class nsIStringBundleService;
108 class nsISupports;
109 class nsITransferable;
110 class nsIURI;
111 class nsIWidget;
112 class nsIWritableVariant;
113 class nsIXPConnect;
114 class nsNodeInfoManager;
115 class nsParser;
116 class nsPIWindowRoot;
117 class nsPresContext;
118 class nsStringBuffer;
119 class nsTextFragment;
120 class nsView;
121 class nsWrapperCache;
123 struct JSContext;
124 struct nsPoint;
126 namespace IPC {
127 class Message;
128 class MessageReader;
129 class MessageWriter;
130 } // namespace IPC
132 namespace JS {
133 class Value;
134 class PropertyDescriptor;
135 } // namespace JS
137 namespace mozilla {
138 class Dispatcher;
139 class EditorBase;
140 class ErrorResult;
141 class EventListenerManager;
142 class HTMLEditor;
143 class LazyLogModule;
144 class LogModule;
145 class PresShell;
146 class TextEditor;
147 class WidgetDragEvent;
148 class WidgetKeyboardEvent;
150 struct InputEventOptions;
152 template <typename ParentType, typename RefType>
153 class RangeBoundaryBase;
155 template <typename T>
156 class NotNull;
157 template <class T>
158 class StaticRefPtr;
160 namespace dom {
161 class IPCImage;
162 struct AutocompleteInfo;
163 class BrowserChild;
164 class BrowserParent;
165 class BrowsingContext;
166 class BrowsingContextGroup;
167 class ContentChild;
168 class ContentFrameMessageManager;
169 class ContentParent;
170 struct CustomElementDefinition;
171 class CustomElementFormValue;
172 class CustomElementRegistry;
173 class DataTransfer;
174 class Document;
175 class DocumentFragment;
176 class DOMArena;
177 class Element;
178 class Event;
179 class EventTarget;
180 class HTMLElement;
181 class HTMLInputElement;
182 class IPCTransferable;
183 class IPCTransferableData;
184 class IPCTransferableDataImageContainer;
185 class IPCTransferableDataItem;
186 struct LifecycleCallbackArgs;
187 class MessageBroadcaster;
188 class NodeInfo;
189 class OwningFileOrUSVStringOrFormData;
190 class Selection;
191 struct StructuredSerializeOptions;
192 class WorkerPrivate;
193 enum class ElementCallbackType;
194 enum class ReferrerPolicy : uint8_t;
195 } // namespace dom
197 namespace ipc {
198 class BigBuffer;
199 class IProtocol;
200 } // namespace ipc
202 namespace gfx {
203 class DataSourceSurface;
204 enum class SurfaceFormat : int8_t;
205 } // namespace gfx
207 class WindowRenderer;
209 } // namespace mozilla
211 extern const char kLoadAsData[];
213 // Stolen from nsReadableUtils, but that's OK, since we can declare the same
214 // name multiple times.
215 const nsString& EmptyString();
216 const nsCString& EmptyCString();
218 enum EventNameType {
219 EventNameType_None = 0x0000,
220 EventNameType_HTML = 0x0001,
221 EventNameType_XUL = 0x0002,
222 EventNameType_SVGGraphic = 0x0004, // svg graphic elements
223 EventNameType_SVGSVG = 0x0008, // the svg element
224 EventNameType_SMIL = 0x0010, // smil elements
225 EventNameType_HTMLBodyOrFramesetOnly = 0x0020,
226 EventNameType_HTMLMarqueeOnly = 0x0040,
228 EventNameType_HTMLXUL = 0x0003,
229 EventNameType_All = 0xFFFF
232 struct EventNameMapping {
233 // This holds pointers to nsGkAtoms members, and is therefore safe as a
234 // non-owning reference.
235 nsAtom* MOZ_NON_OWNING_REF mAtom;
236 int32_t mType;
237 mozilla::EventMessage mMessage;
238 mozilla::EventClassID mEventClassID;
241 namespace mozilla {
242 enum class PreventDefaultResult : uint8_t { No, ByContent, ByChrome };
244 namespace dom {
245 enum JSONBehavior { UndefinedIsNullStringLiteral, UndefinedIsVoidString };
247 } // namespace mozilla
249 class nsContentUtils {
250 friend class nsAutoScriptBlockerSuppressNodeRemoved;
251 using Element = mozilla::dom::Element;
252 using Document = mozilla::dom::Document;
253 using Cancelable = mozilla::Cancelable;
254 using CanBubble = mozilla::CanBubble;
255 using Composed = mozilla::Composed;
256 using ChromeOnlyDispatch = mozilla::ChromeOnlyDispatch;
257 using EventMessage = mozilla::EventMessage;
258 using TimeDuration = mozilla::TimeDuration;
259 using Trusted = mozilla::Trusted;
260 using JSONBehavior = mozilla::dom::JSONBehavior;
261 using RFPTarget = mozilla::RFPTarget;
263 public:
264 static nsresult Init();
266 static bool IsCallerChrome();
267 static bool ThreadsafeIsCallerChrome();
268 static bool IsCallerUAWidget();
269 static bool IsFuzzingEnabled()
270 #ifndef FUZZING
272 return false;
274 #else
276 #endif
277 static bool IsErrorPage(nsIURI* aURI);
279 static bool IsCallerChromeOrFuzzingEnabled(JSContext* aCx, JSObject*) {
280 return ThreadsafeIsSystemCaller(aCx) || IsFuzzingEnabled();
283 static bool IsCallerChromeOrElementTransformGettersEnabled(JSContext* aCx,
284 JSObject*);
286 // The APIs for checking whether the caller is system (in the sense of system
287 // principal) should only be used when the JSContext is known to accurately
288 // represent the caller. In practice, that means you should only use them in
289 // two situations at the moment:
291 // 1) Functions used in WebIDL Func annotations.
292 // 2) Bindings code or other code called directly from the JS engine.
294 // Use pretty much anywhere else is almost certainly wrong and should be
295 // replaced with [NeedsCallerType] annotations in bindings.
297 // Check whether the caller is system if you know you're on the main thread.
298 static bool IsSystemCaller(JSContext* aCx);
300 // Check whether the caller is system if you might be on a worker or worklet
301 // thread.
302 static bool ThreadsafeIsSystemCaller(JSContext* aCx);
304 // In the traditional Gecko architecture, both C++ code and untrusted JS code
305 // needed to rely on the same XPCOM method/getter/setter to get work done.
306 // This required lots of security checks in the various exposed methods, which
307 // in turn created difficulty in determining whether the caller was script
308 // (whose access needed to be checked) and internal C++ platform code (whose
309 // access did not need to be checked). To address this problem, Gecko had a
310 // convention whereby the absence of script on the stack was interpretted as
311 // "System Caller" and always granted unfettered access.
313 // Unfortunately, this created a bunch of footguns. For example, when the
314 // implementation of a DOM method wanted to perform a privileged
315 // sub-operation, it needed to "hide" the presence of script on the stack in
316 // order for that sub-operation to be allowed. Additionally, if script could
317 // trigger an API entry point to be invoked in some asynchronous way without
318 // script on the stack, it could potentially perform privilege escalation.
320 // In the modern world, untrusted script should interact with the platform
321 // exclusively over WebIDL APIs, and platform code has a lot more flexibility
322 // in deciding whether or not to use XPCOM. This gives us the flexibility to
323 // do something better.
325 // Going forward, APIs should be designed such that any security checks that
326 // ask the question "is my caller allowed to do this?" should live in WebIDL
327 // API entry points, with a separate method provided for internal callers
328 // that just want to get the job done.
330 // To enforce this and catch bugs, nsContentUtils::SubjectPrincipal will crash
331 // if it is invoked without script on the stack. To land that transition, it
332 // was necessary to go through and whitelist a bunch of callers that were
333 // depending on the old behavior. Those callers should be fixed up, and these
334 // methods should not be used by new code without review from bholley or bz.
335 static bool LegacyIsCallerNativeCode() { return !GetCurrentJSContext(); }
336 static bool LegacyIsCallerChromeOrNativeCode() {
337 return LegacyIsCallerNativeCode() || IsCallerChrome();
339 static nsIPrincipal* SubjectPrincipalOrSystemIfNativeCaller() {
340 if (!GetCurrentJSContext()) {
341 return GetSystemPrincipal();
343 return SubjectPrincipal();
346 static bool LookupBindingMember(
347 JSContext* aCx, nsIContent* aContent, JS::Handle<jsid> aId,
348 JS::MutableHandle<JS::PropertyDescriptor> aDesc);
350 // Check whether we should avoid leaking distinguishing information to JS/CSS.
351 // This function can be called both in the main thread and worker threads.
352 static bool ShouldResistFingerprinting(RFPTarget aTarget);
353 static bool ShouldResistFingerprinting(nsIGlobalObject* aGlobalObject,
354 RFPTarget aTarget);
355 // Similar to the function above, but always allows CallerType::System
356 // callers.
357 static bool ShouldResistFingerprinting(mozilla::dom::CallerType aCallerType,
358 nsIGlobalObject* aGlobalObject,
359 RFPTarget aTarget);
360 static bool ShouldResistFingerprinting(nsIDocShell* aDocShell,
361 RFPTarget aTarget);
362 // These functions are the new, nuanced functions
363 static bool ShouldResistFingerprinting(nsIChannel* aChannel,
364 RFPTarget aTarget);
365 // These functions are labeled as dangerous because they will do the wrong
366 // thing in _most_ cases. They should only be used if you don't have a fully
367 // constructed LoadInfo or Document.
368 // A constant string used as justification is required when calling them,
369 // it should explain why a Document, Channel, LoadInfo, or CookieJarSettings
370 // does not exist in this context.
371 // (see below for more on justification strings.)
372 static bool ShouldResistFingerprinting_dangerous(
373 nsIURI* aURI, const mozilla::OriginAttributes& aOriginAttributes,
374 const char* aJustification, RFPTarget aTarget);
375 static bool ShouldResistFingerprinting_dangerous(nsIPrincipal* aPrincipal,
376 const char* aJustification,
377 RFPTarget aTarget);
380 * Implement a RFP function that only checks the pref, and does not take
381 * into account any additional context such as PBM mode or Web Extensions.
383 * It requires an explanation for why the coarse check is being used instead
384 * of the nuanced check. While there is a gradual cut over of
385 * ShouldResistFingerprinting calls to a nuanced API, some features still
386 * require a legacy function. (Additionally, we sometimes use the coarse
387 * check first, to avoid running additional code to support a nuanced check.)
389 static bool ShouldResistFingerprinting(const char* aJustification,
390 RFPTarget aTarget);
392 // A helper function to calculate the rounded window size for fingerprinting
393 // resistance. The rounded size is based on the chrome UI size and available
394 // screen size. If the inputWidth/Height is greater than the available content
395 // size, this will report the available content size. Otherwise, it will
396 // round the size to the nearest upper 200x100.
397 static void CalcRoundedWindowSizeForResistingFingerprinting(
398 int32_t aChromeWidth, int32_t aChromeHeight, int32_t aScreenWidth,
399 int32_t aScreenHeight, int32_t aInputWidth, int32_t aInputHeight,
400 bool aSetOuterWidth, bool aSetOuterHeight, int32_t* aOutputWidth,
401 int32_t* aOutputHeight);
404 * Returns the parent node of aChild crossing document boundaries, but skips
405 * any cross-process parent frames and continues with the nearest in-process
406 * frame in the hierarchy.
408 * Uses the parent node in the composed document.
410 static nsINode* GetNearestInProcessCrossDocParentNode(nsINode* aChild);
413 * Similar to nsINode::IsInclusiveDescendantOf, except will treat an
414 * HTMLTemplateElement or ShadowRoot as an ancestor of things in the
415 * corresponding DocumentFragment. See the concept of "host-including
416 * inclusive ancestor" in the DOM specification.
418 static bool ContentIsHostIncludingDescendantOf(
419 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
422 * Similar to nsINode::IsInclusiveDescendantOf except it crosses document
423 * boundaries, this function uses ancestor/descendant relations in the
424 * composed document (see shadow DOM spec).
426 static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant,
427 nsINode* aPossibleAncestor);
430 * As with ContentIsCrossDocDescendantOf but crosses shadow boundaries but not
431 * cross document boundaries.
433 * @see nsINode::GetFlattenedTreeParentNode()
435 static bool ContentIsFlattenedTreeDescendantOf(
436 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
439 * Same as `ContentIsFlattenedTreeDescendantOf`, but from the flattened tree
440 * point of view of the style system
442 * @see nsINode::GetFlattenedTreeParentNodeForStyle()
444 static bool ContentIsFlattenedTreeDescendantOfForStyle(
445 const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
448 * Retarget an object A against an object B
449 * @see https://dom.spec.whatwg.org/#retarget
451 static nsINode* Retarget(nsINode* aTargetA, nsINode* aTargetB);
454 * @see https://wicg.github.io/element-timing/#get-an-element
456 static Element* GetAnElementForTiming(Element* aTarget,
457 const Document* aDocument,
458 nsIGlobalObject* aGlobal);
461 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
463 * This method fills the |aArray| with all ancestor nodes of |aNode|
464 * including |aNode| at the zero index.
467 static nsresult GetInclusiveAncestors(nsINode* aNode,
468 nsTArray<nsINode*>& aArray);
471 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor.
473 * This method fills |aAncestorNodes| with all ancestor nodes of |aNode|
474 * including |aNode| (QI'd to nsIContent) at the zero index.
475 * For each ancestor, there is a corresponding element in |aAncestorOffsets|
476 * which is the ComputeIndexOf the child in relation to its parent.
478 * This method just sucks.
480 static nsresult GetInclusiveAncestorsAndOffsets(
481 nsINode* aNode, uint32_t aOffset, nsTArray<nsIContent*>* aAncestorNodes,
482 nsTArray<mozilla::Maybe<uint32_t>>* aAncestorOffsets);
485 * Returns the closest common inclusive ancestor
486 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) , if any,
487 * for two nodes.
489 * Returns null if the nodes are disconnected.
491 static nsINode* GetClosestCommonInclusiveAncestor(nsINode* aNode1,
492 nsINode* aNode2) {
493 if (aNode1 == aNode2) {
494 return aNode1;
497 return GetCommonAncestorHelper(aNode1, aNode2);
501 * Returns the common flattened tree ancestor, if any, for two given content
502 * nodes.
504 static nsIContent* GetCommonFlattenedTreeAncestor(nsIContent* aContent1,
505 nsIContent* aContent2) {
506 if (aContent1 == aContent2) {
507 return aContent1;
510 return GetCommonFlattenedTreeAncestorHelper(aContent1, aContent2);
514 * Returns the common flattened tree ancestor from the point of view of the
515 * style system, if any, for two given content nodes.
517 static Element* GetCommonFlattenedTreeAncestorForStyle(Element* aElement1,
518 Element* aElement2);
521 * Returns the common BrowserParent ancestor, if any, for two given
522 * BrowserParent.
524 static mozilla::dom::BrowserParent* GetCommonBrowserParentAncestor(
525 mozilla::dom::BrowserParent* aBrowserParent1,
526 mozilla::dom::BrowserParent* aBrowserParent2);
528 // https://html.spec.whatwg.org/#target-element
529 // https://html.spec.whatwg.org/#find-a-potential-indicated-element
530 static Element* GetTargetElement(Document* aDocument,
531 const nsAString& aAnchorName);
533 * Returns true if aNode1 is before aNode2 in the same connected
534 * tree.
535 * aNode1Index and aNode2Index are in/out arguments. If non-null, and value is
536 * Some, that value is used instead of calling slow ComputeIndexOf on the
537 * parent node. If value is Nothing, the value will be set to the return value
538 * of ComputeIndexOf.
540 static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2,
541 mozilla::Maybe<uint32_t>* aNode1Index = nullptr,
542 mozilla::Maybe<uint32_t>* aNode2Index = nullptr);
544 struct ComparePointsCache {
545 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aParent,
546 const nsINode* aChild) {
547 if (aParent == mParent && aChild == mChild) {
548 return mIndex;
551 mIndex = aParent->ComputeIndexOf(aChild);
552 mParent = aParent;
553 mChild = aChild;
554 return mIndex;
557 private:
558 const nsINode* mParent = nullptr;
559 const nsINode* mChild = nullptr;
560 mozilla::Maybe<uint32_t> mIndex;
564 * Utility routine to compare two "points", where a point is a node/offset
565 * pair.
566 * Pass a cache object as aParent1Cache if you expect to repeatedly
567 * call this function with the same value as aParent1.
569 * @return -1 if point1 < point2,
570 * 1 if point1 > point2,
571 * 0 if point1 == point2.
572 * `Nothing` if the two nodes aren't in the same connected subtree.
574 static mozilla::Maybe<int32_t> ComparePoints(
575 const nsINode* aParent1, uint32_t aOffset1, const nsINode* aParent2,
576 uint32_t aOffset2, ComparePointsCache* aParent1Cache = nullptr);
577 template <typename FPT, typename FRT, typename SPT, typename SRT>
578 static mozilla::Maybe<int32_t> ComparePoints(
579 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
580 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary);
583 * Utility routine to compare two "points", where a point is a
584 * node/offset pair
585 * Returns -1 if point1 < point2, 1, if point1 > point2,
586 * 0 if error or if point1 == point2.
587 * NOTE! If the two nodes aren't in the same connected subtree,
588 * the result is 1, and the optional aDisconnected parameter
589 * is set to true.
591 * Pass a cache object as aParent1Cache if you expect to repeatedly
592 * call this function with the same value as aParent1.
594 static int32_t ComparePoints_Deprecated(
595 const nsINode* aParent1, uint32_t aOffset1, const nsINode* aParent2,
596 uint32_t aOffset2, bool* aDisconnected = nullptr,
597 ComparePointsCache* aParent1Cache = nullptr);
598 template <typename FPT, typename FRT, typename SPT, typename SRT>
599 static int32_t ComparePoints_Deprecated(
600 const mozilla::RangeBoundaryBase<FPT, FRT>& aFirstBoundary,
601 const mozilla::RangeBoundaryBase<SPT, SRT>& aSecondBoundary,
602 bool* aDisconnected = nullptr);
605 * DO NOT USE this method for comparing the points in new code. this method
606 * emulates same result as `ComparePoints` before bug 1741148.
607 * When the old `ComparePoints` was called with offset value over `INT32_MAX`
608 * or `-1` which is used as "not found" by some API, they were treated as-is
609 * without checking whether the negative value or valid value. Thus, this
610 * handles the negative offset cases in the special paths to keep the
611 * traditional behavior. If you want to use this in new code, it means that
612 * you **should** check the offset values and call `ComparePoints` instead.
614 static mozilla::Maybe<int32_t> ComparePoints_AllowNegativeOffsets(
615 const nsINode* aParent1, int64_t aOffset1, const nsINode* aParent2,
616 int64_t aOffset2) {
617 if (MOZ_UNLIKELY(aOffset1 < 0 || aOffset2 < 0)) {
618 // If in same container, just the offset is compared.
619 if (aParent1 == aParent2) {
620 const int32_t compOffsets =
621 aOffset1 == aOffset2 ? 0 : (aOffset1 < aOffset2 ? -1 : 1);
622 return mozilla::Some(compOffsets);
624 // Otherwise, aOffset1 is referred only when aParent2 is a descendant of
625 // aParent1.
626 if (aOffset1 < 0 && aParent2->IsInclusiveDescendantOf(aParent1)) {
627 return mozilla::Some(-1);
629 // And also aOffset2 is referred only when aParent1 is a descendant of
630 // aParent2.
631 if (aOffset2 < 0 && aParent1->IsInclusiveDescendantOf(aParent2)) {
632 return mozilla::Some(1);
634 // Otherwise, aOffset1 nor aOffset2 is referred so that any value is fine
635 // if negative.
636 return ComparePoints(
637 aParent1, aOffset1 < 0 ? UINT32_MAX : static_cast<uint32_t>(aOffset1),
638 aParent2,
639 aOffset2 < 0 ? UINT32_MAX : static_cast<uint32_t>(aOffset2));
641 return ComparePoints(aParent1, aOffset1, aParent2, aOffset2);
645 * Brute-force search of the element subtree rooted at aContent for
646 * an element with the given id. aId must be nonempty, otherwise
647 * this method may return nodes even if they have no id!
649 static Element* MatchElementId(nsIContent* aContent, const nsAString& aId);
652 * Similar to above, but to be used if one already has an atom for the ID
654 static Element* MatchElementId(nsIContent* aContent, const nsAtom* aId);
657 * Reverses the document position flags passed in.
659 * @param aDocumentPosition The document position flags to be reversed.
661 * @return The reversed document position flags.
663 * @see Node
665 static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition);
667 static const nsDependentSubstring TrimCharsInSet(const char* aSet,
668 const nsAString& aValue);
670 template <bool IsWhitespace(char16_t)>
671 static const nsDependentSubstring TrimWhitespace(const nsAString& aStr,
672 bool aTrimTrailing = true);
675 * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe.
677 static bool IsFirstLetterPunctuation(uint32_t aChar);
680 * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No
682 static bool IsAlphanumeric(uint32_t aChar);
684 * Returns true if aChar is of class L*, N* or S* (for first-letter).
686 static bool IsAlphanumericOrSymbol(uint32_t aChar);
689 * Is the character an HTML whitespace character?
691 * We define whitespace using the list in HTML5 and css3-selectors:
692 * U+0009, U+000A, U+000C, U+000D, U+0020
694 * HTML 4.01 also lists U+200B (zero-width space).
696 static bool IsHTMLWhitespace(char16_t aChar);
699 * Returns whether the character is an HTML whitespace (see IsHTMLWhitespace)
700 * or a nbsp character (U+00A0).
702 static bool IsHTMLWhitespaceOrNBSP(char16_t aChar);
705 * https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
707 static bool IsHTMLBlockLevelElement(nsIContent* aContent);
709 enum ParseHTMLIntegerResultFlags {
710 eParseHTMLInteger_NoFlags = 0,
711 // eParseHTMLInteger_NonStandard is set if the string representation of the
712 // integer was not the canonical one, but matches at least one of the
713 // following:
714 // * had leading whitespaces
715 // * had '+' sign
716 // * had leading '0'
717 // * was '-0'
718 eParseHTMLInteger_NonStandard = 1 << 0,
719 eParseHTMLInteger_DidNotConsumeAllInput = 1 << 1,
720 // Set if one or more error flags were set.
721 eParseHTMLInteger_Error = 1 << 2,
722 eParseHTMLInteger_ErrorNoValue = 1 << 3,
723 eParseHTMLInteger_ErrorOverflow = 1 << 4,
724 // Use this flag to detect the difference between overflow and underflow
725 eParseHTMLInteger_Negative = 1 << 5,
727 static int32_t ParseHTMLInteger(const nsAString& aValue,
728 ParseHTMLIntegerResultFlags* aResult) {
729 return ParseHTMLInteger(aValue.BeginReading(), aValue.EndReading(),
730 aResult);
732 static int32_t ParseHTMLInteger(const char16_t* aStart, const char16_t* aEnd,
733 ParseHTMLIntegerResultFlags* aResult);
734 static int32_t ParseHTMLInteger(const nsACString& aValue,
735 ParseHTMLIntegerResultFlags* aResult) {
736 return ParseHTMLInteger(aValue.BeginReading(), aValue.EndReading(),
737 aResult);
739 static int32_t ParseHTMLInteger(const char* aStart, const char* aEnd,
740 ParseHTMLIntegerResultFlags* aResult);
742 private:
743 template <class CharT>
744 static int32_t ParseHTMLIntegerImpl(const CharT* aStart, const CharT* aEnd,
745 ParseHTMLIntegerResultFlags* aResult);
747 public:
749 * Parse a margin string of format 'top, right, bottom, left' into
750 * an nsIntMargin.
752 * @param aString the string to parse
753 * @param aResult the resulting integer
754 * @return whether the value could be parsed
756 static bool ParseIntMarginValue(const nsAString& aString,
757 nsIntMargin& aResult);
760 * Parse the value of the <font size=""> attribute according to the HTML5
761 * spec as of April 16, 2012.
763 * @param aValue the value to parse
764 * @return 1 to 7, or 0 if the value couldn't be parsed
766 static int32_t ParseLegacyFontSize(const nsAString& aValue);
768 static void Shutdown();
771 * Checks whether two nodes come from the same origin.
773 static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
774 const nsINode* unTrustedNode);
776 // Check if the (JS) caller can access aNode.
777 static bool CanCallerAccess(const nsINode* aNode);
779 // Check if the (JS) caller can access aWindow.
780 // aWindow can be either outer or inner window.
781 static bool CanCallerAccess(nsPIDOMWindowInner* aWindow);
783 // Check if the principal is chrome or an addon with the permission.
784 static bool PrincipalHasPermission(nsIPrincipal& aPrincipal,
785 const nsAtom* aPerm);
787 // Check if the JS caller is chrome or an addon with the permission.
788 static bool CallerHasPermission(JSContext* aCx, const nsAtom* aPerm);
791 * Returns the triggering principal which should be used for the given URL
792 * attribute value with the given subject principal.
794 * If the attribute value is not an absolute URL, the subject principal will
795 * be ignored, and the node principal of aContent will be used instead.
796 * If aContent is non-null, this function will always return a principal.
797 * Otherewise, it may return null if aSubjectPrincipal is null or is rejected
798 * based on the attribute value.
800 * @param aContent The content on which the attribute is being set.
801 * @param aAttrValue The URL value of the attribute. For parsed attribute
802 * values, such as `srcset`, this function should be called separately
803 * for each URL value it contains.
804 * @param aSubjectPrincipal The subject principal of the scripted caller
805 * responsible for setting the attribute, or null if no scripted caller
806 * can be determined.
808 static nsIPrincipal* GetAttrTriggeringPrincipal(
809 nsIContent* aContent, const nsAString& aAttrValue,
810 nsIPrincipal* aSubjectPrincipal);
813 * Returns true if the given string is guaranteed to be treated as an absolute
814 * URL, rather than a relative URL. In practice, this means any complete URL
815 * as supported by nsStandardURL, or any string beginning with a valid scheme
816 * which is known to the IO service, and has the URI_NORELATIVE flag.
818 * If the URL may be treated as absolute in some cases, but relative in others
819 * (for instance, "http:foo", which can be either an absolute or relative URL,
820 * depending on the context), this function returns false.
822 static bool IsAbsoluteURL(const nsACString& aURL);
824 // Check if a node is in the document prolog, i.e. before the document
825 // element.
826 static bool InProlog(nsINode* aNode);
828 static nsIBidiKeyboard* GetBidiKeyboard();
831 * Get the cache security manager service. Can return null if the layout
832 * module has been shut down.
834 static nsIScriptSecurityManager* GetSecurityManager() {
835 return sSecurityManager;
838 // Returns the subject principal from the JSContext. May only be called
839 // from the main thread and assumes an existing compartment.
840 static nsIPrincipal* SubjectPrincipal(JSContext* aCx);
842 // Returns the subject principal. Guaranteed to return non-null. May only
843 // be called when nsContentUtils is initialized.
844 static nsIPrincipal* SubjectPrincipal();
846 // Returns the prinipal of the given JS object. This may only be called on
847 // the main thread for objects from the main thread's JSRuntime. The object
848 // must not be a cross-compartment wrapper, because CCWs are not associated
849 // with a single realm.
850 static nsIPrincipal* ObjectPrincipal(JSObject* aObj);
852 static void GenerateStateKey(nsIContent* aContent, Document* aDocument,
853 nsACString& aKey);
856 * Create a new nsIURI from aSpec, using aBaseURI as the base. The
857 * origin charset of the new nsIURI will be the document charset of
858 * aDocument.
860 static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
861 const nsAString& aSpec,
862 Document* aDocument,
863 nsIURI* aBaseURI);
866 * Returns true if |aName| is a name with dashes.
868 static bool IsNameWithDash(nsAtom* aName);
871 * Returns true if |aName| is a valid name to be registered via
872 * customElements.define.
874 static bool IsCustomElementName(nsAtom* aName, uint32_t aNameSpaceID);
876 static nsresult CheckQName(const nsAString& aQualifiedName,
877 bool aNamespaceAware = true,
878 const char16_t** aColon = nullptr);
880 static nsresult SplitQName(const nsIContent* aNamespaceResolver,
881 const nsString& aQName, int32_t* aNamespace,
882 nsAtom** aLocalName);
884 static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
885 const nsAString& aQualifiedName,
886 nsNodeInfoManager* aNodeInfoManager,
887 uint16_t aNodeType,
888 mozilla::dom::NodeInfo** aNodeInfo);
890 static void SplitExpatName(const char16_t* aExpatName, nsAtom** aPrefix,
891 nsAtom** aTagName, int32_t* aNameSpaceID);
893 // Get a permission-manager setting for the given principal and type.
894 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
895 // returned, otherwise true is returned. Always returns true for the
896 // system principal, and false for a null principal.
897 static bool IsSitePermAllow(nsIPrincipal* aPrincipal,
898 const nsACString& aType);
900 // Get a permission-manager setting for the given principal and type.
901 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
902 // returned, otherwise true is returned. Always returns false for the
903 // system principal, and true for a null principal.
904 static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const nsACString& aType);
906 // Get a permission-manager setting for the given principal and type.
907 // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
908 // returned, otherwise true is returned. Always returns true for the
909 // system principal, and false for a null principal.
910 // This version checks the permission for an exact host match on
911 // the principal
912 static bool IsExactSitePermAllow(nsIPrincipal* aPrincipal,
913 const nsACString& aType);
915 // Get a permission-manager setting for the given principal and type.
916 // If the pref doesn't exist or if it isn't DENY_ACTION, false is
917 // returned, otherwise true is returned. Always returns false for the
918 // system principal, and true for a null principal.
919 // This version checks the permission for an exact host match on
920 // the principal
921 static bool IsExactSitePermDeny(nsIPrincipal* aPrincipal,
922 const nsACString& aType);
924 // Returns true if the pref exists and is not UNKNOWN_ACTION.
925 static bool HasSitePerm(nsIPrincipal* aPrincipal, const nsACString& aType);
927 // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s.
928 static bool HaveEqualPrincipals(Document* aDoc1, Document* aDoc2);
931 * Regster aObserver as a shutdown observer. A strong reference is held
932 * to aObserver until UnregisterShutdownObserver is called.
934 static void RegisterShutdownObserver(nsIObserver* aObserver);
935 static void UnregisterShutdownObserver(nsIObserver* aObserver);
938 * @return true if aContent has an attribute aName in namespace aNameSpaceID,
939 * and the attribute value is non-empty.
941 static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID,
942 nsAtom* aName);
945 * Method that gets the primary presContext for the node.
947 * @param aContent The content node.
948 * @return the presContext, or nullptr if the content is not in a document
949 * (if GetComposedDoc returns nullptr)
951 static nsPresContext* GetContextForContent(const nsIContent* aContent);
954 * Method that gets the pres shell for the node.
956 * @param aContent The content node.
957 * @return the pres shell, or nullptr if the content is not in a document
958 * (if GetComposedDoc returns nullptr)
960 static mozilla::PresShell* GetPresShellForContent(const nsIContent* aContent);
963 * Method to do security and content policy checks on the image URI
965 * @param aURI uri of the image to be loaded
966 * @param aNode, the context the image is loaded in (eg an element)
967 * @param aLoadingDocument the document we belong to
968 * @param aLoadingPrincipal the principal doing the load
969 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
970 * (Optional) The CP content type to use
971 * @param aImageBlockingStatus the nsIContentPolicy blocking status for this
972 * image. This will be set even if a security check fails for the
973 * image, to some reasonable REJECT_* value. This out param will only
974 * be set if it's non-null.
975 * @return true if the load can proceed, or false if it is blocked.
976 * Note that aImageBlockingStatus, if set will always be an ACCEPT
977 * status if true is returned and always be a REJECT_* status if
978 * false is returned.
980 static bool CanLoadImage(nsIURI* aURI, nsINode* aNode,
981 Document* aLoadingDocument,
982 nsIPrincipal* aLoadingPrincipal);
985 * Returns true if objects in aDocument shouldn't initiate image loads.
987 static bool DocumentInactiveForImageLoads(Document* aDocument);
990 * Convert a CORSMode into the corresponding imgILoader flags for
991 * passing to LoadImage.
992 * @param aMode CORS mode to convert
993 * @return a bitfield suitable to bitwise OR with other nsIRequest flags
995 static int32_t CORSModeToLoadImageFlags(mozilla::CORSMode aMode);
998 * Method to start an image load. This does not do any security checks.
999 * This method will attempt to make aURI immutable; a caller that wants to
1000 * keep a mutable version around should pass in a clone.
1002 * @param aURI uri of the image to be loaded
1003 * @param aContext element of document where the result of this request
1004 * will be used.
1005 * @param aLoadingDocument the document we belong to
1006 * @param aLoadingPrincipal the principal doing the load
1007 * @param aReferrerInfo the referrerInfo use on channel creation
1008 * @param aObserver the observer for the image load
1009 * @param aLoadFlags the load flags to use. See nsIRequest
1010 * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE]
1011 * (Optional) The CP content type to use
1012 * @param aUseUrgentStartForChannel,(Optional) a flag to mark on channel if it
1013 * is triggered by user input events.
1014 * @return the imgIRequest for the image load
1016 static nsresult LoadImage(
1017 nsIURI* aURI, nsINode* aContext, Document* aLoadingDocument,
1018 nsIPrincipal* aLoadingPrincipal, uint64_t aRequestContextID,
1019 nsIReferrerInfo* aReferrerInfo, imgINotificationObserver* aObserver,
1020 int32_t aLoadFlags, const nsAString& initiatorType,
1021 imgRequestProxy** aRequest,
1022 nsContentPolicyType aContentPolicyType =
1023 nsIContentPolicy::TYPE_INTERNAL_IMAGE,
1024 bool aUseUrgentStartForChannel = false, bool aLinkPreload = false,
1025 uint64_t aEarlyHintPreloaderId = 0);
1028 * Obtain an image loader that respects the given document/channel's privacy
1029 * status. Null document/channel arguments return the public image loader.
1031 static imgLoader* GetImgLoaderForDocument(Document* aDoc);
1032 static imgLoader* GetImgLoaderForChannel(nsIChannel* aChannel,
1033 Document* aContext);
1036 * Method to get an imgIContainer from an image loading content
1038 * @param aContent The image loading content. Must not be null.
1039 * @param aRequest The image request [out]
1040 * @return the imgIContainer corresponding to the first frame of the image
1042 static already_AddRefed<imgIContainer> GetImageFromContent(
1043 nsIImageLoadingContent* aContent, imgIRequest** aRequest = nullptr);
1046 * Method that decides whether a content node is draggable
1048 * @param aContent The content node to test.
1049 * @return whether it's draggable
1051 static bool ContentIsDraggable(nsIContent* aContent);
1054 * Method that decides whether a content node is a draggable image
1056 * @param aContent The content node to test.
1057 * @return whether it's a draggable image
1059 static bool IsDraggableImage(nsIContent* aContent);
1062 * Method that decides whether a content node is a draggable link
1064 * @param aContent The content node to test.
1065 * @return whether it's a draggable link
1067 static bool IsDraggableLink(const nsIContent* aContent);
1070 * Convenience method to create a new nodeinfo that differs only by prefix and
1071 * name from aNodeInfo. The new nodeinfo's name is set to aName, and prefix is
1072 * set to null.
1074 static nsresult QNameChanged(mozilla::dom::NodeInfo* aNodeInfo, nsAtom* aName,
1075 mozilla::dom::NodeInfo** aResult);
1078 * Returns the appropriate event argument names for the specified
1079 * namespace and event name. Added because we need to switch between
1080 * SVG's "evt" and the rest of the world's "event", and because onerror
1081 * on window takes 5 args.
1083 static void GetEventArgNames(int32_t aNameSpaceID, nsAtom* aEventName,
1084 bool aIsForWindow, uint32_t* aArgCount,
1085 const char*** aArgNames);
1088 * Returns true if this document is in a Private Browsing window.
1090 static bool IsInPrivateBrowsing(Document* aDoc);
1093 * Returns true if this loadGroup uses Private Browsing.
1095 static bool IsInPrivateBrowsing(nsILoadGroup* aLoadGroup);
1098 * Returns whether a node is in the same tree as another one, accounting for
1099 * anonymous roots.
1101 * This method is particularly useful for callers who are trying to ensure
1102 * that they are working with a non-anonymous descendant of a given node. If
1103 * aContent is a descendant of aNode, a return value of false from this
1104 * method means that it's an anonymous descendant from aNode's point of view.
1106 * Both arguments to this method must be non-null.
1108 static bool IsInSameAnonymousTree(const nsINode* aNode,
1109 const nsINode* aOtherNode);
1112 * Traverse the parent chain from aElement up to aStop, and return true if
1113 * there's an interactive html content; false otherwise.
1115 * Note: This crosses shadow boundaries but not document boundaries.
1117 static bool IsInInteractiveHTMLContent(const Element* aElement,
1118 const Element* aStop);
1121 * Return the nsIXPConnect service.
1123 static nsIXPConnect* XPConnect() { return sXPConnect; }
1126 * Report simple error message to the browser console
1127 * @param aErrorText the error message
1128 * @param aCategory Name of the module reporting error
1129 * @param aFromPrivateWindow Whether from private window or not
1130 * @param aFromChromeContext Whether from chrome context or not
1131 * @param [aErrorFlags] See nsIScriptError.
1133 static void LogSimpleConsoleError(
1134 const nsAString& aErrorText, const nsACString& aCategory,
1135 bool aFromPrivateWindow, bool aFromChromeContext,
1136 uint32_t aErrorFlags = nsIScriptError::errorFlag);
1139 * Report a non-localized error message to the error console.
1140 * @param aErrorText the error message
1141 * @param aErrorFlags See nsIScriptError.
1142 * @param aCategory Name of module reporting error.
1143 * @param aDocument Reference to the document which triggered the message.
1144 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1145 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1146 contains the error (may be empty).
1147 * @param [aLineNumber=0] (Optional) Line number within resource
1148 containing error.
1149 * @param [aColumnNumber=0] (Optional) Column number within resource
1150 containing error.
1151 If aURI is null, then aDocument->GetDocumentURI() is used.
1152 * @param [aLocationMode] (Optional) Specifies the behavior if
1153 error location information is omitted.
1155 enum MissingErrorLocationMode {
1156 // Don't show location information in the error console.
1157 eOMIT_LOCATION,
1158 // Get location information from the currently executing script.
1159 eUSE_CALLING_LOCATION
1161 static nsresult ReportToConsoleNonLocalized(
1162 const nsAString& aErrorText, uint32_t aErrorFlags,
1163 const nsACString& aCategory, const Document* aDocument,
1164 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1165 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
1166 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1169 * Report a non-localized error message to the error console base on the
1170 * innerWindowID.
1171 * @param aErrorText the error message
1172 * @param aErrorFlags See nsIScriptError.
1173 * @param aCategory Name of module reporting error.
1174 * @param [aInnerWindowID] Inner window ID for document which triggered the
1175 * message.
1176 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1177 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1178 contains the error (may be empty).
1179 * @param [aLineNumber=0] (Optional) Line number within resource
1180 containing error.
1181 * @param [aColumnNumber=0] (Optional) Column number within resource
1182 containing error.
1183 If aURI is null, then aDocument->GetDocumentURI() is used.
1184 * @param [aLocationMode] (Optional) Specifies the behavior if
1185 error location information is omitted.
1187 static nsresult ReportToConsoleByWindowID(
1188 const nsAString& aErrorText, uint32_t aErrorFlags,
1189 const nsACString& aCategory, uint64_t aInnerWindowID,
1190 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1191 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0,
1192 MissingErrorLocationMode aLocationMode = eUSE_CALLING_LOCATION);
1195 * Report a localized error message to the error console.
1196 * @param aErrorFlags See nsIScriptError.
1197 * @param aCategory Name of module reporting error.
1198 * @param aDocument Reference to the document which triggered the message.
1199 * @param aFile Properties file containing localized message.
1200 * @param aMessageName Name of localized message.
1201 * @param [aParams=empty-array] (Optional) Parameters to be substituted into
1202 localized message.
1203 * @param [aURI=nullptr] (Optional) URI of resource containing error.
1204 * @param [aSourceLine=u""_ns] (Optional) The text of the line that
1205 contains the error (may be empty).
1206 * @param [aLineNumber=0] (Optional) Line number within resource
1207 containing error.
1208 * @param [aColumnNumber=0] (Optional) Column number within resource
1209 containing error.
1210 If aURI is null, then aDocument->GetDocumentURI() is used.
1212 enum PropertiesFile {
1213 eCSS_PROPERTIES,
1214 eXUL_PROPERTIES,
1215 eLAYOUT_PROPERTIES,
1216 eFORMS_PROPERTIES,
1217 ePRINTING_PROPERTIES,
1218 eDOM_PROPERTIES,
1219 eHTMLPARSER_PROPERTIES,
1220 eSVG_PROPERTIES,
1221 eBRAND_PROPERTIES,
1222 eCOMMON_DIALOG_PROPERTIES,
1223 eMATHML_PROPERTIES,
1224 eSECURITY_PROPERTIES,
1225 eNECKO_PROPERTIES,
1226 eFORMS_PROPERTIES_en_US,
1227 eDOM_PROPERTIES_en_US,
1228 PropertiesFile_COUNT
1230 static nsresult ReportToConsole(
1231 uint32_t aErrorFlags, const nsACString& aCategory,
1232 const Document* aDocument, PropertiesFile aFile, const char* aMessageName,
1233 const nsTArray<nsString>& aParams = nsTArray<nsString>(),
1234 nsIURI* aURI = nullptr, const nsString& aSourceLine = u""_ns,
1235 uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0);
1237 static void ReportEmptyGetElementByIdArg(const Document* aDoc);
1239 static void LogMessageToConsole(const char* aMsg);
1241 static bool SpoofLocaleEnglish();
1244 * Get the localized string named |aKey| in properties file |aFile|.
1246 static nsresult GetLocalizedString(PropertiesFile aFile, const char* aKey,
1247 nsAString& aResult);
1250 * Same as GetLocalizedString, except that it might use en-US locale depending
1251 * on SpoofLocaleEnglish() and whether the document is a built-in browser
1252 * page.
1254 static nsresult GetMaybeLocalizedString(PropertiesFile aFile,
1255 const char* aKey, Document* aDocument,
1256 nsAString& aResult);
1259 * A helper function that parses a sandbox attribute (of an <iframe> or a CSP
1260 * directive) and converts it to the set of flags used internally.
1262 * @param aSandboxAttr the sandbox attribute
1263 * @return the set of flags (SANDBOXED_NONE if aSandboxAttr is
1264 * null)
1266 static uint32_t ParseSandboxAttributeToFlags(const nsAttrValue* aSandboxAttr);
1269 * A helper function that checks if a string matches a valid sandbox flag.
1271 * @param aFlag the potential sandbox flag.
1272 * @return true if the flag is a sandbox flag.
1274 static bool IsValidSandboxFlag(const nsAString& aFlag);
1277 * A helper function that returns a string attribute corresponding to the
1278 * sandbox flags.
1280 * @param aFlags the sandbox flags
1281 * @param aString the attribute corresponding to the flags (null if aFlags
1282 * is zero)
1284 static void SandboxFlagsToString(uint32_t aFlags, nsAString& aString);
1286 static bool PrefetchPreloadEnabled(nsIDocShell* aDocShell);
1288 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1289 nsAString& aSourceSpecOut, uint32_t* aLineOut,
1290 uint32_t* aColumnOut, nsString& aMessageOut);
1292 // Variant on `ExtractErrorValues` with a `nsACString`. This
1293 // method is provided for backwards compatibility. Prefer the
1294 // faster method above for your code.
1295 static void ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1296 nsACString& aSourceSpecOut, uint32_t* aLineOut,
1297 uint32_t* aColumnOut, nsString& aMessageOut);
1299 static nsresult CalculateBufferSizeForImage(
1300 const uint32_t& aStride, const mozilla::gfx::IntSize& aImageSize,
1301 const mozilla::gfx::SurfaceFormat& aFormat, size_t* aMaxBufferSize,
1302 size_t* aUsedBufferSize);
1304 // Returns true if the URI's host is contained in a list which is a comma
1305 // separated domain list. Each item may start with "*.". If starts with
1306 // "*.", it matches any sub-domains.
1307 // The aList argument must be a lower-case string.
1308 static bool IsURIInList(nsIURI* aURI, const nsCString& aList);
1310 // Returns true if the URI's host is contained in a pref list which is a comma
1311 // separated domain list. Each item may start with "*.". If starts with
1312 // "*.", it matches any sub-domains.
1313 static bool IsURIInPrefList(nsIURI* aURI, const char* aPrefName);
1316 * A convenience version of FormatLocalizedString that can be used if all the
1317 * params are in same-typed strings. The variadic template args need to come
1318 * at the end, so we put aResult at the beginning to make sure it's clear
1319 * which is the output and which are the inputs.
1321 template <typename... T>
1322 static nsresult FormatLocalizedString(nsAString& aResult,
1323 PropertiesFile aFile, const char* aKey,
1324 const T&... aParams) {
1325 static_assert(sizeof...(aParams) != 0, "Use GetLocalizedString()");
1326 AutoTArray<nsString, sizeof...(aParams)> params = {
1327 aParams...,
1329 return FormatLocalizedString(aFile, aKey, params, aResult);
1333 * Same as FormatLocalizedString template version, except that it might use
1334 * en-US locale depending on SpoofLocaleEnglish() and whether the document is
1335 * a built-in browser page.
1337 template <typename... T>
1338 static nsresult FormatMaybeLocalizedString(nsAString& aResult,
1339 PropertiesFile aFile,
1340 const char* aKey,
1341 Document* aDocument,
1342 const T&... aParams) {
1343 static_assert(sizeof...(aParams) != 0, "Use GetMaybeLocalizedString()");
1344 AutoTArray<nsString, sizeof...(aParams)> params = {
1345 aParams...,
1347 return FormatMaybeLocalizedString(aFile, aKey, aDocument, params, aResult);
1351 * Fill (with the parameters given) the localized string named |aKey| in
1352 * properties file |aFile| consuming an nsTArray of nsString parameters rather
1353 * than a char16_t** for the sake of avoiding use-after-free errors involving
1354 * temporaries.
1356 static nsresult FormatLocalizedString(PropertiesFile aFile, const char* aKey,
1357 const nsTArray<nsString>& aParamArray,
1358 nsAString& aResult);
1361 * Same as FormatLocalizedString, except that it might use en-US locale
1362 * depending on SpoofLocaleEnglish() and whether the document is a built-in
1363 * browser page.
1365 static nsresult FormatMaybeLocalizedString(
1366 PropertiesFile aFile, const char* aKey, Document* aDocument,
1367 const nsTArray<nsString>& aParamArray, nsAString& aResult);
1370 * Returns true if aDocument is a chrome document
1372 static bool IsChromeDoc(const Document* aDocument);
1375 * Returns true if aDocument is in a docshell whose parent is the same type
1377 static bool IsChildOfSameType(Document* aDoc);
1380 * Returns true if the content-type will be rendered as plain-text.
1382 static bool IsPlainTextType(const nsACString& aContentType);
1385 * Returns true iff the type is rendered as plain text and doesn't support
1386 * non-UTF-8 encodings.
1388 static bool IsUtf8OnlyPlainTextType(const nsACString& aContentType);
1391 * Returns true if aDocument belongs to a chrome docshell for
1392 * display purposes. Returns false for null documents or documents
1393 * which do not belong to a docshell.
1395 static bool IsInChromeDocshell(const Document* aDocument);
1398 * Return the content policy service
1400 static nsIContentPolicy* GetContentPolicy();
1403 * Map internal content policy types to external ones.
1405 static inline ExtContentPolicyType InternalContentPolicyTypeToExternal(
1406 nsContentPolicyType aType);
1409 * check whether the Link header field applies to the context resource
1410 * see <http://tools.ietf.org/html/rfc5988#section-5.2>
1412 static bool LinkContextIsURI(const nsAString& aAnchor, nsIURI* aDocURI);
1415 * Returns true if the content policy type is any of:
1416 * * TYPE_INTERNAL_SCRIPT_PRELOAD
1417 * * TYPE_INTERNAL_IMAGE_PRELOAD
1418 * * TYPE_INTERNAL_STYLESHEET_PRELOAD
1420 static bool IsPreloadType(nsContentPolicyType aType);
1423 * Quick helper to determine whether there are any mutation listeners
1424 * of a given type that apply to this content or any of its ancestors.
1425 * The method has the side effect to call document's MayDispatchMutationEvent
1426 * using aTargetForSubtreeModified as the parameter.
1428 * @param aNode The node to search for listeners
1429 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1430 * @param aTargetForSubtreeModified The node which is the target of the
1431 * possible DOMSubtreeModified event.
1433 * @return true if there are mutation listeners of the specified type
1435 static bool HasMutationListeners(nsINode* aNode, uint32_t aType,
1436 nsINode* aTargetForSubtreeModified);
1439 * Quick helper to determine whether there are any mutation listeners
1440 * of a given type that apply to any content in this document. It is valid
1441 * to pass null for aDocument here, in which case this function always
1442 * returns true.
1444 * @param aDocument The document to search for listeners
1445 * @param aType The type of listener (NS_EVENT_BITS_MUTATION_*)
1447 * @return true if there are mutation listeners of the specified type
1449 static bool HasMutationListeners(Document* aDocument, uint32_t aType);
1451 * Synchronously fire DOMNodeRemoved on aChild. Only fires the event if
1452 * there really are listeners by checking using the HasMutationListeners
1453 * function above. The function makes sure to hold the relevant objects alive
1454 * for the duration of the event firing. However there are no guarantees
1455 * that any of the objects are alive by the time the function returns.
1456 * If you depend on that you need to hold references yourself.
1458 * @param aChild The node to fire DOMNodeRemoved at.
1459 * @param aParent The parent of aChild.
1461 MOZ_CAN_RUN_SCRIPT static void MaybeFireNodeRemoved(nsINode* aChild,
1462 nsINode* aParent);
1465 * These methods create and dispatch a trusted event.
1466 * Works only with events which can be created by calling
1467 * Document::CreateEvent() with parameter "Events".
1468 * Note that don't use these methods for "input" event. Use
1469 * DispatchInputEvent() instead.
1471 * @param aDoc The document which will be used to create the event.
1472 * @param aTarget The target of the event.
1473 * @param aEventName The name of the event.
1474 * @param aCanBubble Whether the event can bubble.
1475 * @param aCancelable Is the event cancelable.
1476 * @param aCopmosed Is the event composed.
1477 * @param aDefaultAction Set to true if default action should be taken,
1478 * see EventTarget::DispatchEvent.
1480 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1481 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1482 static nsresult DispatchTrustedEvent(Document* aDoc,
1483 mozilla::dom::EventTarget* aTarget,
1484 const nsAString& aEventName, CanBubble,
1485 Cancelable,
1486 Composed aComposed = Composed::eDefault,
1487 bool* aDefaultAction = nullptr);
1489 // TODO: annotate with `MOZ_CAN_RUN_SCRIPT`
1490 // (https://bugzilla.mozilla.org/show_bug.cgi?id=1625902).
1491 static nsresult DispatchTrustedEvent(Document* aDoc,
1492 mozilla::dom::EventTarget* aTarget,
1493 const nsAString& aEventName,
1494 CanBubble aCanBubble,
1495 Cancelable aCancelable,
1496 bool* aDefaultAction) {
1497 return DispatchTrustedEvent(aDoc, aTarget, aEventName, aCanBubble,
1498 aCancelable, Composed::eDefault,
1499 aDefaultAction);
1503 * This method creates and dispatches a trusted event using an event message.
1504 * @param aDoc The document which will be used to create the event.
1505 * @param aTarget The target of the event.
1506 * @param aEventMessage The event message.
1507 * @param aCanBubble Whether the event can bubble.
1508 * @param aCancelable Is the event cancelable.
1509 * @param aDefaultAction Set to true if default action should be taken,
1510 * see EventTarget::DispatchEvent.
1512 template <class WidgetEventType>
1513 static nsresult DispatchTrustedEvent(
1514 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1515 EventMessage aEventMessage, CanBubble aCanBubble, Cancelable aCancelable,
1516 bool* aDefaultAction = nullptr,
1517 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1518 WidgetEventType event(true, aEventMessage);
1519 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1520 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1521 aCancelable, Trusted::eYes, aDefaultAction,
1522 aOnlyChromeDispatch);
1526 * This method dispatches "beforeinput" event with EditorInputEvent or
1527 * "input" event with proper event class. If it's unsafe to dispatch,
1528 * this put the event into the script runner queue. In such case, the
1529 * event becomes not cancelable even if it's defined as cancelable by
1530 * the spec.
1531 * Input Events spec defines as:
1532 * Input events are dispatched on elements that act as editing hosts,
1533 * including elements with the contenteditable attribute set, textarea
1534 * elements, and input elements that permit text input.
1536 * @param aEventTarget The event target element of the "beforeinput"
1537 * or "input" event. Must not be nullptr.
1538 * @param aEventMessage Muse be eEditorBeforeInput or eEditorInput.
1539 * @param aEditorInputType The inputType value of InputEvent.
1540 * If aEventTarget won't dispatch "input" event
1541 * with InputEvent, set EditorInputType::eUnknown.
1542 * @param aEditorBase Optional. If this is called by editor,
1543 * editor should set this. Otherwise, leave
1544 * nullptr.
1545 * @param aOptions Optional. If aEditorInputType value requires
1546 * some additional data, they should be properly
1547 * set with this argument.
1548 * @param aEventStatus Returns nsEventStatus_eConsumeNoDefault if
1549 * the dispatching event is cancelable and the
1550 * event was canceled by script (including
1551 * chrome script). Otherwise, returns given
1552 * value. Note that this can be nullptr only
1553 * when the dispatching event is not cancelable.
1555 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(Element* aEventTarget);
1556 MOZ_CAN_RUN_SCRIPT static nsresult DispatchInputEvent(
1557 Element* aEventTarget, mozilla::EventMessage aEventMessage,
1558 mozilla::EditorInputType aEditorInputType,
1559 mozilla::EditorBase* aEditorBase, mozilla::InputEventOptions&& aOptions,
1560 nsEventStatus* aEventStatus = nullptr);
1563 * This method creates and dispatches a untrusted event.
1564 * Works only with events which can be created by calling
1565 * Document::CreateEvent() with parameter "Events".
1566 * @param aDoc The document which will be used to create the event.
1567 * @param aTarget The target of the event.
1568 * @param aEventName The name of the event.
1569 * @param aCanBubble Whether the event can bubble.
1570 * @param aCancelable Is the event cancelable.
1571 * @param aDefaultAction Set to true if default action should be taken,
1572 * see EventTarget::DispatchEvent.
1574 static nsresult DispatchUntrustedEvent(Document* aDoc,
1575 mozilla::dom::EventTarget* aTarget,
1576 const nsAString& aEventName, CanBubble,
1577 Cancelable,
1578 bool* aDefaultAction = nullptr);
1581 * This method creates and dispatches a untrusted event using an event
1582 * message.
1583 * @param aDoc The document which will be used to create the event.
1584 * @param aTarget The target of the event.
1585 * @param aEventMessage The event message.
1586 * @param aCanBubble Whether the event can bubble.
1587 * @param aCancelable Is the event cancelable.
1588 * @param aDefaultAction Set to true if default action should be taken,
1589 * see EventTarget::DispatchEvent.
1591 template <class WidgetEventType>
1592 static nsresult DispatchUntrustedEvent(
1593 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1594 EventMessage aEventMessage, CanBubble aCanBubble, Cancelable aCancelable,
1595 bool* aDefaultAction = nullptr,
1596 ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo) {
1597 WidgetEventType event(false, aEventMessage);
1598 MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1599 return DispatchEvent(aDoc, aTarget, event, aEventMessage, aCanBubble,
1600 aCancelable, Trusted::eNo, aDefaultAction,
1601 aOnlyChromeDispatch);
1605 * This method creates and dispatches a trusted event to the chrome
1606 * event handler (the parent object of the DOM Window in the event target
1607 * chain). Note, chrome event handler is used even if aTarget is a chrome
1608 * object. Use DispatchEventOnlyToChrome if the normal event dispatching is
1609 * wanted in case aTarget is a chrome object.
1610 * Works only with events which can be created by calling
1611 * Document::CreateEvent() with parameter "Events".
1612 * @param aDocument The document which will be used to create the event,
1613 * and whose window's chrome handler will be used to
1614 * dispatch the event.
1615 * @param aTarget The target of the event, used for event->SetTarget()
1616 * @param aEventName The name of the event.
1617 * @param aCanBubble Whether the event can bubble.
1618 * @param aCancelable Is the event cancelable.
1619 * @param aDefaultAction Set to true if default action should be taken,
1620 * see EventTarget::DispatchEvent.
1622 static nsresult DispatchChromeEvent(Document* aDoc,
1623 mozilla::dom::EventTarget* aTarget,
1624 const nsAString& aEventName, CanBubble,
1625 Cancelable,
1626 bool* aDefaultAction = nullptr);
1629 * Helper to dispatch a "framefocusrequested" event to chrome, which will only
1630 * bring the window to the foreground and switch tabs if aCanRaise is true.
1632 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void RequestFrameFocus(
1633 Element& aFrameElement, bool aCanRaise,
1634 mozilla::dom::CallerType aCallerType);
1637 * This method creates and dispatches a trusted event.
1638 * If aTarget is not a chrome object, the nearest chrome object in the
1639 * propagation path will be used as the start of the event target chain.
1640 * This method is different than DispatchChromeEvent, which always dispatches
1641 * events to chrome event handler. DispatchEventOnlyToChrome works like
1642 * DispatchTrustedEvent in the case aTarget is a chrome object.
1643 * Works only with events which can be created by calling
1644 * Document::CreateEvent() with parameter "Events".
1645 * @param aDoc The document which will be used to create the event.
1646 * @param aTarget The target of the event.
1647 * @param aEventName The name of the event.
1648 * @param aCanBubble Whether the event can bubble.
1649 * @param aCancelable Is the event cancelable.
1650 * @param aComposed Is the event composed.
1651 * @param aDefaultAction Set to true if default action should be taken,
1652 * see EventTarget::DispatchEvent.
1654 static nsresult DispatchEventOnlyToChrome(
1655 Document* aDoc, mozilla::dom::EventTarget* aTarget,
1656 const nsAString& aEventName, CanBubble, Cancelable,
1657 Composed aComposed = Composed::eDefault, bool* aDefaultAction = nullptr);
1659 static nsresult DispatchEventOnlyToChrome(Document* aDoc,
1660 mozilla::dom::EventTarget* aTarget,
1661 const nsAString& aEventName,
1662 CanBubble aCanBubble,
1663 Cancelable aCancelable,
1664 bool* aDefaultAction) {
1665 return DispatchEventOnlyToChrome(aDoc, aTarget, aEventName, aCanBubble,
1666 aCancelable, Composed::eDefault,
1667 aDefaultAction);
1671 * Determines if an event attribute name (such as onclick) is valid for
1672 * a given element type. Types are from the EventNameType enumeration
1673 * defined above.
1675 * @param aName the event name to look up
1676 * @param aType the type of content
1678 static bool IsEventAttributeName(nsAtom* aName, int32_t aType);
1681 * Return the event message for the event with the given name. The name is
1682 * the event name with the 'on' prefix. Returns eUnidentifiedEvent if the
1683 * event doesn't match a known event name.
1685 * @param aName the event name to look up
1687 static EventMessage GetEventMessage(nsAtom* aName);
1690 * Return the event type atom for a given event message.
1692 static nsAtom* GetEventTypeFromMessage(EventMessage aEventMessage);
1695 * Returns the EventMessage and nsAtom to be used for event listener
1696 * registration.
1698 static EventMessage GetEventMessageAndAtomForListener(const nsAString& aName,
1699 nsAtom** aOnName);
1702 * Return the EventClassID for the event with the given name. The name is the
1703 * event name *without* the 'on' prefix. Returns eBasicEventClass if the event
1704 * is not known to be of any particular event class.
1706 * @param aName the event name to look up
1708 static mozilla::EventClassID GetEventClassID(const nsAString& aName);
1711 * Return the event message and atom for the event with the given name.
1712 * The name is the event name *without* the 'on' prefix.
1713 * Returns eUnidentifiedEvent on the aEventID if the
1714 * event doesn't match a known event name in the category.
1716 * @param aName the event name to look up
1717 * @param aEventClassID only return event id for aEventClassID
1719 static nsAtom* GetEventMessageAndAtom(const nsAString& aName,
1720 mozilla::EventClassID aEventClassID,
1721 EventMessage* aEventMessage);
1724 * Used only during traversal of the XPCOM graph by the cycle
1725 * collector: push a pointer to the listener manager onto the
1726 * children deque, if it exists. Do nothing if there is no listener
1727 * manager.
1729 * Crucially: does not perform any refcounting operations.
1731 * @param aNode The node to traverse.
1732 * @param children The buffer to push a listener manager pointer into.
1734 static void TraverseListenerManager(nsINode* aNode,
1735 nsCycleCollectionTraversalCallback& cb);
1738 * Get the eventlistener manager for aNode, creating it if it does not
1739 * already exist.
1741 * @param aNode The node for which to get the eventlistener manager.
1743 static mozilla::EventListenerManager* GetListenerManagerForNode(
1744 nsINode* aNode);
1746 * Get the eventlistener manager for aNode, returning null if it does not
1747 * already exist.
1749 * @param aNode The node for which to get the eventlistener manager.
1751 static mozilla::EventListenerManager* GetExistingListenerManagerForNode(
1752 const nsINode* aNode);
1754 static void AddEntryToDOMArenaTable(nsINode* aNode,
1755 mozilla::dom::DOMArena* aDOMArena);
1757 static already_AddRefed<mozilla::dom::DOMArena> TakeEntryFromDOMArenaTable(
1758 const nsINode* aNode);
1760 static void UnmarkGrayJSListenersInCCGenerationDocuments();
1763 * Remove the eventlistener manager for aNode.
1765 * @param aNode The node for which to remove the eventlistener manager.
1767 static void RemoveListenerManager(nsINode* aNode);
1769 static bool IsInitialized() { return sInitialized; }
1772 * Checks if the localname/prefix/namespace triple is valid wrt prefix
1773 * and namespace according to the Namespaces in XML and DOM Code
1774 * specfications.
1776 * @param aLocalname localname of the node
1777 * @param aPrefix prefix of the node
1778 * @param aNamespaceID namespace of the node
1780 static bool IsValidNodeName(nsAtom* aLocalName, nsAtom* aPrefix,
1781 int32_t aNamespaceID);
1784 * Creates a DocumentFragment from text using a context node to resolve
1785 * namespaces.
1787 * Please note that for safety reasons, if the node principal of
1788 * aContextNode is the system principal, this function will automatically
1789 * sanitize its input using nsTreeSanitizer.
1791 * Note! In the HTML case with the HTML5 parser enabled, this is only called
1792 * from Range.createContextualFragment() and the implementation here is
1793 * quirky accordingly (html context node behaves like a body context node).
1794 * If you don't want that quirky behavior, don't use this method as-is!
1796 * @param aContextNode the node which is used to resolve namespaces
1797 * @param aFragment the string which is parsed to a DocumentFragment
1798 * @param aReturn the resulting fragment
1799 * @param aPreventScriptExecution whether to mark scripts as already started
1801 static already_AddRefed<mozilla::dom::DocumentFragment>
1802 CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment,
1803 bool aPreventScriptExecution,
1804 mozilla::ErrorResult& aRv);
1807 * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
1809 * Please note that for safety reasons, if the node principal of aTargetNode
1810 * is the system principal, this function will automatically sanitize its
1811 * input using nsTreeSanitizer.
1813 * @param aSourceBuffer the string being set as innerHTML
1814 * @param aTargetNode the target container
1815 * @param aContextLocalName local name of context node
1816 * @param aContextNamespace namespace of context node
1817 * @param aQuirks true to make <table> not close <p>
1818 * @param aPreventScriptExecution true to prevent scripts from executing;
1819 * don't set to false when parsing into a target node that has been
1820 * bound to tree.
1821 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1822 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1823 * long and NS_OK otherwise.
1824 * @param aFlags defaults to -1 indicating that ParseFragmentHTML will do
1825 * default sanitization for system privileged calls to it. Only
1826 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1827 * which will then used for sanitization of the fragment.
1828 * To pass explicit aFlags use any of the sanitization flags
1829 * listed in nsIParserUtils.idl.
1831 static nsresult ParseFragmentHTML(const nsAString& aSourceBuffer,
1832 nsIContent* aTargetNode,
1833 nsAtom* aContextLocalName,
1834 int32_t aContextNamespace, bool aQuirks,
1835 bool aPreventScriptExecution,
1836 int32_t aFlags = -1);
1839 * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
1841 * Please note that for safety reasons, if the node principal of aDocument
1842 * is the system principal, this function will automatically sanitize its
1843 * input using nsTreeSanitizer.
1845 * @param aSourceBuffer the string being set as innerHTML
1846 * @param aDocument the target document
1847 * @param aTagStack the namespace mapping context
1848 * @param aPreventExecution whether to mark scripts as already started
1849 * @param aFlags, pass -1 and ParseFragmentXML will do default
1850 * sanitization for system privileged calls to it. Only
1851 * ParserUtils::ParseFragment() should ever pass explicit aFlags
1852 * which will then used for sanitization of the fragment.
1853 * To pass explicit aFlags use any of the sanitization flags
1854 * listed in nsIParserUtils.idl.
1855 * @param aReturn the result fragment
1856 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1857 * fragments is made, a return code from the XML parser.
1859 static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
1860 Document* aDocument,
1861 nsTArray<nsString>& aTagStack,
1862 bool aPreventScriptExecution, int32_t aFlags,
1863 mozilla::dom::DocumentFragment** aReturn);
1866 * Parse a string into a document using the HTML parser.
1867 * Script elements are marked unexecutable.
1869 * @param aSourceBuffer the string to parse as an HTML document
1870 * @param aTargetDocument the document object to parse into. Must not have
1871 * child nodes.
1872 * @param aScriptingEnabledForNoscriptParsing whether <noscript> is parsed
1873 * as if scripting was enabled
1874 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1875 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1876 * long and NS_OK otherwise.
1878 static nsresult ParseDocumentHTML(const nsAString& aSourceBuffer,
1879 Document* aTargetDocument,
1880 bool aScriptingEnabledForNoscriptParsing);
1883 * Converts HTML source to plain text by parsing the source and using the
1884 * plain text serializer on the resulting tree.
1886 * @param aSourceBuffer the string to parse as an HTML document
1887 * @param aResultBuffer the string where the plain text result appears;
1888 * may be the same string as aSourceBuffer
1889 * @param aFlags Flags from nsIDocumentEncoder.
1890 * @param aWrapCol Number of columns after which to line wrap; 0 for no
1891 * auto-wrapping
1892 * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1893 * fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1894 * long and NS_OK otherwise.
1896 static nsresult ConvertToPlainText(const nsAString& aSourceBuffer,
1897 nsAString& aResultBuffer, uint32_t aFlags,
1898 uint32_t aWrapCol);
1901 * Creates a 'loaded-as-data' HTML document that takes that principal,
1902 * script global, and URL from the argument, which may be null.
1904 static already_AddRefed<Document> CreateInertHTMLDocument(
1905 const Document* aTemplate);
1908 * Creates a 'loaded-as-data' XML document that takes that principal,
1909 * script global, and URL from the argument, which may be null.
1911 static already_AddRefed<Document> CreateInertXMLDocument(
1912 const Document* aTemplate);
1914 public:
1916 * Sets the text contents of a node by replacing all existing children
1917 * with a single text child.
1919 * The function always notifies.
1921 * Will reuse the first text child if one is available. Will not reuse
1922 * existing cdata children.
1924 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1926 * @param aContent Node to set contents of.
1927 * @param aValue Value to set contents to.
1928 * @param aTryReuse When true, the function will try to reuse an existing
1929 * textnodes rather than always creating a new one.
1931 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult SetNodeTextContent(
1932 nsIContent* aContent, const nsAString& aValue, bool aTryReuse);
1935 * Get the textual contents of a node. This is a concatenation of all
1936 * textnodes that are direct or (depending on aDeep) indirect children
1937 * of the node.
1939 * NOTE! No serialization takes place and <br> elements
1940 * are not converted into newlines. Only textnodes and cdata nodes are
1941 * added to the result.
1943 * @see nsLayoutUtils::GetFrameTextContent
1945 * @param aNode Node to get textual contents of.
1946 * @param aDeep If true child elements of aNode are recursivly descended
1947 * into to find text children.
1948 * @param aResult the result. Out param.
1949 * @return false on out of memory errors, true otherwise.
1951 [[nodiscard]] static bool GetNodeTextContent(const nsINode* aNode, bool aDeep,
1952 nsAString& aResult,
1953 const mozilla::fallible_t&);
1955 static void GetNodeTextContent(const nsINode* aNode, bool aDeep,
1956 nsAString& aResult);
1959 * Same as GetNodeTextContents but appends the result rather than sets it.
1961 static bool AppendNodeTextContent(const nsINode* aNode, bool aDeep,
1962 nsAString& aResult,
1963 const mozilla::fallible_t&);
1966 * Utility method that checks if a given node has any non-empty children. This
1967 * method does not descend recursively into children by default.
1969 * @param aDiscoverMode Set to eRecurseIntoChildren to descend recursively
1970 * into children.
1972 enum TextContentDiscoverMode : uint8_t {
1973 eRecurseIntoChildren,
1974 eDontRecurseIntoChildren
1977 static bool HasNonEmptyTextContent(
1978 nsINode* aNode,
1979 TextContentDiscoverMode aDiscoverMode = eDontRecurseIntoChildren);
1982 * Delete strings allocated for nsContentList matches
1984 static void DestroyMatchString(void* aData);
1987 * Notify when the first XUL menu is opened and when the all XUL menus are
1988 * closed. At opening, aInstalling should be TRUE, otherwise, it should be
1989 * FALSE.
1991 MOZ_CAN_RUN_SCRIPT static void NotifyInstalledMenuKeyboardListener(
1992 bool aInstalling);
1995 * Check whether the nsIURI uses the given scheme.
1997 * Note that this will check the innermost URI rather than that of
1998 * the nsIURI itself.
2000 static bool SchemeIs(nsIURI* aURI, const char* aScheme);
2003 * Returns true if aPrincipal is an ExpandedPrincipal.
2005 static bool IsExpandedPrincipal(nsIPrincipal* aPrincipal);
2008 * Returns true if aPrincipal is the system or an ExpandedPrincipal.
2010 static bool IsSystemOrExpandedPrincipal(nsIPrincipal* aPrincipal);
2013 * Gets the system principal from the security manager.
2015 static nsIPrincipal* GetSystemPrincipal();
2018 * Gets the null subject principal singleton. This is only useful for
2019 * assertions.
2021 static nsIPrincipal* GetNullSubjectPrincipal() {
2022 return sNullSubjectPrincipal;
2026 * *aResourcePrincipal is a principal describing who may access the contents
2027 * of a resource. The resource can only be consumed by a principal that
2028 * subsumes *aResourcePrincipal. MAKE SURE THAT NOTHING EVER ACTS WITH THE
2029 * AUTHORITY OF *aResourcePrincipal.
2030 * It may be null to indicate that the resource has no data from any origin
2031 * in it yet and anything may access the resource.
2032 * Additional data is being mixed into the resource from aExtraPrincipal
2033 * (which may be null; if null, no data is being mixed in and this function
2034 * will do nothing). Update *aResourcePrincipal to reflect the new data.
2035 * If *aResourcePrincipal subsumes aExtraPrincipal, nothing needs to change,
2036 * otherwise *aResourcePrincipal is replaced with the system principal.
2037 * Returns true if *aResourcePrincipal changed.
2039 static bool CombineResourcePrincipals(
2040 nsCOMPtr<nsIPrincipal>* aResourcePrincipal,
2041 nsIPrincipal* aExtraPrincipal);
2044 * Trigger a link with uri aLinkURI. If aClick is false, this triggers a
2045 * mouseover on the link, otherwise it triggers a load after doing a
2046 * security check using aContent's principal.
2048 * @param aContent the node on which a link was triggered.
2049 * @param aLinkURI the URI of the link, must be non-null.
2050 * @param aTargetSpec the target (like target=, may be empty).
2051 * @param aClick whether this was a click or not (if false, this method
2052 * assumes you just hovered over the link).
2053 * @param aIsTrusted If false, JS Context will be pushed to stack
2054 * when the link is triggered.
2056 static void TriggerLink(nsIContent* aContent, nsIURI* aLinkURI,
2057 const nsString& aTargetSpec, bool aClick,
2058 bool aIsTrusted);
2061 * Get the link location.
2063 static void GetLinkLocation(mozilla::dom::Element* aElement,
2064 nsString& aLocationString);
2067 * Return top-level widget in the parent chain.
2069 static nsIWidget* GetTopLevelWidget(nsIWidget* aWidget);
2072 * Return the localized ellipsis for UI.
2074 static const nsDependentString GetLocalizedEllipsis();
2077 * Hide any XUL popups associated with aDocument, including any documents
2078 * displayed in child frames. Does nothing if aDocument is null.
2080 MOZ_CAN_RUN_SCRIPT_BOUNDARY static void HidePopupsInDocument(
2081 Document* aDocument);
2084 * Retrieve the current drag session, or null if no drag is currently occuring
2086 static already_AddRefed<nsIDragSession> GetDragSession();
2089 * Initialize and set the dataTransfer field of an WidgetDragEvent.
2091 static nsresult SetDataTransferInEvent(mozilla::WidgetDragEvent* aDragEvent);
2093 // filters the drag and drop action to fit within the effects allowed and
2094 // returns it.
2095 static uint32_t FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed);
2098 * Return true if the target of a drop event is a content document that is
2099 * an ancestor of the document for the source of the drag.
2101 static bool CheckForSubFrameDrop(nsIDragSession* aDragSession,
2102 mozilla::WidgetDragEvent* aDropEvent);
2105 * Return true if aURI is a local file URI (i.e. file://).
2107 static bool URIIsLocalFile(nsIURI* aURI);
2110 * Get the application manifest URI for this document. The manifest URI
2111 * is specified in the manifest= attribute of the root element of the
2112 * document.
2114 * @param aDocument The document that lists the manifest.
2115 * @param aURI The manifest URI.
2117 static void GetOfflineAppManifest(Document* aDocument, nsIURI** aURI);
2120 * Check whether an application should be allowed to use offline APIs.
2122 static bool OfflineAppAllowed(nsIURI* aURI);
2125 * Check whether an application should be allowed to use offline APIs.
2127 static bool OfflineAppAllowed(nsIPrincipal* aPrincipal);
2130 * Increases the count of blockers preventing scripts from running.
2131 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2132 * this directly
2134 static void AddScriptBlocker();
2137 * Decreases the count of blockers preventing scripts from running.
2138 * NOTE: You might want to use nsAutoScriptBlocker rather than calling
2139 * this directly
2141 * WARNING! Calling this function could synchronously execute scripts.
2143 static void RemoveScriptBlocker();
2146 * Add a runnable that is to be executed as soon as it's safe to execute
2147 * scripts.
2148 * NOTE: If it's currently safe to execute scripts, aRunnable will be run
2149 * synchronously before the function returns.
2151 * @param aRunnable The nsIRunnable to run as soon as it's safe to execute
2152 * scripts. Passing null is allowed and results in nothing
2153 * happening. It is also allowed to pass an object that
2154 * has not yet been AddRefed.
2156 static void AddScriptRunner(already_AddRefed<nsIRunnable> aRunnable);
2157 static void AddScriptRunner(nsIRunnable* aRunnable);
2160 * Returns true if it's safe to execute content script and false otherwise.
2162 * The only known case where this lies is mutation events. They run, and can
2163 * run anything else, when this function returns false, but this is ok.
2165 static bool IsSafeToRunScript();
2167 // Returns the browser window with the most recent time stamp that is
2168 // not in private browsing mode.
2169 static already_AddRefed<nsPIDOMWindowOuter> GetMostRecentNonPBWindow();
2172 * Call this function if !IsSafeToRunScript() and we fail to run the script
2173 * (rather than using AddScriptRunner as we usually do). |aDocument| is
2174 * optional as it is only used for showing the URL in the console.
2176 static void WarnScriptWasIgnored(Document* aDocument);
2179 * Add a "synchronous section", in the form of an nsIRunnable run once the
2180 * event loop has reached a "stable state". |aRunnable| must not cause any
2181 * queued events to be processed (i.e. must not spin the event loop).
2182 * We've reached a stable state when the currently executing task/event has
2183 * finished, see
2184 * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#synchronous-section
2185 * In practice this runs aRunnable once the currently executing event
2186 * finishes. If called multiple times per task/event, all the runnables will
2187 * be executed, in the order in which RunInStableState() was called.
2189 static void RunInStableState(already_AddRefed<nsIRunnable> aRunnable);
2191 /* Add a pending IDBTransaction to be cleaned up at the end of performing a
2192 * microtask checkpoint.
2193 * See the step of "Cleanup Indexed Database Transactions" in
2194 * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
2196 static void AddPendingIDBTransaction(
2197 already_AddRefed<nsIRunnable> aTransaction);
2200 * Returns true if we are doing StableState/MetastableState.
2202 static bool IsInStableOrMetaStableState();
2204 static JSContext* GetCurrentJSContext();
2207 * Case insensitive comparison between two atoms.
2209 static bool EqualsIgnoreASCIICase(nsAtom* aAtom1, nsAtom* aAtom2);
2212 * Case insensitive comparison between two strings. However it only ignores
2213 * case for ASCII characters a-z.
2215 static bool EqualsIgnoreASCIICase(const nsAString& aStr1,
2216 const nsAString& aStr2);
2219 * Convert ASCII A-Z to a-z.
2221 static void ASCIIToLower(nsAString& aStr);
2222 static void ASCIIToLower(nsACString& aStr);
2223 static void ASCIIToLower(const nsAString& aSource, nsAString& aDest);
2224 static void ASCIIToLower(const nsACString& aSource, nsACString& aDest);
2227 * Convert ASCII a-z to A-Z.
2229 static void ASCIIToUpper(nsAString& aStr);
2230 static void ASCIIToUpper(nsACString& aStr);
2231 static void ASCIIToUpper(const nsAString& aSource, nsAString& aDest);
2232 static void ASCIIToUpper(const nsACString& aSource, nsACString& aDest);
2235 * Return whether aStr contains an ASCII uppercase character.
2237 static bool StringContainsASCIIUpper(const nsAString& aStr);
2239 // Returns NS_OK for same origin, error (NS_ERROR_DOM_BAD_URI) if not.
2240 static nsresult CheckSameOrigin(nsIChannel* aOldChannel,
2241 nsIChannel* aNewChannel);
2242 static nsIInterfaceRequestor* SameOriginChecker();
2245 * Returns an ASCII compatible serialization of the nsIPrincipal or nsIURI's
2246 * origin, as specified by the whatwg HTML specification. If the principal
2247 * does not have a host, the origin will be "null".
2249 * https://html.spec.whatwg.org/multipage/browsers.html#ascii-serialisation-of-an-origin
2251 * Note that this is different from nsIPrincipal::GetOrigin, does not contain
2252 * gecko-specific metadata like origin attributes, and should not be used for
2253 * permissions or security checks.
2255 * See also `nsIPrincipal::GetWebExposedOriginSerialization`.
2257 * These methods are thread-safe.
2259 * @pre aPrincipal/aURI must not be null.
2261 * @note this should be used for HTML5 origin determination.
2263 static nsresult GetWebExposedOriginSerialization(nsIURI* aURI,
2264 nsACString& aOrigin);
2265 static nsresult GetWebExposedOriginSerialization(nsIPrincipal* aPrincipal,
2266 nsAString& aOrigin);
2267 static nsresult GetWebExposedOriginSerialization(nsIURI* aURI,
2268 nsAString& aOrigin);
2271 * This method creates and dispatches "command" event, which implements
2272 * XULCommandEvent.
2273 * If aPresShell is not null, dispatching goes via
2274 * PresShell::HandleDOMEventWithTarget().
2276 MOZ_CAN_RUN_SCRIPT
2277 static nsresult DispatchXULCommand(
2278 nsIContent* aTarget, bool aTrusted,
2279 mozilla::dom::Event* aSourceEvent = nullptr,
2280 mozilla::PresShell* aPresShell = nullptr, bool aCtrl = false,
2281 bool aAlt = false, bool aShift = false, bool aMeta = false,
2282 // Including MouseEventBinding here leads
2283 // to incude loops, unfortunately.
2284 uint16_t inputSource = 0 /* MouseEvent_Binding::MOZ_SOURCE_UNKNOWN */,
2285 int16_t aButton = 0);
2287 static bool CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel,
2288 bool aAllowIfInheritsPrincipal);
2291 * The method checks whether the caller can access native anonymous content.
2292 * If there is no JS in the stack or privileged JS is running, this
2293 * method returns true, otherwise false.
2295 static bool CanAccessNativeAnon();
2297 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2298 const nsIID* aIID,
2299 JS::MutableHandle<JS::Value> vp,
2300 bool aAllowWrapping = true) {
2301 return WrapNative(cx, native, nullptr, aIID, vp, aAllowWrapping);
2304 // Same as the WrapNative above, but use this one if aIID is nsISupports' IID.
2305 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2306 JS::MutableHandle<JS::Value> vp,
2307 bool aAllowWrapping = true) {
2308 return WrapNative(cx, native, nullptr, nullptr, vp, aAllowWrapping);
2311 [[nodiscard]] static nsresult WrapNative(JSContext* cx, nsISupports* native,
2312 nsWrapperCache* cache,
2313 JS::MutableHandle<JS::Value> vp,
2314 bool aAllowWrapping = true) {
2315 return WrapNative(cx, native, cache, nullptr, vp, aAllowWrapping);
2319 * Creates an arraybuffer from a binary string.
2321 static nsresult CreateArrayBuffer(JSContext* aCx, const nsACString& aData,
2322 JSObject** aResult);
2324 static void StripNullChars(const nsAString& aInStr, nsAString& aOutStr);
2327 * Strip all \n, \r and nulls from the given string
2328 * @param aString the string to remove newlines from [in/out]
2330 static void RemoveNewlines(nsString& aString);
2333 * Convert Windows and Mac platform linebreaks to \n.
2334 * @param aString the string to convert the newlines inside [in/out]
2336 static void PlatformToDOMLineBreaks(nsString& aString);
2337 [[nodiscard]] static bool PlatformToDOMLineBreaks(nsString& aString,
2338 const mozilla::fallible_t&);
2341 * Populates aResultString with the contents of the string-buffer aBuf, up
2342 * to aBuf's null-terminator. aBuf must not be null. Ownership of the string
2343 * is not transferred.
2345 static void PopulateStringFromStringBuffer(nsStringBuffer* aBuf,
2346 nsAString& aResultString);
2348 static bool IsHandlingKeyBoardEvent() { return sIsHandlingKeyBoardEvent; }
2350 static void SetIsHandlingKeyBoardEvent(bool aHandling) {
2351 sIsHandlingKeyBoardEvent = aHandling;
2355 * Utility method for getElementsByClassName. aRootNode is the node (either
2356 * document or element), which getElementsByClassName was called on.
2358 static already_AddRefed<nsContentList> GetElementsByClassName(
2359 nsINode* aRootNode, const nsAString& aClasses);
2362 * Returns a presshell for this document, if there is one. This will be
2363 * aDoc's direct presshell if there is one, otherwise we'll look at all
2364 * ancestor documents to try to find a presshell, so for example this can
2365 * still find a presshell for documents in display:none frames that have
2366 * no presentation. So you have to be careful how you use this presshell ---
2367 * getting generic data like a device context or widget from it is OK, but it
2368 * might not be this document's actual presentation.
2370 static mozilla::PresShell* FindPresShellForDocument(
2371 const Document* aDocument);
2374 * Like FindPresShellForDocument, but returns the shell's PresContext instead.
2376 static nsPresContext* FindPresContextForDocument(const Document* aDocument);
2379 * Returns the widget for this document if there is one. Looks at all ancestor
2380 * documents to try to find a widget, so for example this can still find a
2381 * widget for documents in display:none frames that have no presentation.
2383 * You should probably use WidgetForContent() instead of this, unless you have
2384 * a good reason to do otherwise.
2386 static nsIWidget* WidgetForDocument(const Document* aDocument);
2389 * Returns the appropriate widget for this element, if there is one. Unlike
2390 * WidgetForDocument(), this returns the correct widget for content in popups.
2392 * You should probably use this instead of WidgetForDocument().
2394 static nsIWidget* WidgetForContent(const nsIContent* aContent);
2397 * Returns a window renderer to use for the given document. Basically we
2398 * look up the document hierarchy for the first document which has
2399 * a presentation with an associated widget, and use that widget's
2400 * window renderer.
2402 * You should probably use WindowRendererForContent() instead of this, unless
2403 * you have a good reason to do otherwise.
2405 * @param aDoc the document for which to return a window renderer.
2406 * @param aAllowRetaining an outparam that states whether the returned
2407 * layer manager should be used for retained layers
2409 static mozilla::WindowRenderer* WindowRendererForDocument(
2410 const Document* aDoc);
2413 * Returns a window renderer to use for the given content. Unlike
2414 * WindowRendererForDocument(), this returns the correct window renderer for
2415 * content in popups.
2417 * You should probably use this instead of WindowRendererForDocument().
2419 static mozilla::WindowRenderer* WindowRendererForContent(
2420 const nsIContent* aContent);
2423 * Determine whether a content node is focused or not,
2425 * @param aContent the content node to check
2426 * @return true if the content node is focused, false otherwise.
2428 static bool IsFocusedContent(const nsIContent* aContent);
2431 * Returns true if calling execCommand with 'cut' or 'copy' arguments is
2432 * allowed for the given subject principal. These are only allowed if the user
2433 * initiated them (like with a mouse-click or key press).
2435 static bool IsCutCopyAllowed(Document* aDocument,
2436 nsIPrincipal& aSubjectPrincipal);
2439 * Returns true if CSSOM origin check should be skipped for WebDriver
2440 * based crawl to be able to collect data from cross-origin CSS style
2441 * sheets. This can be enabled by setting environment variable
2442 * MOZ_BYPASS_CSSOM_ORIGIN_CHECK.
2444 static bool BypassCSSOMOriginCheck() {
2445 #ifdef RELEASE_OR_BETA
2446 return false;
2447 #else
2448 return sBypassCSSOMOriginCheck;
2449 #endif
2453 * Fire mutation events for changes caused by parsing directly into a
2454 * context node.
2456 * @param aDoc the document of the node
2457 * @param aDest the destination node that got stuff appended to it
2458 * @param aOldChildCount the number of children the node had before parsing
2460 static void FireMutationEventsForDirectParsing(Document* aDoc,
2461 nsIContent* aDest,
2462 int32_t aOldChildCount);
2465 * Returns the in-process subtree root document in a document hierarchy.
2466 * This could be a chrome document.
2468 static Document* GetInProcessSubtreeRootDocument(Document* aDoc) {
2469 return const_cast<Document*>(
2470 GetInProcessSubtreeRootDocument(const_cast<const Document*>(aDoc)));
2472 static const Document* GetInProcessSubtreeRootDocument(const Document* aDoc);
2474 static void GetShiftText(nsAString& text);
2475 static void GetControlText(nsAString& text);
2476 static void GetCommandOrWinText(nsAString& text);
2477 static void GetAltText(nsAString& text);
2478 static void GetModifierSeparatorText(nsAString& text);
2481 * Returns if aContent has the 'scrollgrab' property.
2482 * aContent may be null (in this case false is returned).
2484 static bool HasScrollgrab(nsIContent* aContent);
2487 * Flushes the layout tree (recursively)
2489 * @param aWindow the window the flush should start at
2492 static void FlushLayoutForTree(nsPIDOMWindowOuter* aWindow);
2495 * Returns true if content with the given principal is allowed to use XUL
2496 * and XBL and false otherwise.
2498 static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
2501 * Perform cleanup that's appropriate for XPCOM shutdown.
2503 static void XPCOMShutdown();
2506 * Checks if internal PDF viewer is enabled.
2508 static bool IsPDFJSEnabled();
2511 * Checks to see whether the given principal is the internal PDF
2512 * viewer principal.
2514 static bool IsPDFJS(nsIPrincipal* aPrincipal);
2516 * Same, but from WebIDL bindings. Checks whether the subject principal is for
2517 * the internal PDF viewer or system JS.
2519 static bool IsSystemOrPDFJS(JSContext*, JSObject*);
2522 * Checks if internal SWF player is enabled.
2524 static bool IsSWFPlayerEnabled();
2526 enum ContentViewerType {
2527 TYPE_UNSUPPORTED,
2528 TYPE_CONTENT,
2529 TYPE_FALLBACK,
2530 TYPE_UNKNOWN
2533 static already_AddRefed<nsIDocumentLoaderFactory> FindInternalContentViewer(
2534 const nsACString& aType, ContentViewerType* aLoaderType = nullptr);
2537 * This helper method returns true if the aPattern pattern matches aValue.
2538 * aPattern should not contain leading and trailing slashes (/).
2539 * The pattern has to match the entire value not just a subset.
2540 * aDocument must be a valid pointer (not null).
2542 * This is following the HTML5 specification:
2543 * http://dev.w3.org/html5/spec/forms.html#attr-input-pattern
2545 * WARNING: This method mutates aPattern!
2547 * @param aValue the string to check.
2548 * @param aPattern the string defining the pattern.
2549 * @param aDocument the owner document of the element.
2550 * @param aHasMultiple whether or not there are multiple values.
2551 * @param aFlags the flags to use for creating the regexp object.
2552 * @result whether the given string is matches the pattern, or
2553 * Nothing() if the pattern couldn't be evaluated.
2555 static mozilla::Maybe<bool> IsPatternMatching(
2556 const nsAString& aValue, nsString&& aPattern, const Document* aDocument,
2557 bool aHasMultiple = false,
2558 JS::RegExpFlags aFlags = JS::RegExpFlag::UnicodeSets);
2561 * Calling this adds support for
2562 * ontouch* event handler DOM attributes.
2564 static void InitializeTouchEventTable();
2567 * Test whether the given URI always inherits a security context
2568 * from the document it comes from.
2570 static nsresult URIInheritsSecurityContext(nsIURI* aURI, bool* aResult);
2573 * Called before a channel is created to query whether the new
2574 * channel should inherit the principal.
2576 * The argument aLoadingPrincipal must not be null. The argument
2577 * aURI must be the URI of the new channel. If aInheritForAboutBlank
2578 * is true, then about:blank will be told to inherit the principal.
2579 * If aForceInherit is true, the new channel will be told to inherit
2580 * the principal no matter what.
2582 * The return value is whether the new channel should inherit
2583 * the principal.
2585 static bool ChannelShouldInheritPrincipal(nsIPrincipal* aLoadingPrincipal,
2586 nsIURI* aURI,
2587 bool aInheritForAboutBlank,
2588 bool aForceInherit);
2590 static nsresult Btoa(const nsAString& aBinaryData,
2591 nsAString& aAsciiBase64String);
2593 static nsresult Atob(const nsAString& aAsciiString, nsAString& aBinaryData);
2596 * Returns whether the input element passed in parameter has the autocomplete
2597 * functionality enabled. It is taking into account the form owner.
2598 * NOTE: the caller has to make sure autocomplete makes sense for the
2599 * element's type.
2601 * @param aInput the input element to check. NOTE: aInput can't be null.
2602 * @return whether the input element has autocomplete enabled.
2604 static bool IsAutocompleteEnabled(mozilla::dom::HTMLInputElement* aInput);
2606 enum AutocompleteAttrState : uint8_t {
2607 eAutocompleteAttrState_Unknown = 1,
2608 eAutocompleteAttrState_Invalid,
2609 eAutocompleteAttrState_Valid,
2612 * Parses the value of the autocomplete attribute into aResult, ensuring it's
2613 * composed of valid tokens, otherwise the value "" is used.
2614 * Note that this method is used for form fields, not on a <form> itself.
2616 * @return whether aAttr was valid and can be cached.
2618 static AutocompleteAttrState SerializeAutocompleteAttribute(
2619 const nsAttrValue* aAttr, nsAString& aResult,
2620 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown);
2622 /* Variation that is used to retrieve a dictionary of the parts of the
2623 * autocomplete attribute.
2625 * @return whether aAttr was valid and can be cached.
2627 static AutocompleteAttrState SerializeAutocompleteAttribute(
2628 const nsAttrValue* aAttr, mozilla::dom::AutocompleteInfo& aInfo,
2629 AutocompleteAttrState aCachedState = eAutocompleteAttrState_Unknown,
2630 bool aGrantAllValidValue = false);
2633 * This will parse aSource, to extract the value of the pseudo attribute
2634 * with the name specified in aName. See
2635 * http://www.w3.org/TR/xml-stylesheet/#NT-StyleSheetPI for the specification
2636 * which is used to parse aSource.
2638 * @param aSource the string to parse
2639 * @param aName the name of the attribute to get the value for
2640 * @param aValue [out] the value for the attribute with name specified in
2641 * aAttribute. Empty if the attribute isn't present.
2642 * @return true if the attribute exists and was successfully parsed.
2643 * false if the attribute doesn't exist, or has a malformed
2644 * value, such as an unknown or unterminated entity.
2646 static bool GetPseudoAttributeValue(const nsString& aSource, nsAtom* aName,
2647 nsAString& aValue);
2650 * Returns true if the language name is a version of JavaScript and
2651 * false otherwise
2653 static bool IsJavaScriptLanguage(const nsString& aName);
2655 static bool IsJavascriptMIMEType(const nsAString& aMIMEType);
2657 static void SplitMimeType(const nsAString& aValue, nsString& aType,
2658 nsString& aParams);
2661 * Takes a selection, and a text control element (<input> or <textarea>), and
2662 * returns the offsets in the text content corresponding to the selection.
2663 * The selection's anchor and focus must both be in the root node passed or a
2664 * descendant.
2666 * @param aSelection Selection to check
2667 * @param aRoot Root <input> or <textarea> element
2668 * @param aOutStartOffset Output start offset
2669 * @param aOutEndOffset Output end offset
2671 static void GetSelectionInTextControl(mozilla::dom::Selection* aSelection,
2672 Element* aRoot,
2673 uint32_t& aOutStartOffset,
2674 uint32_t& aOutEndOffset);
2677 * Takes a frame for anonymous content within a text control (<input> or
2678 * <textarea>), and returns an offset in the text content, adjusted for a
2679 * trailing <br> frame.
2681 * @param aOffsetFrame Frame for the text content in which the offset
2682 * lies
2683 * @param aOffset Offset as calculated by GetContentOffsetsFromPoint
2684 * @param aOutOffset Output adjusted offset
2686 * @see GetSelectionInTextControl for the original basis of this function.
2688 static int32_t GetAdjustedOffsetInTextControl(nsIFrame* aOffsetFrame,
2689 int32_t aOffset);
2692 * Returns pointer to HTML editor instance for the aPresContext when there is.
2693 * The HTML editor is shared by contenteditable elements or used in
2694 * designMode. When there are no contenteditable elements and the document
2695 * is not in designMode, this returns nullptr.
2697 static mozilla::HTMLEditor* GetHTMLEditor(nsPresContext* aPresContext);
2698 static mozilla::HTMLEditor* GetHTMLEditor(nsDocShell* aDocShell);
2701 * Returns pointer to a text editor if <input> or <textarea> element is
2702 * active element in the document for aPresContext, or pointer to HTML
2703 * editor if there is (i.e., even if non-editable element has focus or
2704 * nobody has focus). The reason is, HTML editor may handle some input
2705 * even if there is no active editing host.
2706 * Note that this does not return editor in descendant documents.
2708 static mozilla::EditorBase* GetActiveEditor(nsPresContext* aPresContext);
2709 static mozilla::EditorBase* GetActiveEditor(nsPIDOMWindowOuter* aWindow);
2712 * Returns `TextEditor` which manages `aAnonymousContent` if there is.
2713 * Note that this method returns `nullptr` if `TextEditor` for the
2714 * `aAnonymousContent` hasn't been created yet.
2716 static mozilla::TextEditor* GetTextEditorFromAnonymousNodeWithoutCreation(
2717 const nsIContent* aAnonymousContent);
2720 * Returns whether a node has an editable ancestor.
2722 * @param aNode The node to test.
2724 static bool IsNodeInEditableRegion(nsINode* aNode);
2727 * Returns a LogModule that logs debugging info from RFP functions.
2729 static mozilla::LogModule* ResistFingerprintingLog();
2732 * Returns a LogModule that dump calls from content script are logged to.
2733 * This can be enabled with the 'Dump' module, and is useful for synchronizing
2734 * content JS to other logging modules.
2736 static mozilla::LogModule* DOMDumpLog();
2739 * Returns whether a given header is forbidden for an XHR or fetch
2740 * request.
2742 static bool IsForbiddenRequestHeader(const nsACString& aHeader,
2743 const nsACString& aValue);
2746 * Returns whether a given header is forbidden for a system XHR
2747 * request.
2749 static bool IsForbiddenSystemRequestHeader(const nsACString& aHeader);
2752 * Checks whether the header overrides any http methods
2754 static bool IsOverrideMethodHeader(const nsACString& headerName);
2756 * Checks whether the header value contains any forbidden method
2758 static bool ContainsForbiddenMethod(const nsACString& headerValue);
2760 class ParsedRange {
2761 public:
2762 explicit ParsedRange(mozilla::Maybe<uint64_t> aStart,
2763 mozilla::Maybe<uint64_t> aEnd)
2764 : mStart(aStart), mEnd(aEnd) {}
2766 mozilla::Maybe<uint64_t> Start() const { return mStart; }
2767 mozilla::Maybe<uint64_t> End() const { return mEnd; }
2769 bool operator==(const ParsedRange& aOther) const {
2770 return Start() == aOther.Start() && End() == aOther.End();
2773 private:
2774 mozilla::Maybe<uint64_t> mStart;
2775 mozilla::Maybe<uint64_t> mEnd;
2779 * Parse a single range request and return a pair containing the resulting
2780 * start and end of the range.
2782 * See https://fetch.spec.whatwg.org/#simple-range-header-value
2784 static mozilla::Maybe<ParsedRange> ParseSingleRangeRequest(
2785 const nsACString& aHeaderValue, bool aAllowWhitespace);
2788 * Returns whether a given header has characters that aren't permitted
2790 static bool IsCorsUnsafeRequestHeaderValue(const nsACString& aHeaderValue);
2793 * Returns whether a given Accept header value is allowed
2794 * for a non-CORS XHR or fetch request.
2796 static bool IsAllowedNonCorsAccept(const nsACString& aHeaderValue);
2799 * Returns whether a given Content-Type header value is allowed
2800 * for a non-CORS XHR or fetch request.
2802 static bool IsAllowedNonCorsContentType(const nsACString& aHeaderValue);
2805 * Returns whether a given Content-Language or accept-language header value is
2806 * allowed for a non-CORS XHR or fetch request.
2808 static bool IsAllowedNonCorsLanguage(const nsACString& aHeaderValue);
2811 * Returns whether a given Range header value is allowed for a non-CORS XHR or
2812 * fetch request.
2814 static bool IsAllowedNonCorsRange(const nsACString& aHeaderValue);
2817 * Returns whether a given header and value is a CORS-safelisted request
2818 * header per https://fetch.spec.whatwg.org/#cors-safelisted-request-header
2820 static bool IsCORSSafelistedRequestHeader(const nsACString& aName,
2821 const nsACString& aValue);
2824 * Returns whether a given header is forbidden for an XHR or fetch
2825 * response.
2827 static bool IsForbiddenResponseHeader(const nsACString& aHeader);
2830 * Returns the inner window ID for the window associated with a request.
2832 static uint64_t GetInnerWindowID(nsIRequest* aRequest);
2835 * Returns the inner window ID for the window associated with a load group.
2837 static uint64_t GetInnerWindowID(nsILoadGroup* aLoadGroup);
2840 * Encloses aHost in brackets if it is an IPv6 address.
2842 static void MaybeFixIPv6Host(nsACString& aHost);
2845 * If the hostname for aURI is an IPv6 it encloses it in brackets,
2846 * otherwise it just outputs the hostname in aHost.
2848 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsAString& aHost);
2849 static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsACString& aHost);
2850 static nsresult GetHostOrIPv6WithBrackets(nsIPrincipal* aPrincipal,
2851 nsACString& aHost);
2854 * Call the given callback on all remote children of the given top-level
2855 * window. Return Callstate::Stop from the callback to stop calling further
2856 * children.
2858 static void CallOnAllRemoteChildren(
2859 nsPIDOMWindowOuter* aWindow,
2860 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
2861 aCallback);
2864 * Given an IPCDataTransferImageContainer construct an imgIContainer for the
2865 * image encoded by the transfer item.
2867 static nsresult DeserializeTransferableDataImageContainer(
2868 const mozilla::dom::IPCTransferableDataImageContainer& aData,
2869 imgIContainer** aContainer);
2872 * Given a flavor obtained from an IPCDataTransferItem or nsITransferable,
2873 * returns true if we should treat the data as an image.
2875 static bool IsFlavorImage(const nsACString& aFlavor);
2877 static bool IPCTransferableDataItemHasKnownFlavor(
2878 const mozilla::dom::IPCTransferableDataItem& aItem);
2880 static nsresult IPCTransferableDataToTransferable(
2881 const mozilla::dom::IPCTransferableData& aTransferableData,
2882 bool aAddDataFlavor, nsITransferable* aTransferable,
2883 const bool aFilterUnknownFlavors);
2885 static nsresult IPCTransferableDataToTransferable(
2886 const mozilla::dom::IPCTransferableData& aTransferableData,
2887 const bool& aIsPrivateData, nsIPrincipal* aRequestingPrincipal,
2888 const nsContentPolicyType& aContentPolicyType, bool aAddDataFlavor,
2889 nsITransferable* aTransferable, const bool aFilterUnknownFlavors);
2891 static nsresult IPCTransferableToTransferable(
2892 const mozilla::dom::IPCTransferable& aIPCTransferable,
2893 bool aAddDataFlavor, nsITransferable* aTransferable,
2894 const bool aFilterUnknownFlavors);
2896 static nsresult IPCTransferableDataItemToVariant(
2897 const mozilla::dom::IPCTransferableDataItem& aItem,
2898 nsIWritableVariant* aVariant);
2900 static void TransferablesToIPCTransferableDatas(
2901 nsIArray* aTransferables,
2902 nsTArray<mozilla::dom::IPCTransferableData>& aIPC, bool aInSyncMessage,
2903 mozilla::dom::ContentParent* aParent);
2905 static void TransferableToIPCTransferableData(
2906 nsITransferable* aTransferable,
2907 mozilla::dom::IPCTransferableData* aTransferableData, bool aInSyncMessage,
2908 mozilla::dom::ContentParent* aParent);
2910 static void TransferableToIPCTransferable(
2911 nsITransferable* aTransferable,
2912 mozilla::dom::IPCTransferable* aIPCTransferable, bool aInSyncMessage,
2913 mozilla::dom::ContentParent* aParent);
2916 * Get the pixel data from the given source surface and return it as a
2917 * BigBuffer. The length and stride will be assigned from the surface.
2919 static mozilla::Maybe<mozilla::ipc::BigBuffer> GetSurfaceData(
2920 mozilla::gfx::DataSourceSurface&, size_t* aLength, int32_t* aStride);
2922 static mozilla::Maybe<mozilla::dom::IPCImage> SurfaceToIPCImage(
2923 mozilla::gfx::DataSourceSurface&);
2924 static already_AddRefed<mozilla::gfx::DataSourceSurface> IPCImageToSurface(
2925 mozilla::dom::IPCImage&&);
2927 // Helpers shared by the implementations of nsContentUtils methods and
2928 // nsIDOMWindowUtils methods.
2929 static mozilla::Modifiers GetWidgetModifiers(int32_t aModifiers);
2930 static nsIWidget* GetWidget(mozilla::PresShell* aPresShell, nsPoint* aOffset);
2931 static int16_t GetButtonsFlagForButton(int32_t aButton);
2932 static mozilla::LayoutDeviceIntPoint ToWidgetPoint(
2933 const mozilla::CSSPoint& aPoint, const nsPoint& aOffset,
2934 nsPresContext* aPresContext);
2935 static nsView* GetViewToDispatchEvent(nsPresContext* aPresContext,
2936 mozilla::PresShell** aPresShell);
2939 * Synthesize a mouse event to the given widget
2940 * (see nsIDOMWindowUtils.sendMouseEvent).
2942 MOZ_CAN_RUN_SCRIPT
2943 static nsresult SendMouseEvent(
2944 mozilla::PresShell* aPresShell, const nsAString& aType, float aX,
2945 float aY, int32_t aButton, int32_t aButtons, int32_t aClickCount,
2946 int32_t aModifiers, bool aIgnoreRootScrollFrame, float aPressure,
2947 unsigned short aInputSourceArg, uint32_t aIdentifier, bool aToWindow,
2948 mozilla::PreventDefaultResult* aPreventDefault,
2949 bool aIsDOMEventSynthesized, bool aIsWidgetEventSynthesized);
2951 static void FirePageShowEventForFrameLoaderSwap(
2952 nsIDocShellTreeItem* aItem,
2953 mozilla::dom::EventTarget* aChromeEventHandler, bool aFireIfShowing,
2954 bool aOnlySystemGroup = false);
2956 static void FirePageHideEventForFrameLoaderSwap(
2957 nsIDocShellTreeItem* aItem,
2958 mozilla::dom::EventTarget* aChromeEventHandler,
2959 bool aOnlySystemGroup = false);
2961 static already_AddRefed<nsPIWindowRoot> GetWindowRoot(Document* aDoc);
2964 * If there is a Referrer-Policy response header in |aChannel|, parse a
2965 * referrer policy from the header.
2967 * @param the channel from which to get the Referrer-Policy header
2968 * @return referrer policy from the response header in aChannel
2970 static mozilla::dom::ReferrerPolicy GetReferrerPolicyFromChannel(
2971 nsIChannel* aChannel);
2973 static bool IsNonSubresourceRequest(nsIChannel* aChannel);
2975 static bool IsNonSubresourceInternalPolicyType(nsContentPolicyType aType);
2977 public:
2979 * Returns true if this window's channel has been marked as a third-party
2980 * tracking resource.
2982 static bool IsThirdPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
2985 * Returns true if this window's channel has been marked as a first-party
2986 * tracking resource.
2988 static bool IsFirstPartyTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
2991 * Serializes a HTML nsINode into its markup representation.
2993 static bool SerializeNodeToMarkup(nsINode* aRoot, bool aDescendentsOnly,
2994 nsAString& aOut);
2997 * Returns true iff the provided JSObject is a global, and its URI matches
2998 * the provided about: URI.
2999 * @param aGlobal the JSObject whose URI to check, if it is a global.
3000 * @param aUri the URI to match, e.g. "about:feeds"
3002 static bool IsSpecificAboutPage(JSObject* aGlobal, const char* aUri);
3004 static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
3007 * Try to find the docshell corresponding to the given event target.
3009 static nsIDocShell* GetDocShellForEventTarget(
3010 mozilla::dom::EventTarget* aTarget);
3013 * Returns true if the "HTTPS state" of the document should be "modern". See:
3015 * https://html.spec.whatwg.org/#concept-document-https-state
3016 * https://fetch.spec.whatwg.org/#concept-response-https-state
3018 static bool HttpsStateIsModern(Document* aDocument);
3021 * Returns true if the channel is for top-level window and is over secure
3022 * context.
3023 * https://github.com/whatwg/html/issues/4930 tracks the spec side of this.
3025 static bool ComputeIsSecureContext(nsIChannel* aChannel);
3028 * Try to upgrade an element.
3029 * https://html.spec.whatwg.org/multipage/custom-elements.html#concept-try-upgrade
3031 static void TryToUpgradeElement(Element* aElement);
3034 * Creates a new XUL or XHTML element applying any appropriate custom element
3035 * definition.
3037 * If aFromParser != FROM_PARSER_FRAGMENT, a nested event loop permits
3038 * arbitrary changes to the world before this function returns. This should
3039 * probably just be MOZ_CAN_RUN_SCRIPT - bug 1543259.
3041 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult NewXULOrHTMLElement(
3042 Element** aResult, mozilla::dom::NodeInfo* aNodeInfo,
3043 mozilla::dom::FromParser aFromParser, nsAtom* aIsAtom,
3044 mozilla::dom::CustomElementDefinition* aDefinition);
3046 static mozilla::dom::CustomElementRegistry* GetCustomElementRegistry(
3047 Document*);
3050 * Looking up a custom element definition.
3051 * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
3053 static mozilla::dom::CustomElementDefinition* LookupCustomElementDefinition(
3054 Document* aDoc, nsAtom* aNameAtom, uint32_t aNameSpaceID,
3055 nsAtom* aTypeAtom);
3057 static void RegisterCallbackUpgradeElement(Element* aElement,
3058 nsAtom* aTypeName);
3060 static void RegisterUnresolvedElement(Element* aElement, nsAtom* aTypeName);
3061 static void UnregisterUnresolvedElement(Element* aElement);
3063 static void EnqueueUpgradeReaction(
3064 Element* aElement, mozilla::dom::CustomElementDefinition* aDefinition);
3066 static void EnqueueLifecycleCallback(
3067 mozilla::dom::ElementCallbackType aType, Element* aCustomElement,
3068 const mozilla::dom::LifecycleCallbackArgs& aArgs,
3069 mozilla::dom::CustomElementDefinition* aDefinition = nullptr);
3071 static mozilla::dom::CustomElementFormValue ConvertToCustomElementFormValue(
3072 const mozilla::dom::Nullable<
3073 mozilla::dom::OwningFileOrUSVStringOrFormData>& aState);
3075 static mozilla::dom::Nullable<mozilla::dom::OwningFileOrUSVStringOrFormData>
3076 ExtractFormAssociatedCustomElementValue(
3077 nsIGlobalObject* aGlobal,
3078 const mozilla::dom::CustomElementFormValue& aCEValue);
3081 * Appends all "document level" native anonymous content subtree roots for
3082 * aDocument to aElements. Document level NAC subtrees are those created
3083 * by ancestor frames of the document element's primary frame, such as
3084 * the scrollbar elements created by the root scroll frame.
3086 static void AppendDocumentLevelNativeAnonymousContentTo(
3087 Document* aDocument, nsTArray<nsIContent*>& aElements);
3090 * Appends all native anonymous content subtree roots generated by `aContent`
3091 * to `aKids`.
3093 * See `AllChildrenIterator` for the description of the `aFlags` parameter.
3095 static void AppendNativeAnonymousChildren(const nsIContent* aContent,
3096 nsTArray<nsIContent*>& aKids,
3097 uint32_t aFlags);
3100 * Query triggeringPrincipal if there's a 'triggeringprincipal' attribute on
3101 * aLoadingNode, if no such attribute is specified, aDefaultPrincipal is
3102 * returned if it is provided, otherwise the NodePrincipal of aLoadingNode is
3103 * returned.
3105 * Return true if aLoadingNode has a 'triggeringprincipal' attribute, and
3106 * the value 'triggeringprincipal' is also successfully deserialized,
3107 * otherwise return false.
3109 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3110 nsIPrincipal* aDefaultPrincipal,
3111 nsIPrincipal** aTriggeringPrincipal);
3113 static bool QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3114 nsIPrincipal** aTriggeringPrincipal) {
3115 return QueryTriggeringPrincipal(aLoadingNode, nullptr,
3116 aTriggeringPrincipal);
3119 // Returns whether the image for the given URI and triggering principal is
3120 // already available. Ideally this should exactly match the "list of available
3121 // images" in the HTML spec, but our implementation of that at best only
3122 // resembles it.
3123 static bool IsImageAvailable(nsIContent*, nsIURI*,
3124 nsIPrincipal* aDefaultTriggeringPrincipal,
3125 mozilla::CORSMode);
3126 static bool IsImageAvailable(nsIURI*, nsIPrincipal* aTriggeringPrincipal,
3127 mozilla::CORSMode, Document*);
3130 * Returns the content policy type that should be used for loading images
3131 * for displaying in the UI. The sources of such images can be <xul:image>,
3132 * <xul:menuitem> on OSX where we load the image through nsMenuItemIconX, etc.
3134 static void GetContentPolicyTypeForUIImageLoading(
3135 nsIContent* aLoadingNode, nsIPrincipal** aTriggeringPrincipal,
3136 nsContentPolicyType& aContentPolicyType, uint64_t* aRequestContextID);
3138 static nsresult CreateJSValueFromSequenceOfObject(
3139 JSContext* aCx, const mozilla::dom::Sequence<JSObject*>& aTransfer,
3140 JS::MutableHandle<JS::Value> aValue);
3143 * This implements the structured cloning algorithm as described by
3144 * https://html.spec.whatwg.org/#structured-cloning.
3146 static void StructuredClone(
3147 JSContext* aCx, nsIGlobalObject* aGlobal, JS::Handle<JS::Value> aValue,
3148 const mozilla::dom::StructuredSerializeOptions& aOptions,
3149 JS::MutableHandle<JS::Value> aRetval, mozilla::ErrorResult& aError);
3152 * Returns true if reserved key events should be prevented from being sent
3153 * to their target. Instead, the key event should be handled by chrome only.
3155 static bool ShouldBlockReservedKeys(mozilla::WidgetKeyboardEvent* aKeyEvent);
3158 * Returns the nsIPluginTag for the plugin we should try to use for a given
3159 * MIME type.
3161 * @param aMIMEType The MIME type of the document being loaded.
3162 * @param aNoFakePlugin If false then this method should consider JS plugins.
3164 static already_AddRefed<nsIPluginTag> PluginTagForType(
3165 const nsCString& aMIMEType, bool aNoFakePlugin);
3168 * Returns one of the nsIObjectLoadingContent::TYPE_ values describing the
3169 * content type which will be used for the given MIME type when loaded within
3170 * an nsObjectLoadingContent.
3172 * NOTE: This method doesn't take capabilities into account. The caller must
3173 * take that into account.
3175 * @param aMIMEType The MIME type of the document being loaded.
3176 * @param aNoFakePlugin If false then this method should consider JS plugins.
3178 static uint32_t HtmlObjectContentTypeForMIMEType(const nsCString& aMIMEType,
3179 bool aNoFakePlugin);
3182 * Detect whether a string is a local-url.
3183 * https://drafts.csswg.org/css-values/#local-urls
3185 static bool IsLocalRefURL(const nsAString& aString);
3188 * Compose a tab id with process id and a serial number.
3190 static uint64_t GenerateTabId();
3193 * Compose a browser id with process id and a serial number.
3195 static uint64_t GenerateBrowserId();
3198 * Generate an id for a BrowsingContext using a range of serial
3199 * numbers reserved for the current process.
3201 static uint64_t GenerateBrowsingContextId();
3204 * Generate an id using a range of serial numbers reserved for the current
3205 * process. aId should be a counter that's incremented every time
3206 * GenerateProcessSpecificId is called.
3208 static uint64_t GenerateProcessSpecificId(uint64_t aId);
3210 static std::tuple<uint64_t, uint64_t> SplitProcessSpecificId(uint64_t aId);
3213 * Generate a window ID which is unique across processes and will never be
3214 * recycled.
3216 static uint64_t GenerateWindowId();
3219 * Generate an ID for a load which is unique across processes and will never
3220 * be recycled.
3222 static uint64_t GenerateLoadIdentifier();
3225 * Determine whether or not the user is currently interacting with the web
3226 * browser. This method is safe to call from off of the main thread.
3228 static bool GetUserIsInteracting();
3230 // Alternate data MIME type used by the ScriptLoader to register and read
3231 // bytecode out of the nsCacheInfoChannel.
3232 [[nodiscard]] static bool InitJSBytecodeMimeType();
3233 static nsCString& JSScriptBytecodeMimeType() {
3234 MOZ_ASSERT(sJSScriptBytecodeMimeType);
3235 return *sJSScriptBytecodeMimeType;
3237 static nsCString& JSModuleBytecodeMimeType() {
3238 MOZ_ASSERT(sJSModuleBytecodeMimeType);
3239 return *sJSModuleBytecodeMimeType;
3243 * Checks if the passed-in name is one of the special names: "_blank", "_top",
3244 * "_parent" or "_self".
3246 static bool IsSpecialName(const nsAString& aName);
3249 * Checks if the passed-in name should override an existing name on the
3250 * window. Values which should not override include: "", "_blank", "_top",
3251 * "_parent" and "_self".
3253 static bool IsOverridingWindowName(const nsAString& aName);
3256 * If there is a SourceMap (higher precedence) or X-SourceMap (lower
3257 * precedence) response header in |aChannel|, set |aResult| to the
3258 * header's value and return true. Otherwise, return false.
3260 * @param aChannel The HTTP channel
3261 * @param aResult The string result.
3263 static bool GetSourceMapURL(nsIHttpChannel* aChannel, nsACString& aResult);
3266 * Returns true if the passed-in mesasge is a pending InputEvent.
3268 * @param aMsg The message to check
3270 static bool IsMessageInputEvent(const IPC::Message& aMsg);
3273 * Returns true if the passed-in message is a critical InputEvent.
3275 * @param aMsg The message to check
3277 static bool IsMessageCriticalInputEvent(const IPC::Message& aMsg);
3279 static void AsyncPrecreateStringBundles();
3281 static bool ContentIsLink(nsIContent* aContent);
3283 static already_AddRefed<mozilla::dom::ContentFrameMessageManager>
3284 TryGetBrowserChildGlobal(nsISupports* aFrom);
3286 // Get a serial number for a newly created inner or outer window.
3287 static uint32_t InnerOrOuterWindowCreated();
3288 // Record that an inner or outer window has been destroyed.
3289 static void InnerOrOuterWindowDestroyed();
3290 // Get the current number of inner or outer windows.
3291 static int32_t GetCurrentInnerOrOuterWindowCount() {
3292 return sInnerOrOuterWindowCount;
3295 // Return an anonymized URI so that it can be safely exposed publicly.
3296 static nsresult AnonymizeURI(nsIURI* aURI, nsCString& aAnonymizedURI);
3299 * Serializes a JSON-like JS::Value into a string.
3300 * Cases where JSON.stringify would return undefined are handled according to
3301 * the |aBehavior| argument:
3303 * - If it is |UndefinedIsNullStringLiteral|, the string "null" is returned.
3304 * - If it is |UndefinedIsVoidString|, the void string is returned.
3306 * The |UndefinedIsNullStringLiteral| case is likely not desirable, but is
3307 * retained for now for historical reasons.
3308 * Usage:
3309 * nsAutoString serializedValue;
3310 * nsContentUtils::StringifyJSON(cx, value, serializedValue, behavior);
3312 static bool StringifyJSON(JSContext* aCx, JS::Handle<JS::Value> aValue,
3313 nsAString& aOutStr, JSONBehavior aBehavior);
3316 * Returns true if the top level ancestor content document of aDocument hasn't
3317 * yet had the first contentful paint and there is a high priority event
3318 * pending in the main thread.
3320 static bool HighPriorityEventPendingForTopLevelDocumentBeforeContentfulPaint(
3321 Document* aDocument);
3324 * Get the inner window corresponding to the incumbent global, including
3325 * mapping extension content script globals to the attached window.
3327 * Returns null if the incumbent global doesn't correspond to an inner window.
3329 static nsGlobalWindowInner* IncumbentInnerWindow();
3332 * Get the inner window corresponding to the entry global, including mapping
3333 * extension content script globals to the attached window.
3335 * Returns null if the entry global doesn't correspond to an inner window.
3337 static nsGlobalWindowInner* EntryInnerWindow();
3340 * Return safe area insets of window that defines as
3341 * https://drafts.csswg.org/css-env-1/#safe-area-insets.
3343 static mozilla::ScreenIntMargin GetWindowSafeAreaInsets(
3344 nsIScreen* aScreen, const mozilla::ScreenIntMargin& aSafeareaInsets,
3345 const mozilla::LayoutDeviceIntRect& aWindowRect);
3347 struct SubresourceCacheValidationInfo {
3348 // The expiration time, in seconds, if known.
3349 mozilla::Maybe<uint32_t> mExpirationTime;
3350 bool mMustRevalidate = false;
3354 * Gets cache validation info for subresources such as images or CSS
3355 * stylesheets.
3357 static SubresourceCacheValidationInfo GetSubresourceCacheValidationInfo(
3358 nsIRequest*, nsIURI*);
3360 static uint32_t SecondsFromPRTime(PRTime aTime) {
3361 return uint32_t(int64_t(aTime) / int64_t(PR_USEC_PER_SEC));
3365 * Converts the given URL to a string and truncates it to the given length.
3367 * Returns an empty string if aURL is null.
3369 static nsCString TruncatedURLForDisplay(nsIURI* aURL, size_t aMaxLen = 128);
3372 * Anonymize the given id by hashing it with the provided origin. The
3373 * resulting id will have the same length as the one that was passed in.
3375 enum class OriginFormat {
3376 Base64,
3377 Plain,
3380 static nsresult AnonymizeId(nsAString& aId, const nsACString& aOriginKey,
3381 OriginFormat aFormat = OriginFormat::Base64);
3384 * Return true if we should hide the synthetic browsing context for <object>
3385 * or <embed> images in synthetic documents.
3387 static bool ShouldHideObjectOrEmbedImageDocument();
3390 * Returns the object type that the object loading content will actually use
3391 * to load the resource. Used for ORB and loading images into synthetic
3392 * documents.
3394 static uint32_t ResolveObjectType(uint32_t aType);
3397 * Create and load the string bundle for the 'aFile'.
3398 * This API is used to preload the string bundle on the main thread so later
3399 * other thread could access it.
3401 static nsresult EnsureAndLoadStringBundle(PropertiesFile aFile);
3404 * The method asks nsIAppShell to prioritize Gecko's internal tasks over
3405 * the OS level tasks for a short period of time.
3407 static void RequestGeckoTaskBurst();
3409 static void SetMayHaveFormCheckboxStateChangeListeners() {
3410 sMayHaveFormCheckboxStateChangeListeners = true;
3413 static bool MayHaveFormCheckboxStateChangeListeners() {
3414 return sMayHaveFormCheckboxStateChangeListeners;
3417 static void SetMayHaveFormRadioStateChangeListeners() {
3418 sMayHaveFormRadioStateChangeListeners = true;
3421 static bool MayHaveFormRadioStateChangeListeners() {
3422 return sMayHaveFormRadioStateChangeListeners;
3426 * Returns the closest link element in the flat tree of aContent if there's
3427 * one, otherwise returns nullptr.
3429 static nsIContent* GetClosestLinkInFlatTree(nsIContent* aContent);
3431 static bool IsExternalProtocol(nsIURI* aURI);
3434 * Add an element to a list, keeping the list sorted by tree order.
3435 * Can take a potential ancestor of the elements in order to speed up
3436 * tree-order comparisons, if such an ancestor exists.
3437 * Returns true if the element is appended to the end of the list.
3439 template <typename ElementType, typename ElementPtr>
3440 static bool AddElementToListByTreeOrder(nsTArray<ElementType>& aList,
3441 ElementPtr aChild,
3442 nsIContent* aCommonAncestor);
3445 * Compares the position of aContent1 and aContent2 in the document
3446 * @param aContent1 First content to compare.
3447 * @param aContent2 Second content to compare.
3448 * @param aCommonAncestor Potential ancestor of the contents, if one exists.
3449 * This is only a hint; if it's not an ancestor of
3450 * aContent1 or aContent2, this function will still
3451 * work, but it will be slower than normal.
3452 * @return < 0 if aContent1 is before aContent2,
3453 * > 0 if aContent1 is after aContent2,
3454 * 0 otherwise
3456 static int32_t CompareTreePosition(nsIContent* aContent1,
3457 nsIContent* aContent2,
3458 const nsIContent* aCommonAncestor);
3460 private:
3461 static bool InitializeEventTable();
3463 static nsresult EnsureStringBundle(PropertiesFile aFile);
3465 static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
3466 nsIPrincipal* aPrincipal);
3468 static nsresult WrapNative(JSContext* cx, nsISupports* native,
3469 nsWrapperCache* cache, const nsIID* aIID,
3470 JS::MutableHandle<JS::Value> vp,
3471 bool aAllowWrapping);
3473 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3474 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult DispatchEvent(
3475 Document* aDoc, mozilla::dom::EventTarget* aTarget,
3476 const nsAString& aEventName, CanBubble, Cancelable, Composed, Trusted,
3477 bool* aDefaultAction = nullptr,
3478 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3480 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
3481 MOZ_CAN_RUN_SCRIPT_BOUNDARY static nsresult DispatchEvent(
3482 Document* aDoc, mozilla::dom::EventTarget* aTarget,
3483 mozilla::WidgetEvent& aWidgetEvent, EventMessage aEventMessage, CanBubble,
3484 Cancelable, Trusted, bool* aDefaultAction = nullptr,
3485 ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3487 static void InitializeModifierStrings();
3489 static void DropFragmentParsers();
3491 static bool MatchClassNames(mozilla::dom::Element* aElement,
3492 int32_t aNamespaceID, nsAtom* aAtom, void* aData);
3493 static void DestroyClassNameArray(void* aData);
3494 static void* AllocClassMatchingInfo(nsINode* aRootNode,
3495 const nsString* aClasses);
3497 static mozilla::EventClassID GetEventClassIDFromMessage(
3498 EventMessage aEventMessage);
3500 // Fills in aInfo with the tokens from the supplied autocomplete attribute.
3501 static AutocompleteAttrState InternalSerializeAutocompleteAttribute(
3502 const nsAttrValue* aAttrVal, mozilla::dom::AutocompleteInfo& aInfo,
3503 bool aGrantAllValidValue = false);
3505 static mozilla::CallState CallOnAllRemoteChildren(
3506 mozilla::dom::MessageBroadcaster* aManager,
3507 const std::function<mozilla::CallState(mozilla::dom::BrowserParent*)>&
3508 aCallback);
3510 static nsINode* GetCommonAncestorHelper(nsINode* aNode1, nsINode* aNode2);
3511 static nsIContent* GetCommonFlattenedTreeAncestorHelper(
3512 nsIContent* aContent1, nsIContent* aContent2);
3514 static nsIXPConnect* sXPConnect;
3516 static nsIScriptSecurityManager* sSecurityManager;
3517 static nsIPrincipal* sSystemPrincipal;
3518 static nsIPrincipal* sNullSubjectPrincipal;
3520 static nsIConsoleService* sConsoleService;
3522 static nsIStringBundleService* sStringBundleService;
3523 class nsContentUtilsReporter;
3525 static nsIContentPolicy* sContentPolicyService;
3526 static bool sTriedToGetContentPolicy;
3528 static mozilla::StaticRefPtr<nsIBidiKeyboard> sBidiKeyboard;
3530 static bool sInitialized;
3531 static uint32_t sScriptBlockerCount;
3532 static uint32_t sDOMNodeRemovedSuppressCount;
3534 // Not an nsCOMArray because removing elements from those is slower
3535 static AutoTArray<nsCOMPtr<nsIRunnable>, 8>* sBlockedScriptRunners;
3536 static uint32_t sRunnersCountAtFirstBlocker;
3537 static uint32_t sScriptBlockerCountWhereRunnersPrevented;
3539 static nsIInterfaceRequestor* sSameOriginChecker;
3541 static bool sIsHandlingKeyBoardEvent;
3542 #ifndef RELEASE_OR_BETA
3543 static bool sBypassCSSOMOriginCheck;
3544 #endif
3546 class UserInteractionObserver;
3547 static UserInteractionObserver* sUserInteractionObserver;
3549 static nsHtml5StringParser* sHTMLFragmentParser;
3550 static nsParser* sXMLFragmentParser;
3551 static nsIFragmentContentSink* sXMLFragmentSink;
3554 * True if there's a fragment parser activation on the stack.
3556 static bool sFragmentParsingActive;
3558 static nsString* sShiftText;
3559 static nsString* sControlText;
3560 static nsString* sCommandOrWinText;
3561 static nsString* sAltText;
3562 static nsString* sModifierSeparator;
3564 // Alternate data mime types, used by the ScriptLoader to register and read
3565 // the bytecode out of the nsCacheInfoChannel.
3566 static nsCString* sJSScriptBytecodeMimeType;
3567 static nsCString* sJSModuleBytecodeMimeType;
3569 static mozilla::LazyLogModule gResistFingerprintingLog;
3570 static mozilla::LazyLogModule sDOMDumpLog;
3572 static int32_t sInnerOrOuterWindowCount;
3573 static uint32_t sInnerOrOuterWindowSerialCounter;
3575 static bool sMayHaveFormCheckboxStateChangeListeners;
3576 static bool sMayHaveFormRadioStateChangeListeners;
3579 /* static */ inline ExtContentPolicyType
3580 nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType) {
3581 switch (aType) {
3582 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
3583 case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
3584 case nsIContentPolicy::TYPE_INTERNAL_MODULE:
3585 case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD:
3586 case nsIContentPolicy::TYPE_INTERNAL_WORKER:
3587 case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
3588 case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
3589 case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
3590 case nsIContentPolicy::TYPE_INTERNAL_WORKER_STATIC_MODULE:
3591 case nsIContentPolicy::TYPE_INTERNAL_AUDIOWORKLET:
3592 case nsIContentPolicy::TYPE_INTERNAL_PAINTWORKLET:
3593 case nsIContentPolicy::TYPE_INTERNAL_CHROMEUTILS_COMPILED_SCRIPT:
3594 case nsIContentPolicy::TYPE_INTERNAL_FRAME_MESSAGEMANAGER_SCRIPT:
3595 return ExtContentPolicy::TYPE_SCRIPT;
3597 case nsIContentPolicy::TYPE_INTERNAL_EMBED:
3598 case nsIContentPolicy::TYPE_INTERNAL_OBJECT:
3599 return ExtContentPolicy::TYPE_OBJECT;
3601 case nsIContentPolicy::TYPE_INTERNAL_FRAME:
3602 case nsIContentPolicy::TYPE_INTERNAL_IFRAME:
3603 return ExtContentPolicy::TYPE_SUBDOCUMENT;
3605 case nsIContentPolicy::TYPE_INTERNAL_AUDIO:
3606 case nsIContentPolicy::TYPE_INTERNAL_VIDEO:
3607 case nsIContentPolicy::TYPE_INTERNAL_TRACK:
3608 return ExtContentPolicy::TYPE_MEDIA;
3610 case nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST:
3611 case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE:
3612 return ExtContentPolicy::TYPE_XMLHTTPREQUEST;
3614 case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
3615 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
3616 case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON:
3617 return ExtContentPolicy::TYPE_IMAGE;
3619 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
3620 case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
3621 return ExtContentPolicy::TYPE_STYLESHEET;
3623 case nsIContentPolicy::TYPE_INTERNAL_DTD:
3624 case nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD:
3625 return ExtContentPolicy::TYPE_DTD;
3627 case nsIContentPolicy::TYPE_INTERNAL_FONT_PRELOAD:
3628 return ExtContentPolicy::TYPE_FONT;
3630 case nsIContentPolicy::TYPE_INTERNAL_FETCH_PRELOAD:
3631 return ExtContentPolicy::TYPE_FETCH;
3633 default:
3634 return static_cast<ExtContentPolicyType>(aType);
3638 namespace mozilla {
3639 std::ostream& operator<<(
3640 std::ostream& aOut,
3641 const mozilla::PreventDefaultResult aPreventDefaultResult);
3642 } // namespace mozilla
3644 class MOZ_RAII nsAutoScriptBlocker {
3645 public:
3646 explicit nsAutoScriptBlocker() { nsContentUtils::AddScriptBlocker(); }
3647 ~nsAutoScriptBlocker() { nsContentUtils::RemoveScriptBlocker(); }
3649 private:
3652 class MOZ_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved
3653 : public nsAutoScriptBlocker {
3654 public:
3655 nsAutoScriptBlockerSuppressNodeRemoved() {
3656 ++nsContentUtils::sDOMNodeRemovedSuppressCount;
3658 ~nsAutoScriptBlockerSuppressNodeRemoved() {
3659 --nsContentUtils::sDOMNodeRemovedSuppressCount;
3663 namespace mozilla::dom {
3665 class TreeOrderComparator {
3666 public:
3667 bool Equals(nsINode* aElem1, nsINode* aElem2) const {
3668 return aElem1 == aElem2;
3670 bool LessThan(nsINode* aElem1, nsINode* aElem2) const {
3671 return nsContentUtils::PositionIsBefore(aElem1, aElem2);
3675 } // namespace mozilla::dom
3677 #define NS_INTERFACE_MAP_ENTRY_TEAROFF(_interface, _allocator) \
3678 if (aIID.Equals(NS_GET_IID(_interface))) { \
3679 foundInterface = static_cast<_interface*>(_allocator); \
3680 if (!foundInterface) { \
3681 *aInstancePtr = nullptr; \
3682 return NS_ERROR_OUT_OF_MEMORY; \
3684 } else
3687 * In the following helper macros we exploit the fact that the result of a
3688 * series of additions will not be finite if any one of the operands in the
3689 * series is not finite.
3691 #define NS_ENSURE_FINITE(f, rv) \
3692 if (!std::isfinite(f)) { \
3693 return (rv); \
3696 #define NS_ENSURE_FINITE2(f1, f2, rv) \
3697 if (!std::isfinite((f1) + (f2))) { \
3698 return (rv); \
3701 #define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv) \
3702 if (!std::isfinite((f1) + (f2) + (f3) + (f4))) { \
3703 return (rv); \
3706 #define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv) \
3707 if (!std::isfinite((f1) + (f2) + (f3) + (f4) + (f5))) { \
3708 return (rv); \
3711 #define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv) \
3712 if (!std::isfinite((f1) + (f2) + (f3) + (f4) + (f5) + (f6))) { \
3713 return (rv); \
3716 // Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
3717 #define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_) \
3719 type_* cur = (ptr_)->member_; \
3720 (ptr_)->member_ = nullptr; \
3721 while (cur) { \
3722 type_* next = cur->member_; \
3723 cur->member_ = nullptr; \
3724 delete cur; \
3725 cur = next; \
3729 #endif /* nsContentUtils_h___ */