nsGlobalWindowInner.h (60300B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef nsGlobalWindowInner_h___ 8 #define nsGlobalWindowInner_h___ 9 10 #include "nsHashKeys.h" 11 #include "nsPIDOMWindow.h" 12 13 // Local Includes 14 // Helper Classes 15 #include "mozilla/WeakPtr.h" 16 #include "nsCOMPtr.h" 17 #include "nsCycleCollectionParticipant.h" 18 #include "nsTHashMap.h" 19 #include "nsWeakReference.h" 20 21 // Interfaces Needed 22 #include "Units.h" 23 #include "mozilla/Attributes.h" 24 #include "mozilla/CallState.h" 25 #include "mozilla/EventListenerManager.h" 26 #include "mozilla/FlushType.h" 27 #include "mozilla/LinkedList.h" 28 #include "mozilla/MozPromise.h" 29 #include "mozilla/StorageAccess.h" 30 #include "mozilla/TimeStamp.h" 31 #include "mozilla/UniquePtr.h" 32 #include "mozilla/dom/BindingDeclarations.h" 33 #include "mozilla/dom/ChromeMessageBroadcaster.h" 34 #include "mozilla/dom/DebuggerNotificationManager.h" 35 #include "mozilla/dom/EventTarget.h" 36 #include "mozilla/dom/GamepadHandle.h" 37 #include "mozilla/dom/ImageBitmapBinding.h" 38 #include "mozilla/dom/ImageBitmapSource.h" 39 #include "mozilla/dom/Location.h" 40 #include "mozilla/dom/Promise.h" 41 #include "mozilla/dom/StorageEvent.h" 42 #include "mozilla/dom/WindowBinding.h" 43 #include "mozilla/dom/WindowProxyHolder.h" 44 #include "nsCheapSets.h" 45 #include "nsIBrowserDOMWindow.h" 46 #include "nsIInterfaceRequestor.h" 47 #include "nsIPrincipal.h" 48 #include "nsIScriptGlobalObject.h" 49 #include "nsIScriptObjectPrincipal.h" 50 #include "nsSize.h" 51 #include "nsThreadUtils.h" 52 #include "nsWrapperCacheInlines.h" 53 #include "prclist.h" 54 55 class nsIArray; 56 class nsIBaseWindow; 57 class nsIContent; 58 class nsICookieJarSettings; 59 class nsIDocShellTreeOwner; 60 class nsIDOMWindowUtils; 61 class nsIControllers; 62 class nsIScriptContext; 63 class nsIScriptTimeoutHandler; 64 class nsIBrowserChild; 65 class nsIPrintSettings; 66 class nsITimeoutHandler; 67 class nsIWebBrowserChrome; 68 class nsIWebProgressListener; 69 class mozIDOMWindowProxy; 70 71 class nsScreen; 72 class nsHistory; 73 class nsGlobalWindowObserver; 74 class nsGlobalWindowOuter; 75 class nsDOMWindowUtils; 76 class nsIUserIdleService; 77 struct nsRect; 78 class nsWindowRoot; 79 class nsWindowSizes; 80 81 class IdleRequestExecutor; 82 83 class PromiseDocumentFlushedResolver; 84 85 namespace mozilla { 86 class AbstractThread; 87 class ErrorResult; 88 template <class T> 89 class OwningNonNull; 90 class ScrollContainerFrame; 91 92 namespace glean { 93 class Glean; 94 class GleanPings; 95 } // namespace glean 96 97 namespace hal { 98 enum class ScreenOrientation : uint32_t; 99 } 100 101 namespace dom { 102 class BarProp; 103 class BrowsingContext; 104 struct ChannelPixelLayout; 105 class Credential; 106 class ClientSource; 107 class Console; 108 class CookieStore; 109 class Crypto; 110 class CustomElementRegistry; 111 class DataTransfer; 112 class DocGroup; 113 class DocumentPictureInPicture; 114 class External; 115 class FunctionOrTrustedScriptOrString; 116 class Gamepad; 117 class ContentMediaController; 118 enum class ImageBitmapFormat : uint8_t; 119 class IdleRequest; 120 class IdleRequestCallback; 121 class IntlUtils; 122 class MediaQueryList; 123 class OwningExternalOrWindowProxy; 124 class Promise; 125 class PostMessageEvent; 126 struct RequestInit; 127 class RequestOrUTF8String; 128 class SharedWorker; 129 class Selection; 130 struct SizeToContentConstraints; 131 class WebTaskScheduler; 132 class WebTaskSchedulerMainThread; 133 class WebTaskSchedulingState; 134 class SpeechSynthesis; 135 class Timeout; 136 class TrustedTypePolicyFactory; 137 class VisualViewport; 138 class VoidFunction; 139 class VRDisplay; 140 enum class VRDisplayEventReason : uint8_t; 141 class VREventObserver; 142 struct WindowPostMessageOptions; 143 class Worklet; 144 namespace cache { 145 class CacheStorage; 146 } // namespace cache 147 class IDBFactory; 148 } // namespace dom 149 } // namespace mozilla 150 151 extern const JSClass OuterWindowProxyClass; 152 153 //***************************************************************************** 154 // nsGlobalWindowInner: Global Object for Scripting 155 //***************************************************************************** 156 157 // nsGlobalWindowInner inherits PRCList for maintaining a list of all inner 158 // windows still in memory for any given outer window. This list is needed to 159 // ensure that mOuterWindow doesn't end up dangling. The nature of PRCList means 160 // that the window itself is always in the list, and an outer window's list will 161 // also contain all inner window objects that are still in memory (and in 162 // reality all inner window object's lists also contain its outer and all other 163 // inner windows belonging to the same outer window, but that's an unimportant 164 // side effect of inheriting PRCList). 165 166 class nsGlobalWindowInner final : public mozilla::dom::EventTarget, 167 public nsPIDOMWindowInner, 168 private nsIDOMWindow, 169 public nsIScriptGlobalObject, 170 public nsIScriptObjectPrincipal, 171 public nsSupportsWeakReference, 172 public nsIInterfaceRequestor, 173 public PRCListStr { 174 public: 175 using RemoteProxy = mozilla::dom::BrowsingContext; 176 177 using TimeStamp = mozilla::TimeStamp; 178 using TimeDuration = mozilla::TimeDuration; 179 180 using InnerWindowByIdTable = 181 nsTHashMap<nsUint64HashKey, nsGlobalWindowInner*>; 182 183 static void AssertIsOnMainThread() 184 #ifdef DEBUG 185 ; 186 #else 187 { 188 } 189 #endif 190 191 bool IsInnerWindow() const final { return true; } // Overriding EventTarget 192 193 static nsGlobalWindowInner* Cast(nsPIDOMWindowInner* aPIWin) { 194 return static_cast<nsGlobalWindowInner*>(aPIWin); 195 } 196 static const nsGlobalWindowInner* Cast(const nsPIDOMWindowInner* aPIWin) { 197 return static_cast<const nsGlobalWindowInner*>(aPIWin); 198 } 199 static nsGlobalWindowInner* Cast(mozIDOMWindow* aWin) { 200 return Cast(nsPIDOMWindowInner::From(aWin)); 201 } 202 203 static nsGlobalWindowInner* GetInnerWindowWithId(uint64_t aInnerWindowID) { 204 AssertIsOnMainThread(); 205 206 if (!sInnerWindowsById) { 207 return nullptr; 208 } 209 210 nsGlobalWindowInner* innerWindow = sInnerWindowsById->Get(aInnerWindowID); 211 return innerWindow; 212 } 213 214 static InnerWindowByIdTable* GetWindowsTable() { 215 AssertIsOnMainThread(); 216 217 return sInnerWindowsById; 218 } 219 220 static nsGlobalWindowInner* FromSupports(nsISupports* supports) { 221 // Make sure this matches the casts we do in QueryInterface(). 222 return (nsGlobalWindowInner*)(mozilla::dom::EventTarget*)supports; 223 } 224 225 static already_AddRefed<nsGlobalWindowInner> Create( 226 nsGlobalWindowOuter* aOuter, bool aIsChrome, 227 mozilla::dom::WindowGlobalChild* aActor); 228 229 // nsISupports 230 NS_DECL_ISUPPORTS_INHERITED 231 NS_IMETHOD_(void) DeleteCycleCollectable() override; 232 233 // nsWrapperCache 234 virtual JSObject* WrapObject(JSContext* cx, 235 JS::Handle<JSObject*> aGivenProto) override { 236 return GetWrapper(); 237 } 238 239 // nsIGlobalObject 240 bool ShouldResistFingerprinting(RFPTarget aTarget) const final; 241 mozilla::OriginTrials Trials() const final; 242 mozilla::dom::FontFaceSet* GetFonts() final; 243 244 JSObject* GetGlobalJSObject() final { return GetWrapper(); } 245 JSObject* GetGlobalJSObjectPreserveColor() const final { 246 return GetWrapperPreserveColor(); 247 } 248 // The HasJSGlobal on nsIGlobalObject ends up having to do a virtual 249 // call to GetGlobalJSObjectPreserveColor(), because when it's 250 // making the call it doesn't know it's doing it on an 251 // nsGlobalWindowInner. Add a version here that can be entirely 252 // non-virtual. 253 bool HasJSGlobal() const { return GetGlobalJSObjectPreserveColor(); } 254 255 mozilla::Result<mozilla::ipc::PrincipalInfo, nsresult> GetStorageKey() 256 override; 257 258 mozilla::dom::StorageManager* GetStorageManager() override; 259 260 bool IsEligibleForMessaging() override; 261 262 void ReportToConsole(uint32_t aErrorFlags, const nsCString& aCategory, 263 nsContentUtils::PropertiesFile aFile, 264 const nsCString& aMessageName, 265 const nsTArray<nsString>& aParams, 266 const mozilla::SourceLocation& aLocation) override; 267 268 void TraceGlobalJSObject(JSTracer* aTrc); 269 270 virtual nsresult EnsureScriptEnvironment() override; 271 272 virtual nsIScriptContext* GetScriptContext() override; 273 274 virtual bool IsBlackForCC(bool aTracingNeeded = true) override; 275 276 // nsIScriptObjectPrincipal 277 virtual nsIPrincipal* GetPrincipal() override; 278 279 virtual nsIPrincipal* GetEffectiveCookiePrincipal() override; 280 281 virtual nsIPrincipal* GetEffectiveStoragePrincipal() override; 282 283 virtual nsIPrincipal* PartitionedPrincipal() override; 284 285 mozilla::dom::TimeoutManager* GetTimeoutManager() override; 286 287 bool IsRunningTimeout() override; 288 289 // nsIDOMWindow 290 NS_DECL_NSIDOMWINDOW 291 292 void CaptureEvents(); 293 void ReleaseEvents(); 294 void Dump(const nsAString& aStr); 295 void SetResizable(bool aResizable) const; 296 297 virtual mozilla::EventListenerManager* GetExistingListenerManager() 298 const override; 299 300 virtual mozilla::EventListenerManager* GetOrCreateListenerManager() override; 301 302 mozilla::Maybe<mozilla::dom::EventCallbackDebuggerNotificationType> 303 GetDebuggerNotificationType() const override; 304 305 bool ComputeDefaultWantsUntrusted(mozilla::ErrorResult& aRv) final; 306 307 virtual nsPIDOMWindowOuter* GetOwnerGlobalForBindingsInternal() override; 308 309 virtual nsIGlobalObject* GetOwnerGlobal() const override; 310 311 EventTarget* GetTargetForDOMEvent() override; 312 313 using mozilla::dom::EventTarget::DispatchEvent; 314 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230) 315 MOZ_CAN_RUN_SCRIPT_BOUNDARY bool DispatchEvent( 316 mozilla::dom::Event& aEvent, mozilla::dom::CallerType aCallerType, 317 mozilla::ErrorResult& aRv) override; 318 319 void GetEventTargetParent(mozilla::EventChainPreVisitor& aVisitor) override; 320 321 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230) 322 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult 323 PostHandleEvent(mozilla::EventChainPostVisitor& aVisitor) override; 324 325 void Suspend(bool aIncludeSubWindows = true); 326 void Resume(bool aIncludeSubWindows = true); 327 virtual bool IsSuspended() const override; 328 329 // Calling Freeze() on a window will automatically Suspend() it. In 330 // addition, the window and its children (if aIncludeSubWindows is true) are 331 // further treated as no longer suitable for interaction with the user. For 332 // example, it may be marked non-visible, cannot be focused, etc. All worker 333 // threads are also frozen bringing them to a complete stop. A window can 334 // have Freeze() called multiple times and will only thaw after a matching 335 // number of Thaw() calls. 336 void Freeze(bool aIncludeSubWindows = true); 337 void Thaw(bool aIncludeSubWindows = true); 338 virtual bool IsFrozen() const override; 339 virtual bool HasActiveIndexedDBDatabases() const override; 340 virtual bool HasActivePeerConnections() override; 341 virtual bool HasOpenWebSockets() const override; 342 void AudioPlaybackChanged(bool aIsPlayingAudio); 343 virtual bool HasScheduledNormalOrHighPriorityWebTasks() const override; 344 void SyncStateFromParentWindow(); 345 virtual void UpdateWebSocketCount(int32_t aDelta) override; 346 // Increase/Decrease the number of active IndexedDB databases for the 347 // decision making of timeout-throttling. 348 virtual void UpdateActiveIndexedDBDatabaseCount(int32_t aDelta) override; 349 350 // Called on the current inner window of a browsing context when its 351 // background state changes according to selected tab or visibility of the 352 // browser window. Used with Suspend()/Resume() or Freeze()/Thaw() because 353 // background state may change while the inner window is not current. 354 void UpdateBackgroundState(); 355 356 mozilla::dom::DebuggerNotificationManager* 357 GetOrCreateDebuggerNotificationManager() override; 358 359 mozilla::dom::DebuggerNotificationManager* 360 GetExistingDebuggerNotificationManager() override; 361 362 nsIURI* GetBaseURI() const final; 363 364 mozilla::Maybe<mozilla::dom::ClientInfo> GetClientInfo() const override; 365 mozilla::Maybe<mozilla::dom::ClientState> GetClientState() const final; 366 mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> GetController() 367 const override; 368 369 void SetPolicyContainer(nsIPolicyContainer* aPolicyContainer); 370 nsIPolicyContainer* GetPolicyContainer(); 371 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCsp); 372 373 virtual already_AddRefed<mozilla::dom::ServiceWorkerContainer> 374 GetServiceWorkerContainer() override; 375 376 virtual RefPtr<mozilla::dom::ServiceWorker> GetOrCreateServiceWorker( 377 const mozilla::dom::ServiceWorkerDescriptor& aDescriptor) override; 378 379 RefPtr<mozilla::dom::ServiceWorkerRegistration> GetServiceWorkerRegistration( 380 const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor) 381 const override; 382 383 RefPtr<mozilla::dom::ServiceWorkerRegistration> 384 GetOrCreateServiceWorkerRegistration( 385 const mozilla::dom::ServiceWorkerRegistrationDescriptor& aDescriptor) 386 override; 387 388 mozilla::StorageAccess GetStorageAccess() final; 389 390 nsICookieJarSettings* GetCookieJarSettings() final; 391 392 void NoteCalledRegisterForServiceWorkerScope(const nsACString& aScope); 393 394 void NoteDOMContentLoaded(); 395 396 virtual nsresult FireDelayedDOMEvents(bool aIncludeSubWindows) override; 397 398 virtual void MaybeUpdateTouchState() override; 399 400 // Inner windows only. 401 void RefreshRealmPrincipal(); 402 void RefreshReduceTimerPrecisionCallerType(); 403 404 // For accessing protected field mFullscreen 405 friend class FullscreenTransitionTask; 406 407 // Inner windows only. 408 virtual void SetHasGamepadEventListener(bool aHasGamepad = true) override; 409 void NotifyHasXRSession(); 410 bool HasUsedVR() const; 411 bool IsVRContentDetected() const; 412 bool IsVRContentPresenting() const; 413 void RequestXRPermission(); 414 void OnXRPermissionRequestAllow(); 415 void OnXRPermissionRequestCancel(); 416 417 using EventTarget::EventListenerAdded; 418 virtual void EventListenerAdded(nsAtom* aType) override; 419 using EventTarget::EventListenerRemoved; 420 virtual void EventListenerRemoved(nsAtom* aType) override; 421 422 // nsIInterfaceRequestor 423 NS_DECL_NSIINTERFACEREQUESTOR 424 425 // WebIDL interface. 426 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> IndexedGetter( 427 uint32_t aIndex); 428 429 static bool IsPrivilegedChromeWindow(JSContext*, JSObject* aObj); 430 431 static bool DeviceSensorsEnabled(JSContext*, JSObject*); 432 433 bool DoResolve( 434 JSContext* aCx, JS::Handle<JSObject*> aObj, JS::Handle<jsid> aId, 435 JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> aDesc); 436 // The return value is whether DoResolve might end up resolving the given id. 437 // If in doubt, return true. 438 static bool MayResolve(jsid aId); 439 440 void GetOwnPropertyNames(JSContext* aCx, JS::MutableHandleVector<jsid> aNames, 441 bool aEnumerableOnly, mozilla::ErrorResult& aRv); 442 443 nsPIDOMWindowOuter* GetInProcessScriptableTop() override; 444 inline nsGlobalWindowOuter* GetInProcessTopInternal(); 445 446 inline nsGlobalWindowOuter* GetInProcessScriptableTopInternal(); 447 448 already_AddRefed<mozilla::dom::BrowsingContext> GetChildWindow( 449 const nsAString& aName); 450 451 inline nsIBrowserChild* GetBrowserChild() { return mBrowserChild.get(); } 452 453 nsIScriptContext* GetContextInternal(); 454 455 nsGlobalWindowOuter* GetOuterWindowInternal() const; 456 457 bool IsChromeWindow() const { return mIsChrome; } 458 459 // GetScrollContainerFrame does not flush. Callers should do it themselves as 460 // needed, depending on which info they actually want off the scroll container 461 // frame. 462 mozilla::ScrollContainerFrame* GetScrollContainerFrame(); 463 464 nsresult Observe(nsISupports* aSubject, const char* aTopic, 465 const char16_t* aData); 466 467 void ObserveStorageNotification(mozilla::dom::StorageEvent* aEvent, 468 const char16_t* aStorageType, 469 bool aPrivateBrowsing); 470 471 static void Init(); 472 static void ShutDown(); 473 static bool IsCallerChrome(); 474 475 friend class WindowStateHolder; 476 477 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS( 478 nsGlobalWindowInner, mozilla::dom::EventTarget) 479 480 #ifdef DEBUG 481 // Call Unlink on this window. This may cause bad things to happen, so use 482 // with caution. 483 void RiskyUnlink(); 484 #endif 485 486 virtual bool TakeFocus(bool aFocus, uint32_t aFocusMethod) override; 487 MOZ_CAN_RUN_SCRIPT_BOUNDARY virtual void SetReadyForFocus() override; 488 MOZ_CAN_RUN_SCRIPT_BOUNDARY virtual void PageHidden( 489 bool aIsEnteringBFCache) override; 490 virtual nsresult DispatchAsyncHashchange(nsIURI* aOldURI, 491 nsIURI* aNewURI) override; 492 virtual nsresult DispatchSyncPopState() override; 493 494 // Inner windows only. 495 virtual void EnableDeviceSensor(uint32_t aType) override; 496 virtual void DisableDeviceSensor(uint32_t aType) override; 497 498 #if defined(MOZ_WIDGET_ANDROID) 499 virtual void EnableOrientationChangeListener() override; 500 virtual void DisableOrientationChangeListener() override; 501 #endif 502 503 void AddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const; 504 505 void CollectDOMSizesForDataDocuments(nsWindowSizes&) const; 506 void RegisterDataDocumentForMemoryReporting(Document*); 507 void UnregisterDataDocumentForMemoryReporting(Document*); 508 509 enum SlowScriptResponse { 510 ContinueSlowScript = 0, 511 ContinueSlowScriptAndKeepNotifying, 512 AlwaysContinueSlowScript, 513 KillSlowScript, 514 KillScriptGlobal 515 }; 516 SlowScriptResponse ShowSlowScriptDialog(JSContext* aCx, 517 const nsString& aAddonId, 518 const double aDuration); 519 520 // Inner windows only. 521 void AddGamepad(mozilla::dom::GamepadHandle aHandle, 522 mozilla::dom::Gamepad* aGamepad); 523 void RemoveGamepad(mozilla::dom::GamepadHandle aHandle); 524 void GetGamepads(nsTArray<RefPtr<mozilla::dom::Gamepad>>& aGamepads); 525 already_AddRefed<mozilla::dom::Promise> RequestAllGamepads( 526 mozilla::ErrorResult& aRv); 527 already_AddRefed<mozilla::dom::Gamepad> GetGamepad( 528 mozilla::dom::GamepadHandle aHandle); 529 void SetHasSeenGamepadInput(bool aHasSeen); 530 bool HasSeenGamepadInput(); 531 void SyncGamepadState(); 532 void StopGamepadHaptics(); 533 534 // Inner windows only. 535 // Enable/disable updates for gamepad input. 536 void EnableGamepadUpdates(); 537 void DisableGamepadUpdates(); 538 539 // Inner windows only. 540 // Enable/disable updates for VR 541 void EnableVRUpdates(); 542 void DisableVRUpdates(); 543 544 void StartVRActivity(); 545 void StopVRActivity(); 546 547 // Update the VR displays for this window 548 bool UpdateVRDisplays(nsTArray<RefPtr<mozilla::dom::VRDisplay>>& aDisplays); 549 550 // Inner windows only. 551 // Called to inform that the set of active VR displays has changed. 552 void NotifyActiveVRDisplaysChanged(); 553 void NotifyDetectXRRuntimesCompleted(); 554 void NotifyPresentationGenerationChanged(uint32_t aDisplayID); 555 556 void DispatchVRDisplayActivate(uint32_t aDisplayID, 557 mozilla::dom::VRDisplayEventReason aReason); 558 void DispatchVRDisplayDeactivate(uint32_t aDisplayID, 559 mozilla::dom::VRDisplayEventReason aReason); 560 void DispatchVRDisplayConnect(uint32_t aDisplayID); 561 void DispatchVRDisplayDisconnect(uint32_t aDisplayID); 562 void DispatchVRDisplayPresentChange(uint32_t aDisplayID); 563 564 #define EVENT(name_, id_, type_, struct_) \ 565 mozilla::dom::EventHandlerNonNull* GetOn##name_() { \ 566 mozilla::EventListenerManager* elm = GetExistingListenerManager(); \ 567 return elm ? elm->GetEventHandler(nsGkAtoms::on##name_) : nullptr; \ 568 } \ 569 void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler) { \ 570 mozilla::EventListenerManager* elm = GetOrCreateListenerManager(); \ 571 if (elm) { \ 572 elm->SetEventHandler(nsGkAtoms::on##name_, handler); \ 573 } \ 574 } 575 #define ERROR_EVENT(name_, id_, type_, struct_) \ 576 mozilla::dom::OnErrorEventHandlerNonNull* GetOn##name_() { \ 577 mozilla::EventListenerManager* elm = GetExistingListenerManager(); \ 578 return elm ? elm->GetOnErrorEventHandler() : nullptr; \ 579 } \ 580 void SetOn##name_(mozilla::dom::OnErrorEventHandlerNonNull* handler) { \ 581 mozilla::EventListenerManager* elm = GetOrCreateListenerManager(); \ 582 if (elm) { \ 583 elm->SetEventHandler(handler); \ 584 } \ 585 } 586 #define BEFOREUNLOAD_EVENT(name_, id_, type_, struct_) \ 587 mozilla::dom::OnBeforeUnloadEventHandlerNonNull* GetOn##name_() { \ 588 mozilla::EventListenerManager* elm = GetExistingListenerManager(); \ 589 return elm ? elm->GetOnBeforeUnloadEventHandler() : nullptr; \ 590 } \ 591 void SetOn##name_( \ 592 mozilla::dom::OnBeforeUnloadEventHandlerNonNull* handler) { \ 593 mozilla::EventListenerManager* elm = GetOrCreateListenerManager(); \ 594 if (elm) { \ 595 elm->SetEventHandler(handler); \ 596 } \ 597 } 598 #define WINDOW_ONLY_EVENT EVENT 599 #define TOUCH_EVENT EVENT 600 #include "mozilla/EventNameList.h" 601 #undef TOUCH_EVENT 602 #undef WINDOW_ONLY_EVENT 603 #undef BEFOREUNLOAD_EVENT 604 #undef ERROR_EVENT 605 #undef EVENT 606 607 nsISupports* GetParentObject() { return nullptr; } 608 609 static JSObject* CreateNamedPropertiesObject(JSContext* aCx, 610 JS::Handle<JSObject*> aProto); 611 612 mozilla::dom::WindowProxyHolder Window(); 613 mozilla::dom::WindowProxyHolder Self() { return Window(); } 614 Document* GetDocument() { return GetDoc(); } 615 void GetName(nsAString& aName, mozilla::ErrorResult& aError); 616 void SetName(const nsAString& aName, mozilla::ErrorResult& aError); 617 mozilla::dom::Location* Location() override; 618 nsHistory* GetHistory(mozilla::ErrorResult& aError); 619 mozilla::dom::CustomElementRegistry* CustomElements() override; 620 mozilla::dom::CustomElementRegistry* GetExistingCustomElements(); 621 mozilla::dom::BarProp* GetLocationbar(mozilla::ErrorResult& aError); 622 mozilla::dom::BarProp* GetMenubar(mozilla::ErrorResult& aError); 623 mozilla::dom::BarProp* GetPersonalbar(mozilla::ErrorResult& aError); 624 mozilla::dom::BarProp* GetScrollbars(mozilla::ErrorResult& aError); 625 mozilla::dom::BarProp* GetStatusbar(mozilla::ErrorResult& aError); 626 mozilla::dom::BarProp* GetToolbar(mozilla::ErrorResult& aError); 627 void GetStatus(nsAString& aStatus, mozilla::ErrorResult& aError); 628 void SetStatus(const nsAString& aStatus, mozilla::ErrorResult& aError); 629 void Close(mozilla::dom::CallerType aCallerType, 630 mozilla::ErrorResult& aError); 631 nsresult Close() override; 632 bool GetClosed(mozilla::ErrorResult& aError); 633 void Stop(mozilla::ErrorResult& aError); 634 void Focus(mozilla::dom::CallerType aCallerType, 635 mozilla::ErrorResult& aError); 636 nsresult Focus(mozilla::dom::CallerType aCallerType) override; 637 void Blur(mozilla::dom::CallerType aCallerType, mozilla::ErrorResult& aError); 638 mozilla::dom::WindowProxyHolder GetFrames(mozilla::ErrorResult& aError); 639 uint32_t Length(); 640 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> GetTop( 641 mozilla::ErrorResult& aError); 642 643 protected: 644 explicit nsGlobalWindowInner(nsGlobalWindowOuter* aOuterWindow, 645 mozilla::dom::WindowGlobalChild* aActor); 646 // Initializes the mWasOffline member variable 647 void InitWasOffline(); 648 649 public: 650 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> GetOpenerWindow( 651 mozilla::ErrorResult& aError); 652 void GetOpener(JSContext* aCx, JS::MutableHandle<JS::Value> aRetval, 653 mozilla::ErrorResult& aError); 654 void SetOpener(JSContext* aCx, JS::Handle<JS::Value> aOpener, 655 mozilla::ErrorResult& aError); 656 void GetEvent(mozilla::dom::OwningEventOrUndefined& aRetval); 657 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> GetParent( 658 mozilla::ErrorResult& aError); 659 nsPIDOMWindowOuter* GetInProcessScriptableParent() override; 660 mozilla::dom::Element* GetFrameElement(nsIPrincipal& aSubjectPrincipal, 661 mozilla::ErrorResult& aError); 662 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open( 663 const nsAString& aUrl, const nsAString& aName, const nsAString& aOptions, 664 mozilla::ErrorResult& aError); 665 int16_t Orientation(mozilla::dom::CallerType aCallerType); 666 667 already_AddRefed<mozilla::dom::Console> GetConsole(JSContext* aCx, 668 mozilla::ErrorResult& aRv); 669 670 already_AddRefed<mozilla::dom::CookieStore> CookieStore(); 671 672 mozilla::dom::DocumentPictureInPicture* GetExtantDocumentPictureInPicture() 673 override { 674 return mDocumentPiP; 675 } 676 677 mozilla::dom::DocumentPictureInPicture* DocumentPictureInPicture(); 678 679 // https://w3c.github.io/webappsec-secure-contexts/#dom-window-issecurecontext 680 bool IsSecureContext() const; 681 682 mozilla::dom::External* External(); 683 684 mozilla::dom::Worklet* GetPaintWorklet(mozilla::ErrorResult& aRv); 685 686 void GetWebExposedLocales(nsTArray<nsString>& aLocales); 687 688 mozilla::dom::IntlUtils* GetIntlUtils(mozilla::ErrorResult& aRv); 689 690 void StoreSharedWorker(mozilla::dom::SharedWorker* aSharedWorker); 691 692 void ForgetSharedWorker(mozilla::dom::SharedWorker* aSharedWorker); 693 694 public: 695 void Alert(nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& aError); 696 void Alert(const nsAString& aMessage, nsIPrincipal& aSubjectPrincipal, 697 mozilla::ErrorResult& aError); 698 bool Confirm(const nsAString& aMessage, nsIPrincipal& aSubjectPrincipal, 699 mozilla::ErrorResult& aError); 700 void Prompt(const nsAString& aMessage, const nsAString& aInitial, 701 nsAString& aReturn, nsIPrincipal& aSubjectPrincipal, 702 mozilla::ErrorResult& aError); 703 already_AddRefed<mozilla::dom::cache::CacheStorage> GetCaches( 704 mozilla::ErrorResult& aRv); 705 already_AddRefed<mozilla::dom::Promise> Fetch( 706 const mozilla::dom::RequestOrUTF8String& aInput, 707 const mozilla::dom::RequestInit& aInit, 708 mozilla::dom::CallerType aCallerType, mozilla::ErrorResult& aRv); 709 MOZ_CAN_RUN_SCRIPT void Print(mozilla::ErrorResult& aError); 710 MOZ_CAN_RUN_SCRIPT mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> 711 PrintPreview(nsIPrintSettings*, nsIWebProgressListener*, nsIDocShell*, 712 mozilla::ErrorResult&); 713 void PostMessageMoz(JSContext* aCx, JS::Handle<JS::Value> aMessage, 714 const nsAString& aTargetOrigin, 715 const mozilla::dom::Sequence<JSObject*>& aTransfer, 716 nsIPrincipal& aSubjectPrincipal, 717 mozilla::ErrorResult& aError); 718 void PostMessageMoz(JSContext* aCx, JS::Handle<JS::Value> aMessage, 719 const mozilla::dom::WindowPostMessageOptions& aOptions, 720 nsIPrincipal& aSubjectPrincipal, 721 mozilla::ErrorResult& aError); 722 723 MOZ_CAN_RUN_SCRIPT 724 int32_t SetTimeout( 725 JSContext* aCx, 726 const mozilla::dom::FunctionOrTrustedScriptOrString& aHandler, 727 int32_t aTimeout, const mozilla::dom::Sequence<JS::Value>& /* unused */, 728 nsIPrincipal* aSubjectPrincipal, mozilla::ErrorResult& aError); 729 730 MOZ_CAN_RUN_SCRIPT 731 void ClearTimeout(int32_t aHandle); 732 733 MOZ_CAN_RUN_SCRIPT 734 int32_t SetInterval( 735 JSContext* aCx, 736 const mozilla::dom::FunctionOrTrustedScriptOrString& aHandler, 737 const int32_t aTimeout, 738 const mozilla::dom::Sequence<JS::Value>& /* unused */, 739 nsIPrincipal* aSubjectPrincipal, mozilla::ErrorResult& aError); 740 741 MOZ_CAN_RUN_SCRIPT 742 void ClearInterval(int32_t aHandle); 743 void GetOrigin(nsAString& aOrigin); 744 745 MOZ_CAN_RUN_SCRIPT 746 void ReportError(JSContext* aCx, JS::Handle<JS::Value> aError, 747 mozilla::dom::CallerType aCallerType, 748 mozilla::ErrorResult& aRv); 749 750 void Atob(const nsAString& aAsciiBase64String, nsAString& aBinaryData, 751 mozilla::ErrorResult& aError); 752 void Btoa(const nsAString& aBinaryData, nsAString& aAsciiBase64String, 753 mozilla::ErrorResult& aError); 754 755 void MaybeNotifyStorageKeyUsed(); 756 757 mozilla::dom::Storage* GetSessionStorage(mozilla::ErrorResult& aError); 758 mozilla::dom::Storage* GetLocalStorage(mozilla::ErrorResult& aError); 759 mozilla::dom::Selection* GetSelection(mozilla::ErrorResult& aError); 760 mozilla::dom::IDBFactory* GetIndexedDB(JSContext* aCx, 761 mozilla::ErrorResult& aError); 762 already_AddRefed<nsDOMCSSDeclaration> GetComputedStyle( 763 mozilla::dom::Element& aElt, const nsAString& aPseudoElt, 764 mozilla::ErrorResult& aError) override; 765 mozilla::dom::VisualViewport* VisualViewport(); 766 already_AddRefed<mozilla::dom::MediaQueryList> MatchMedia( 767 const nsACString& aQuery, mozilla::dom::CallerType aCallerType, 768 mozilla::ErrorResult& aError); 769 nsScreen* Screen(); 770 bool HasScreen() const { return !!mScreen; } 771 void MoveTo(int32_t aXPos, int32_t aYPos, 772 mozilla::dom::CallerType aCallerType, 773 mozilla::ErrorResult& aError); 774 void MoveBy(int32_t aXDif, int32_t aYDif, 775 mozilla::dom::CallerType aCallerType, 776 mozilla::ErrorResult& aError); 777 void ResizeTo(int32_t aWidth, int32_t aHeight, 778 mozilla::dom::CallerType aCallerType, 779 mozilla::ErrorResult& aError); 780 void ResizeBy(int32_t aWidthDif, int32_t aHeightDif, 781 mozilla::dom::CallerType aCallerType, 782 mozilla::ErrorResult& aError); 783 void Scroll(double aXScroll, double aYScroll) { 784 ScrollTo(aXScroll, aYScroll); 785 } 786 void Scroll(const mozilla::dom::ScrollToOptions& aOptions) { 787 ScrollTo(aOptions); 788 } 789 void ScrollTo(double aXScroll, double aYScroll); 790 void ScrollTo(const mozilla::dom::ScrollToOptions& aOptions); 791 void ScrollBy(double aXScrollDif, double aYScrollDif); 792 void ScrollBy(const mozilla::dom::ScrollToOptions& aOptions); 793 void ScrollByLines(int32_t numLines, 794 const mozilla::dom::ScrollOptions& aOptions); 795 void ScrollByPages(int32_t numPages, 796 const mozilla::dom::ScrollOptions& aOptions); 797 void MozScrollSnap(); 798 double GetScrollX(mozilla::ErrorResult& aError); 799 double GetPageXOffset(mozilla::ErrorResult& aError) { 800 return GetScrollX(aError); 801 } 802 double GetScrollY(mozilla::ErrorResult& aError); 803 double GetPageYOffset(mozilla::ErrorResult& aError) { 804 return GetScrollY(aError); 805 } 806 807 int32_t GetScreenLeft(mozilla::dom::CallerType aCallerType, 808 mozilla::ErrorResult& aError) { 809 return GetScreenX(aCallerType, aError); 810 } 811 812 double ScreenEdgeSlopX() const; 813 double ScreenEdgeSlopY() const; 814 815 int32_t GetScreenTop(mozilla::dom::CallerType aCallerType, 816 mozilla::ErrorResult& aError) { 817 return GetScreenY(aCallerType, aError); 818 } 819 820 void GetScreenX(JSContext* aCx, JS::MutableHandle<JS::Value> aValue, 821 mozilla::dom::CallerType aCallerType, 822 mozilla::ErrorResult& aError); 823 void GetScreenY(JSContext* aCx, JS::MutableHandle<JS::Value> aValue, 824 mozilla::dom::CallerType aCallerType, 825 mozilla::ErrorResult& aError); 826 void GetOuterWidth(JSContext* aCx, JS::MutableHandle<JS::Value> aValue, 827 mozilla::dom::CallerType aCallerType, 828 mozilla::ErrorResult& aError); 829 void GetOuterHeight(JSContext* aCx, JS::MutableHandle<JS::Value> aValue, 830 mozilla::dom::CallerType aCallerType, 831 mozilla::ErrorResult& aError); 832 833 MOZ_CAN_RUN_SCRIPT 834 uint32_t RequestAnimationFrame(mozilla::dom::FrameRequestCallback& aCallback, 835 mozilla::ErrorResult& aError); 836 837 MOZ_CAN_RUN_SCRIPT 838 void CancelAnimationFrame(uint32_t aHandle, mozilla::ErrorResult& aError); 839 840 uint32_t RequestIdleCallback(JSContext* aCx, 841 mozilla::dom::IdleRequestCallback& aCallback, 842 const mozilla::dom::IdleRequestOptions& aOptions, 843 mozilla::ErrorResult& aError); 844 void CancelIdleCallback(uint32_t aHandle); 845 846 #ifdef MOZ_WEBSPEECH 847 mozilla::dom::SpeechSynthesis* GetSpeechSynthesis( 848 mozilla::ErrorResult& aError); 849 bool HasActiveSpeechSynthesis(); 850 #endif 851 852 mozilla::glean::Glean* Glean(); 853 mozilla::glean::GleanPings* GleanPings(); 854 855 already_AddRefed<nsDOMCSSDeclaration> GetDefaultComputedStyle( 856 mozilla::dom::Element& aElt, const nsAString& aPseudoElt, 857 mozilla::ErrorResult& aError); 858 void SizeToContent(const mozilla::dom::SizeToContentConstraints&, 859 mozilla::ErrorResult&); 860 mozilla::dom::Crypto* GetCrypto(mozilla::ErrorResult& aError); 861 nsIControllers* GetControllers(mozilla::ErrorResult& aError); 862 nsresult GetControllers(nsIControllers** aControllers) override; 863 mozilla::dom::Element* GetRealFrameElement(mozilla::ErrorResult& aError); 864 float GetMozInnerScreenX(mozilla::dom::CallerType aCallerType, 865 mozilla::ErrorResult& aError); 866 float GetMozInnerScreenY(mozilla::dom::CallerType aCallerType, 867 mozilla::ErrorResult& aError); 868 double GetDevicePixelRatio(mozilla::dom::CallerType aCallerType, 869 mozilla::ErrorResult& aError); 870 double GetDesktopToDeviceScale(mozilla::ErrorResult& aError); 871 int32_t GetScrollMinX(mozilla::ErrorResult& aError); 872 int32_t GetScrollMinY(mozilla::ErrorResult& aError); 873 int32_t GetScrollMaxX(mozilla::ErrorResult& aError); 874 int32_t GetScrollMaxY(mozilla::ErrorResult& aError); 875 bool GetFullScreen(mozilla::ErrorResult& aError); 876 bool GetFullScreen() override; 877 void SetFullScreen(bool aFullscreen, mozilla::ErrorResult& aError); 878 bool Find(const nsAString& aString, bool aCaseSensitive, bool aBackwards, 879 bool aWrapAround, bool aWholeWord, bool aSearchInFrames, 880 bool aShowDialog, mozilla::ErrorResult& aError); 881 882 bool DidFireDocElemInserted() const { return mDidFireDocElemInserted; } 883 void SetDidFireDocElemInserted() { mDidFireDocElemInserted = true; } 884 885 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> OpenDialog( 886 JSContext* aCx, const nsAString& aUrl, const nsAString& aName, 887 const nsAString& aOptions, 888 const mozilla::dom::Sequence<JS::Value>& aExtraArgument, 889 mozilla::ErrorResult& aError); 890 void UpdateCommands(const nsAString& anAction); 891 892 void GetContent(JSContext* aCx, JS::MutableHandle<JSObject*> aRetval, 893 mozilla::dom::CallerType aCallerType, 894 mozilla::ErrorResult& aError); 895 896 already_AddRefed<mozilla::dom::Promise> CreateImageBitmap( 897 const mozilla::dom::ImageBitmapSource& aImage, 898 const mozilla::dom::ImageBitmapOptions& aOptions, 899 mozilla::ErrorResult& aRv); 900 901 already_AddRefed<mozilla::dom::Promise> CreateImageBitmap( 902 const mozilla::dom::ImageBitmapSource& aImage, int32_t aSx, int32_t aSy, 903 int32_t aSw, int32_t aSh, 904 const mozilla::dom::ImageBitmapOptions& aOptions, 905 mozilla::ErrorResult& aRv); 906 907 void StructuredClone(JSContext* aCx, JS::Handle<JS::Value> aValue, 908 const mozilla::dom::StructuredSerializeOptions& aOptions, 909 JS::MutableHandle<JS::Value> aRetval, 910 mozilla::ErrorResult& aError); 911 912 // ChromeWindow bits. Do NOT call these unless your window is in 913 // fact chrome. 914 uint16_t WindowState(); 915 bool IsFullyOccluded(); 916 nsIBrowserDOMWindow* GetBrowserDOMWindow(mozilla::ErrorResult& aError); 917 void SetBrowserDOMWindow(nsIBrowserDOMWindow* aBrowserWindow, 918 mozilla::ErrorResult& aError); 919 void GetAttention(mozilla::ErrorResult& aError); 920 void GetAttentionWithCycleCount(int32_t aCycleCount, 921 mozilla::ErrorResult& aError); 922 void SetCursor(const nsACString& aCursor, mozilla::ErrorResult& aError); 923 void Maximize(); 924 void Minimize(); 925 void Restore(); 926 void GetWorkspaceID(nsAString& workspaceID); 927 void MoveToWorkspace(const nsAString& workspaceID); 928 bool IsCloaked() const; 929 void NotifyDefaultButtonLoaded(mozilla::dom::Element& aDefaultButton, 930 mozilla::ErrorResult& aError); 931 mozilla::dom::ChromeMessageBroadcaster* MessageManager(); 932 mozilla::dom::ChromeMessageBroadcaster* GetGroupMessageManager( 933 const nsAString& aGroup); 934 935 already_AddRefed<mozilla::dom::Promise> PromiseDocumentFlushed( 936 mozilla::dom::PromiseDocumentFlushedCallback& aCallback, 937 mozilla::ErrorResult& aError); 938 939 void GetInterface(JSContext* aCx, JS::Handle<JS::Value> aIID, 940 JS::MutableHandle<JS::Value> aRetval, 941 mozilla::ErrorResult& aError); 942 943 already_AddRefed<nsWindowRoot> GetWindowRoot(mozilla::ErrorResult& aError); 944 945 bool ShouldReportForServiceWorkerScope(const nsAString& aScope); 946 947 void GetInstallTrigger(JSContext* aCx, JS::MutableHandle<JSObject*> aResult); 948 949 nsIDOMWindowUtils* GetWindowUtils(mozilla::ErrorResult& aRv); 950 951 void UpdateTopInnerWindow(); 952 953 virtual bool IsInSyncOperation() override; 954 955 // Early during inner window creation, `IsSharedMemoryAllowedInternal` 956 // is called before the `mDoc` field has been initialized in order to 957 // determine whether to expose the `SharedArrayBuffer` constructor on the 958 // JS global. We still want to consider the document's principal to see if 959 // it is a privileged extension which should be exposed to 960 // `SharedArrayBuffer`, however the inner window doesn't know the document's 961 // principal yet. `aPrincipalOverride` is used in that situation to provide 962 // the principal for the to-be-loaded document. 963 bool IsSharedMemoryAllowed() const override { 964 return IsSharedMemoryAllowedInternal( 965 const_cast<nsGlobalWindowInner*>(this)->GetPrincipal()); 966 } 967 968 bool IsSharedMemoryAllowedInternal(nsIPrincipal* aPrincipal = nullptr) const; 969 970 // https://whatpr.org/html/4734/structured-data.html#cross-origin-isolated 971 bool CrossOriginIsolated() const override; 972 bool OriginAgentCluster() const; 973 974 mozilla::dom::WebTaskScheduler* Scheduler(); 975 void SetWebTaskSchedulingState( 976 mozilla::dom::WebTaskSchedulingState* aState) override; 977 mozilla::dom::WebTaskSchedulingState* GetWebTaskSchedulingState() 978 const override { 979 return mWebTaskSchedulingState; 980 } 981 982 MOZ_CAN_RUN_SCRIPT bool SynthesizeMouseEvent( 983 const nsAString& aType, float aOffsetX, float aOffsetY, 984 const mozilla::dom::SynthesizeMouseEventData& aMouseEventData, 985 const mozilla::dom::SynthesizeMouseEventOptions& aOptions, 986 const mozilla::dom::Optional< 987 mozilla::OwningNonNull<mozilla::dom::VoidFunction>>& aCallback, 988 mozilla::ErrorResult& aError); 989 990 protected: 991 // Web IDL helpers 992 993 // Redefine the property called aPropName on this window object to be a value 994 // property with the value aValue, much like we would do for a [Replaceable] 995 // property in IDL. 996 void RedefineProperty(JSContext* aCx, const char* aPropName, 997 JS::Handle<JS::Value> aValue, 998 mozilla::ErrorResult& aError); 999 1000 MOZ_CAN_RUN_SCRIPT nsresult GetInnerWidth(double* aWidth) override; 1001 MOZ_CAN_RUN_SCRIPT nsresult GetInnerHeight(double* aHeight) override; 1002 1003 public: 1004 MOZ_CAN_RUN_SCRIPT double GetInnerWidth(mozilla::ErrorResult& aError); 1005 MOZ_CAN_RUN_SCRIPT double GetInnerHeight(mozilla::ErrorResult& aError); 1006 int32_t GetScreenX(mozilla::dom::CallerType aCallerType, 1007 mozilla::ErrorResult& aError); 1008 int32_t GetScreenY(mozilla::dom::CallerType aCallerType, 1009 mozilla::ErrorResult& aError); 1010 int32_t GetOuterWidth(mozilla::dom::CallerType aCallerType, 1011 mozilla::ErrorResult& aError); 1012 int32_t GetOuterHeight(mozilla::dom::CallerType aCallerType, 1013 mozilla::ErrorResult& aError); 1014 1015 protected: 1016 friend class HashchangeCallback; 1017 friend class mozilla::dom::BarProp; 1018 1019 // Object Management 1020 virtual ~nsGlobalWindowInner(); 1021 1022 void FreeInnerObjects(); 1023 1024 // Initialize state that depends on the document. By this point, mDoc should 1025 // be set correctly and have us set as its script global object. 1026 void InitDocumentDependentState(JSContext* aCx); 1027 1028 nsresult EnsureClientSource(); 1029 nsresult ExecutionReady(); 1030 1031 // Inner windows only. 1032 nsresult DefineArgumentsProperty(nsIArray* aArguments); 1033 1034 // Get the parent, returns null if this is a toplevel window 1035 nsPIDOMWindowOuter* GetInProcessParentInternal(); 1036 1037 private: 1038 template <typename Method, typename... Args> 1039 mozilla::CallState CallOnInProcessDescendantsInternal( 1040 mozilla::dom::BrowsingContext* aBrowsingContext, bool aChildOnly, 1041 Method aMethod, Args&&... aArgs); 1042 1043 // Call the given method on the immediate children of this window. The 1044 // CallState returned by the last child method invocation is returned or 1045 // CallState::Continue if the method returns void. 1046 template <typename Method, typename... Args> 1047 mozilla::CallState CallOnInProcessChildren(Method aMethod, Args&&... aArgs) { 1048 MOZ_ASSERT(IsCurrentInnerWindow()); 1049 return CallOnInProcessDescendantsInternal(GetBrowsingContext(), true, 1050 aMethod, aArgs...); 1051 } 1052 1053 // Call the given method on the descendant of this window. The CallState 1054 // returned by the last descendant method invocation is returned or 1055 // CallState::Continue if the method returns void. 1056 template <typename Method, typename... Args> 1057 mozilla::CallState CallOnInProcessDescendants(Method aMethod, 1058 Args&&... aArgs) { 1059 return CallOnInProcessDescendantsInternal(GetBrowsingContext(), false, 1060 aMethod, aArgs...); 1061 } 1062 1063 // Helper to convert a void returning child method into an implicit 1064 // CallState::Continue value. 1065 template <typename Return, typename Method, typename... Args> 1066 typename std::enable_if<std::is_void<Return>::value, mozilla::CallState>::type 1067 CallDescendant(nsGlobalWindowInner* aWindow, Method aMethod, 1068 Args&&... aArgs) { 1069 (aWindow->*aMethod)(aArgs...); 1070 return mozilla::CallState::Continue; 1071 } 1072 1073 // Helper that passes through the CallState value from a child method. 1074 template <typename Return, typename Method, typename... Args> 1075 typename std::enable_if<std::is_same<Return, mozilla::CallState>::value, 1076 mozilla::CallState>::type 1077 CallDescendant(nsGlobalWindowInner* aWindow, Method aMethod, 1078 Args&&... aArgs) { 1079 return (aWindow->*aMethod)(aArgs...); 1080 } 1081 1082 void FreezeInternal(bool aIncludeSubWindows); 1083 void ThawInternal(bool aIncludeSubWindows); 1084 1085 mozilla::CallState ShouldReportForServiceWorkerScopeInternal( 1086 const nsACString& aScope, bool* aResultOut); 1087 1088 public: 1089 // Timeout Functions 1090 // |interval| is in milliseconds. 1091 MOZ_CAN_RUN_SCRIPT 1092 int32_t SetTimeoutOrInterval( 1093 JSContext* aCx, 1094 const mozilla::dom::FunctionOrTrustedScriptOrString& aHandler, 1095 int32_t aTimeout, const mozilla::dom::Sequence<JS::Value>& aArguments, 1096 bool aIsInterval, nsIPrincipal* aSubjectPrincipal, 1097 mozilla::ErrorResult& aError); 1098 1099 // Return true if |aTimeout| was cleared while its handler ran. 1100 MOZ_CAN_RUN_SCRIPT 1101 bool RunTimeoutHandler(mozilla::dom::Timeout* aTimeout) override; 1102 1103 // Helper Functions 1104 already_AddRefed<nsIDocShellTreeOwner> GetTreeOwner(); 1105 already_AddRefed<nsIWebBrowserChrome> GetWebBrowserChrome(); 1106 bool IsPrivateBrowsing(); 1107 1108 void FireOfflineStatusEventIfChanged(); 1109 1110 public: 1111 // Inner windows only. 1112 nsresult FireHashchange(const nsAString& aOldURL, const nsAString& aNewURL); 1113 1114 void FlushPendingNotifications(mozilla::FlushType aType); 1115 1116 void ScrollTo(const mozilla::CSSPoint& aScroll, 1117 const mozilla::dom::ScrollOptions& aOptions); 1118 1119 already_AddRefed<nsIWidget> GetMainWidget() const; 1120 nsIWidget* GetNearestWidget() const; 1121 1122 bool IsInModalState(); 1123 1124 void SetFocusedElement(mozilla::dom::Element* aElement, 1125 uint32_t aFocusMethod = 0, 1126 bool aNeedsFocus = false) override; 1127 1128 uint32_t GetFocusMethod() override; 1129 1130 bool ShouldShowFocusRing() override; 1131 1132 // Inner windows only. 1133 void UpdateCanvasFocus(bool aFocusChanged, nsIContent* aNewContent); 1134 1135 public: 1136 virtual already_AddRefed<nsPIWindowRoot> GetTopWindowRoot() override; 1137 1138 // Get the toplevel principal, returns null if this is a toplevel window. 1139 nsIPrincipal* GetTopLevelAntiTrackingPrincipal(); 1140 1141 // Get the client principal, returns null if the clientSource is not 1142 // available. 1143 nsIPrincipal* GetClientPrincipal(); 1144 1145 // Whether the chrome window is currently in a full screen transition. This 1146 // flag is updated from FullscreenTransitionTask. 1147 bool IsInFullScreenTransition(); 1148 1149 // This method is called if this window loads a 3rd party tracking resource 1150 // and the storage is just been changed. The window can reset the partitioned 1151 // storage objects and switch to the first party cookie jar. 1152 RefPtr<mozilla::GenericPromise> StorageAccessPermissionChanged(bool aGranted); 1153 1154 protected: 1155 void NotifyWindowIDDestroyed(const char* aTopic); 1156 1157 virtual void UpdateParentTarget() override; 1158 1159 // Clear the document-dependent slots on our JS wrapper. Inner windows only. 1160 void ClearDocumentDependentSlots(JSContext* aCx); 1161 1162 // Inner windows only. 1163 already_AddRefed<mozilla::dom::StorageEvent> CloneStorageEvent( 1164 const nsAString& aType, const RefPtr<mozilla::dom::StorageEvent>& aEvent, 1165 mozilla::ErrorResult& aRv); 1166 1167 protected: 1168 already_AddRefed<nsDOMCSSDeclaration> GetComputedStyleHelper( 1169 mozilla::dom::Element& aElt, const nsAString& aPseudoElt, 1170 bool aDefaultStylesOnly, mozilla::ErrorResult& aError); 1171 1172 nsGlobalWindowInner* InnerForSetTimeoutOrInterval( 1173 mozilla::ErrorResult& aError); 1174 1175 void PostMessageMoz(JSContext* aCx, JS::Handle<JS::Value> aMessage, 1176 const nsAString& aTargetOrigin, 1177 JS::Handle<JS::Value> aTransfer, 1178 nsIPrincipal& aSubjectPrincipal, 1179 mozilla::ErrorResult& aError); 1180 1181 private: 1182 // Fire the JS engine's onNewGlobalObject hook. Only used on inner windows. 1183 void FireOnNewGlobalObject(); 1184 1185 // Helper for resolving the components shim. 1186 bool ResolveComponentsShim( 1187 JSContext* aCx, JS::Handle<JSObject*> aObj, 1188 JS::MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> aDesc); 1189 1190 // nsPIDOMWindow{Inner,Outer} should be able to see these helper methods. 1191 friend class nsPIDOMWindowInner; 1192 friend class nsPIDOMWindowOuter; 1193 1194 bool IsBackgroundInternal() const override; 1195 1196 // NOTE: Chrome Only 1197 void DisconnectAndClearGroupMessageManagers() { 1198 MOZ_RELEASE_ASSERT(IsChromeWindow()); 1199 for (const auto& entry : mChromeFields.mGroupMessageManagers) { 1200 mozilla::dom::ChromeMessageBroadcaster* mm = entry.GetWeak(); 1201 if (mm) { 1202 mm->Disconnect(); 1203 } 1204 } 1205 mChromeFields.mGroupMessageManagers.Clear(); 1206 } 1207 1208 // Call mDocumentFlushedResolvers items, and perform MicroTask checkpoint 1209 // after that. 1210 // 1211 // If aUntilExhaustion is true, then we call resolvers that get added as a 1212 // result synchronously, otherwise we wait until the next refresh driver tick. 1213 void CallDocumentFlushedResolvers(bool aUntilExhaustion); 1214 1215 // Called after a refresh driver tick. See documentation of 1216 // CallDocumentFlushedResolvers for the meaning of aUntilExhaustion. 1217 // 1218 // Returns whether we need to keep observing the refresh driver or not. 1219 bool MaybeCallDocumentFlushedResolvers(bool aUntilExhaustion); 1220 1221 // Try to fire the "load" event on our content embedder if we're an iframe. 1222 MOZ_CAN_RUN_SCRIPT void FireFrameLoadEvent(); 1223 1224 void UpdateAutoplayPermission(); 1225 void UpdateShortcutsPermission(); 1226 void UpdatePopupPermission(); 1227 1228 void UpdatePermissions(); 1229 1230 public: 1231 static uint32_t GetShortcutsPermission(nsIPrincipal* aPrincipal); 1232 bool IsPlayingAudio() override; 1233 1234 // Dispatch a runnable related to the global. 1235 nsresult Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) const final; 1236 nsISerialEventTarget* SerialEventTarget() const final; 1237 1238 void DisableIdleCallbackRequests(); 1239 uint32_t LastIdleRequestHandle() const { 1240 return mIdleRequestCallbackCounter - 1; 1241 } 1242 MOZ_CAN_RUN_SCRIPT 1243 void RunIdleRequest(mozilla::dom::IdleRequest* aRequest, 1244 DOMHighResTimeStamp aDeadline, bool aDidTimeout); 1245 MOZ_CAN_RUN_SCRIPT 1246 void ExecuteIdleRequest(TimeStamp aDeadline); 1247 void ScheduleIdleRequestDispatch(); 1248 void SuspendIdleRequests(); 1249 void ResumeIdleRequests(); 1250 1251 using IdleRequests = mozilla::LinkedList<RefPtr<mozilla::dom::IdleRequest>>; 1252 void RemoveIdleCallback(mozilla::dom::IdleRequest* aRequest); 1253 1254 void SetActiveLoadingState(bool aIsLoading) override; 1255 1256 // Hint to the JS engine whether we are currently loading. 1257 void HintIsLoading(bool aIsLoading); 1258 1259 mozilla::dom::ContentMediaController* GetContentMediaController(); 1260 1261 bool TryOpenExternalProtocolIframe() { 1262 if (mHasOpenedExternalProtocolFrame) { 1263 return false; 1264 } 1265 mHasOpenedExternalProtocolFrame = true; 1266 return true; 1267 } 1268 1269 nsTArray<uint32_t>& GetScrollMarks() { return mScrollMarks; } 1270 bool GetScrollMarksOnHScrollbar() const { return mScrollMarksOnHScrollbar; } 1271 void SetScrollMarks(const nsTArray<uint32_t>& aScrollMarks, 1272 bool aOnHScrollbar); 1273 1274 // Don't use this value directly, call StorageAccess::StorageAllowedForWindow 1275 // instead. 1276 mozilla::Maybe<mozilla::StorageAccess> GetStorageAllowedCache( 1277 uint32_t& aRejectedReason) { 1278 if (mStorageAllowedCache.isSome()) { 1279 aRejectedReason = mStorageAllowedReasonCache; 1280 } 1281 return mStorageAllowedCache; 1282 } 1283 void SetStorageAllowedCache(const mozilla::StorageAccess& storageAllowed, 1284 uint32_t aRejectedReason) { 1285 mStorageAllowedCache = Some(storageAllowed); 1286 mStorageAllowedReasonCache = aRejectedReason; 1287 } 1288 void ClearStorageAllowedCache() { 1289 mStorageAllowedCache = mozilla::Nothing(); 1290 mStorageAllowedReasonCache = 0; 1291 } 1292 1293 virtual JS::loader::ModuleLoaderBase* GetModuleLoader( 1294 JSContext* aCx) override; 1295 1296 mozilla::dom::TrustedTypePolicyFactory* TrustedTypes(); 1297 1298 void SetCurrentPasteDataTransfer(mozilla::dom::DataTransfer* aDataTransfer); 1299 mozilla::dom::DataTransfer* GetCurrentPasteDataTransfer() const; 1300 1301 mozilla::dom::ClientSource* GetClientSource() const { 1302 return mClientSource.get(); 1303 } 1304 1305 private: 1306 RefPtr<mozilla::dom::ContentMediaController> mContentMediaController; 1307 1308 RefPtr<mozilla::dom::WebTaskSchedulerMainThread> mWebTaskScheduler; 1309 RefPtr<mozilla::dom::WebTaskSchedulingState> mWebTaskSchedulingState; 1310 1311 RefPtr<mozilla::dom::TrustedTypePolicyFactory> mTrustedTypePolicyFactory; 1312 1313 protected: 1314 // Whether we need to care about orientation changes. 1315 bool mHasOrientationChangeListeners : 1; 1316 1317 // Window offline status. Checked to see if we need to fire offline event 1318 bool mWasOffline : 1; 1319 1320 // Represents whether the inner window's page has had a slow script notice. 1321 // Only used by inner windows; will always be false for outer windows. 1322 // This is used to implement Telemetry measures such as 1323 // SLOW_SCRIPT_PAGE_COUNT (glean::dom::slow_script_page_count). 1324 bool mHasHadSlowScript : 1; 1325 1326 // Fast way to tell if this is a chrome window (without having to QI). 1327 bool mIsChrome : 1; 1328 1329 // Hack to indicate whether a chrome window needs its message manager 1330 // to be disconnected, since clean up code is shared in the global 1331 // window superclass. 1332 bool mCleanMessageManager : 1; 1333 1334 // Indicates that the current document has never received a document focus 1335 // event. 1336 bool mNeedsFocus : 1; 1337 1338 // true if tab navigation has occurred for this window. Focus rings 1339 // should be displayed. 1340 bool mFocusByKeyOccurred : 1; 1341 1342 // True if we have notified document-element-inserted observers for this 1343 // document. 1344 bool mDidFireDocElemInserted : 1; 1345 1346 // Indicates whether this window wants gamepad input events 1347 bool mHasGamepad : 1; 1348 1349 // Indicates whether this window has content that has an XR session 1350 // An XR session results in enumeration and activation of XR devices. 1351 bool mHasXRSession : 1; 1352 1353 // Indicates whether this window wants VRDisplayActivate events 1354 bool mHasVRDisplayActivateEvents : 1; 1355 1356 // Indicates that a request for XR runtime detection has been 1357 // requested, but has not yet been resolved 1358 bool mXRRuntimeDetectionInFlight : 1; 1359 1360 // Indicates that an XR permission request has been requested 1361 // but has not yet been resolved. 1362 bool mXRPermissionRequestInFlight : 1; 1363 1364 // Indicates that an XR permission request has been granted. 1365 // The page should not request permission multiple times. 1366 bool mXRPermissionGranted : 1; 1367 1368 // True if this was the currently-active inner window for a BrowsingContext at 1369 // the time it was discarded. 1370 bool mWasCurrentInnerWindow : 1; 1371 void SetWasCurrentInnerWindow() { mWasCurrentInnerWindow = true; } 1372 bool WasCurrentInnerWindow() const override { return mWasCurrentInnerWindow; } 1373 1374 bool mHasSeenGamepadInput : 1; 1375 1376 // Whether we told the JS engine that we were in pageload. 1377 bool mHintedWasLoading : 1; 1378 1379 // Whether this window has opened an external-protocol iframe without user 1380 // activation once already. Only relevant for top windows. 1381 bool mHasOpenedExternalProtocolFrame : 1; 1382 1383 bool mScrollMarksOnHScrollbar : 1; 1384 1385 nsCheapSet<nsUint32HashKey> mGamepadIndexSet; 1386 nsRefPtrHashtable<nsGenericHashKey<mozilla::dom::GamepadHandle>, 1387 mozilla::dom::Gamepad> 1388 mGamepads; 1389 1390 RefPtr<nsScreen> mScreen; 1391 1392 RefPtr<mozilla::dom::BarProp> mMenubar; 1393 RefPtr<mozilla::dom::BarProp> mToolbar; 1394 RefPtr<mozilla::dom::BarProp> mLocationbar; 1395 RefPtr<mozilla::dom::BarProp> mPersonalbar; 1396 RefPtr<mozilla::dom::BarProp> mStatusbar; 1397 RefPtr<mozilla::dom::BarProp> mScrollbars; 1398 1399 RefPtr<nsGlobalWindowObserver> mObserver; 1400 RefPtr<mozilla::dom::Crypto> mCrypto; 1401 RefPtr<mozilla::dom::cache::CacheStorage> mCacheStorage; 1402 RefPtr<mozilla::dom::Console> mConsole; 1403 RefPtr<mozilla::dom::CookieStore> mCookieStore; 1404 RefPtr<mozilla::dom::DocumentPictureInPicture> mDocumentPiP; 1405 RefPtr<mozilla::dom::Worklet> mPaintWorklet; 1406 RefPtr<mozilla::dom::External> mExternal; 1407 1408 RefPtr<mozilla::dom::Storage> mLocalStorage; 1409 RefPtr<mozilla::dom::Storage> mSessionStorage; 1410 1411 RefPtr<mozilla::EventListenerManager> mListenerManager; 1412 RefPtr<mozilla::dom::Location> mLocation; 1413 RefPtr<nsHistory> mHistory; 1414 RefPtr<mozilla::dom::CustomElementRegistry> mCustomElements; 1415 1416 nsTObserverArray<RefPtr<mozilla::dom::SharedWorker>> mSharedWorkers; 1417 1418 RefPtr<mozilla::dom::VisualViewport> mVisualViewport; 1419 1420 // The document's principals and policyContainer are only stored if 1421 // FreeInnerObjects has been called. 1422 nsCOMPtr<nsIPrincipal> mDocumentPrincipal; 1423 nsCOMPtr<nsIPrincipal> mDocumentCookiePrincipal; 1424 nsCOMPtr<nsIPrincipal> mDocumentStoragePrincipal; 1425 nsCOMPtr<nsIPrincipal> mDocumentPartitionedPrincipal; 1426 nsCOMPtr<nsIPolicyContainer> mDocumentPolicyContainer; 1427 1428 // Used to cache the result of StorageAccess::StorageAllowedForWindow. 1429 // Don't use this field directly, use StorageAccess::StorageAllowedForWindow 1430 // instead. 1431 mozilla::Maybe<mozilla::StorageAccess> mStorageAllowedCache; 1432 uint32_t mStorageAllowedReasonCache; 1433 1434 // When window associated storage is accessed we need to notify the parent 1435 // process. This flag is used to ensure we only do it once per window 1436 // lifetime. 1437 bool hasNotifiedStorageKeyUsed{false}; 1438 1439 RefPtr<mozilla::dom::DebuggerNotificationManager> 1440 mDebuggerNotificationManager; 1441 1442 // mBrowserChild is only ever populated in the content process. 1443 nsCOMPtr<nsIBrowserChild> mBrowserChild; 1444 1445 uint32_t mSuspendDepth; 1446 uint32_t mFreezeDepth; 1447 1448 #ifdef DEBUG 1449 uint32_t mSerial; 1450 #endif 1451 1452 // the method that was used to focus mFocusedElement 1453 uint32_t mFocusMethod; 1454 1455 // Only relevant if we're listening for orientation changes. 1456 int16_t mOrientationAngle = 0; 1457 1458 // The current idle request callback handle 1459 uint32_t mIdleRequestCallbackCounter; 1460 IdleRequests mIdleRequestCallbacks; 1461 RefPtr<IdleRequestExecutor> mIdleRequestExecutor; 1462 1463 #ifdef DEBUG 1464 nsCOMPtr<nsIURI> mLastOpenedURI; 1465 #endif 1466 1467 RefPtr<mozilla::dom::IDBFactory> mIndexedDB; 1468 1469 // This flag keeps track of whether this window is currently 1470 // observing refresh notifications from the refresh driver. 1471 bool mObservingRefresh; 1472 1473 bool mIteratingDocumentFlushedResolvers; 1474 1475 bool TryToObserveRefresh(); 1476 1477 nsTArray<uint32_t> mEnabledSensors; 1478 1479 #ifdef MOZ_WEBSPEECH 1480 RefPtr<mozilla::dom::SpeechSynthesis> mSpeechSynthesis; 1481 #endif 1482 1483 RefPtr<mozilla::glean::Glean> mGlean; 1484 RefPtr<mozilla::glean::GleanPings> mGleanPings; 1485 1486 // This is the CC generation the last time we called CanSkip. 1487 uint32_t mCanSkipCCGeneration; 1488 1489 // The VR Displays for this window 1490 nsTArray<RefPtr<mozilla::dom::VRDisplay>> mVRDisplays; 1491 1492 RefPtr<mozilla::dom::VREventObserver> mVREventObserver; 1493 1494 // The number of unload and beforeunload event listeners registered on this 1495 // window. 1496 uint64_t mUnloadOrBeforeUnloadListenerCount = 0; 1497 1498 RefPtr<mozilla::dom::IntlUtils> mIntlUtils; 1499 1500 mozilla::UniquePtr<mozilla::dom::ClientSource> mClientSource; 1501 1502 nsTArray<mozilla::UniquePtr<PromiseDocumentFlushedResolver>> 1503 mDocumentFlushedResolvers; 1504 1505 nsTArray<uint32_t> mScrollMarks; 1506 1507 nsTArray<mozilla::WeakPtr<Document>> mDataDocumentsForMemoryReporting; 1508 1509 static InnerWindowByIdTable* sInnerWindowsById; 1510 1511 // Members in the mChromeFields member should only be used in chrome windows. 1512 // All accesses to this field should be guarded by a check of mIsChrome. 1513 struct ChromeFields { 1514 RefPtr<mozilla::dom::ChromeMessageBroadcaster> mMessageManager; 1515 nsRefPtrHashtable<nsStringHashKey, mozilla::dom::ChromeMessageBroadcaster> 1516 mGroupMessageManagers{1}; 1517 } mChromeFields; 1518 1519 // Cache the DataTransfer created for a paste event, this will be reset after 1520 // the event is dispatched. 1521 RefPtr<mozilla::dom::DataTransfer> mCurrentPasteDataTransfer; 1522 1523 // These fields are used by the inner and outer windows to prevent 1524 // programatically moving the window while the mouse is down. 1525 static bool sMouseDown; 1526 static bool sDragServiceDisabled; 1527 1528 friend class nsDOMWindowUtils; 1529 friend class mozilla::dom::PostMessageEvent; 1530 friend class mozilla::dom::TimeoutManager; 1531 friend class IdleRequestExecutor; 1532 friend class nsGlobalWindowOuter; 1533 }; 1534 1535 inline nsISupports* ToSupports(nsGlobalWindowInner* p) { 1536 return static_cast<mozilla::dom::EventTarget*>(p); 1537 } 1538 1539 inline nsISupports* ToCanonicalSupports(nsGlobalWindowInner* p) { 1540 return static_cast<mozilla::dom::EventTarget*>(p); 1541 } 1542 1543 // XXX: EWW - This is an awful hack - let's not do this 1544 #include "nsGlobalWindowOuter.h" 1545 1546 inline nsIGlobalObject* nsGlobalWindowInner::GetOwnerGlobal() const { 1547 return const_cast<nsGlobalWindowInner*>(this); 1548 } 1549 1550 inline nsGlobalWindowOuter* nsGlobalWindowInner::GetInProcessTopInternal() { 1551 nsGlobalWindowOuter* outer = GetOuterWindowInternal(); 1552 nsCOMPtr<nsPIDOMWindowOuter> top = outer ? outer->GetInProcessTop() : nullptr; 1553 if (top) { 1554 return nsGlobalWindowOuter::Cast(top); 1555 } 1556 return nullptr; 1557 } 1558 1559 inline nsGlobalWindowOuter* 1560 nsGlobalWindowInner::GetInProcessScriptableTopInternal() { 1561 nsPIDOMWindowOuter* top = GetInProcessScriptableTop(); 1562 return nsGlobalWindowOuter::Cast(top); 1563 } 1564 1565 inline nsIScriptContext* nsGlobalWindowInner::GetContextInternal() { 1566 if (mOuterWindow) { 1567 return GetOuterWindowInternal()->mContext; 1568 } 1569 1570 return nullptr; 1571 } 1572 1573 inline nsGlobalWindowOuter* nsGlobalWindowInner::GetOuterWindowInternal() 1574 const { 1575 return nsGlobalWindowOuter::Cast(GetOuterWindow()); 1576 } 1577 1578 #endif /* nsGlobalWindowInner_h___ */