Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

89.6 KB
Raw Blame
diff --git a/browser/app/winlauncher/LauncherProcessWin.cpp b/browser/app/winlauncher/LauncherProcessWin.cpp
index 3734e1d3eba29d4e939bce3346a9e8e7590420ce..c46b5a7670b10e308a4e1096aa710cac90056d55 100644
--- a/browser/app/winlauncher/LauncherProcessWin.cpp
+++ b/browser/app/winlauncher/LauncherProcessWin.cpp
@@ -20,6 +20,7 @@
 #include "nsWindowsHelpers.h"
 #include "mozilla/mscom/ProcessRuntime.h"
 
+#include <io.h>
 #include <windows.h>
 #include <processthreadsapi.h>
 #include <shlwapi.h>
@@ -577,8 +578,18 @@ Maybe<int> LauncherMain(int& argc, wchar_t* argv[]) {
   HANDLE stdHandles[] = {::GetStdHandle(STD_INPUT_HANDLE),
                          ::GetStdHandle(STD_OUTPUT_HANDLE),
                          ::GetStdHandle(STD_ERROR_HANDLE)};
-
   attrs.AddInheritableHandles(stdHandles);
+  // Playwright pipe installation.
+  bool hasJugglerPipe =
+      mozilla::CheckArg(argc, argv, "juggler-pipe", nullptr,
+                        mozilla::CheckArgFlag::None) == mozilla::ARG_FOUND;
+  if (hasJugglerPipe) {
+    intptr_t stdio3 = _get_osfhandle(3);
+    intptr_t stdio4 = _get_osfhandle(4);
+    HANDLE pipeHandles[] = {reinterpret_cast<HANDLE>(stdio3),
+                            reinterpret_cast<HANDLE>(stdio4)};
+    attrs.AddInheritableHandles(pipeHandles);
+  }
 
   DWORD creationFlags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;
 
diff --git a/browser/installer/allowed-dupes.mn b/browser/installer/allowed-dupes.mn
index 36b2c03e9a19e9305f07d925cb6e1058f51cc159..aae8e86732534646f10416957eb7a5eb6f828180 100644
--- a/browser/installer/allowed-dupes.mn
+++ b/browser/installer/allowed-dupes.mn
@@ -66,6 +66,12 @@ browser/chrome/browser/builtin-addons/webcompat/shims/empty-shim.txt
 removed-files
 #endif
 
+# Juggler/marionette files
+chrome/juggler/content/content/floating-scrollbars.css
+browser/chrome/devtools/skin/floating-scrollbars-responsive-design.css
+chrome/juggler/content/server/stream-utils.js
+chrome/marionette/content/stream-utils.js
+
 # Bug 1606928 - There's no reliable way to connect Top Sites favicons with the favicons in the Search Service
 browser/chrome/browser/content/activity-stream/data/content/tippytop/favicons/allegro-pl.ico
 browser/defaults/settings/main/search-config-icons/96327a73-c433-5eb4-a16d-b090cadfb80b
diff --git a/browser/installer/package-manifest.in b/browser/installer/package-manifest.in
index ae503c243ce915091d893d68b17af4e2263bbaf9..8d4574d8db446221ca46aaad3d74b70d8f8e0f25 100644
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -197,6 +197,9 @@
 @RESPATH@/chrome/remote.manifest
 #endif
 
+@RESPATH@/chrome/juggler@JAREXT@
+@RESPATH@/chrome/juggler.manifest
+
 ; Modules
 @RESPATH@/browser/modules/*
 @RESPATH@/modules/*
diff --git a/docshell/base/BrowsingContext.cpp b/docshell/base/BrowsingContext.cpp
index a0a7b8df9ce619e15064e2a83411b619b979a4dc..d0399abb90ad6c5036ff2b631f96276f199cdea1 100644
--- a/docshell/base/BrowsingContext.cpp
+++ b/docshell/base/BrowsingContext.cpp
@@ -122,8 +122,11 @@ struct ParamTraits<mozilla::dom::DisplayMode>
 
 template <>
 struct ParamTraits<mozilla::dom::PrefersColorSchemeOverride>
-    : public mozilla::dom::WebIDLEnumSerializer<
-          mozilla::dom::PrefersColorSchemeOverride> {};
+    : public mozilla::dom::WebIDLEnumSerializer<mozilla::dom::PrefersColorSchemeOverride> {};
+
+template <>
+struct ParamTraits<mozilla::dom::PrefersContrastOverride>
+    : public mozilla::dom::WebIDLEnumSerializer<mozilla::dom::PrefersContrastOverride> {};
 
 template <>
 struct ParamTraits<mozilla::dom::ForcedColorsOverride>
@@ -491,7 +494,11 @@ already_AddRefed<BrowsingContext> BrowsingContext::CreateDetached(
 
   fields.Get<IDX_UseErrorPages>() = true;
 
-  fields.Get<IDX_TouchEventsOverrideInternal>() = TouchEventsOverride::None;
+  // Playwright: make sure touch events override is propagated to the nested
+  // browsing context. See https://bugzilla.mozilla.org/show_bug.cgi?id=2014330
+  fields.Get<IDX_TouchEventsOverrideInternal>() =
+      inherit ? inherit->GetTouchEventsOverrideInternal() :
+      TouchEventsOverride::None;
 
   fields.Get<IDX_AllowJavascript>() =
       inherit ? inherit->GetAllowJavascript() : true;
@@ -3626,6 +3633,15 @@ void BrowsingContext::DidSet(FieldIndex<IDX_LanguageOverride>,
   });
 }
 
+void BrowsingContext::DidSet(FieldIndex<IDX_PrefersContrastOverride>,
+                             dom::PrefersContrastOverride aOldValue) {
+  MOZ_ASSERT(IsTop());
+  if (PrefersContrastOverride() == aOldValue) {
+    return;
+  }
+  PresContextAffectingFieldChanged();
+}
+
 void BrowsingContext::DidSet(FieldIndex<IDX_MediumOverride>,
                              nsString&& aOldValue) {
   MOZ_ASSERT(IsTop());
@@ -3921,7 +3937,7 @@ void BrowsingContext::SetGeolocationServiceOverride(
   if (aGeolocationOverride.WasPassed()) {
     if (!mGeolocationServiceOverride) {
       mGeolocationServiceOverride = MakeRefPtr<GeolocationService>();
-      mGeolocationServiceOverride->Init();
+      mGeolocationServiceOverride->Init(true /* isOverride */);
     }
     mGeolocationServiceOverride->Update(aGeolocationOverride.Value());
   } else if (RefPtr<GeolocationService> serviceOverride =
diff --git a/docshell/base/BrowsingContext.h b/docshell/base/BrowsingContext.h
index 9cecca7627686be6bcc297cdedd342332b2a07c3..8601d1753e0c49bb86bcb6ad77e04f1a6af6792b 100644
--- a/docshell/base/BrowsingContext.h
+++ b/docshell/base/BrowsingContext.h
@@ -258,6 +258,8 @@ struct EmbedderColorSchemes {
    * scrollbars clear the rounded content-area corners. */                    \
   FIELD(EmbedderScrollbarInset, LayoutDeviceIntMargin)                        \
   FIELD(DisplayMode, dom::DisplayMode)                                        \
+  /* playwright addition */                                                   \
+  FIELD(PrefersContrastOverride, dom::PrefersContrastOverride)                \
   /* The number of entries added to the session history because of this       \
    * browsing context. */                                                     \
   FIELD(HistoryEntryCount, uint32_t)                                          \
@@ -1127,6 +1129,10 @@ class BrowsingContext : public nsILoadContext, public nsWrapperCache {
     return Top()->GetAnimationsPlayBackRateMultiplier();
   }
 
+  dom::PrefersContrastOverride PrefersContrastOverride() const {
+    return GetPrefersContrastOverride();
+  }
+
   bool IsInBFCache() const;
   bool IsEnteringBFCache() const { return mIsEnteringBFCache; }
   void DeactivateDocuments();
@@ -1352,6 +1358,11 @@ class BrowsingContext : public nsILoadContext, public nsWrapperCache {
     return IsTop();
   }
 
+  bool CanSet(FieldIndex<IDX_PrefersContrastOverride>,
+              dom::PrefersContrastOverride, ContentParent*) {
+    return IsTop();
+  }
+
   bool CanSet(FieldIndex<IDX_ForcedColorsOverride>, dom::ForcedColorsOverride,
               ContentParent*) {
     return IsTop();
@@ -1395,6 +1406,9 @@ class BrowsingContext : public nsILoadContext, public nsWrapperCache {
   void DidSet(FieldIndex<IDX_AnimationsPlayBackRateMultiplier>,
               double aOldValue);
 
+  void DidSet(FieldIndex<IDX_PrefersContrastOverride>,
+              dom::PrefersContrastOverride aOldValue);
+
   template <typename Callback>
   void WalkPresContexts(Callback&&);
   void PresContextAffectingFieldChanged();
diff --git a/docshell/base/CanonicalBrowsingContext.cpp b/docshell/base/CanonicalBrowsingContext.cpp
index 941d5c2533f8ed087af1153a7af7863c96df885b..8ec48ce2cc176e4742bbfb88b8699af17f7069a2 100644
--- a/docshell/base/CanonicalBrowsingContext.cpp
+++ b/docshell/base/CanonicalBrowsingContext.cpp
@@ -316,6 +316,23 @@ void CanonicalBrowsingContext::ReplacedBy(
   txn.SetInnerSizeSpoofedForRFP(GetInnerSizeSpoofedForRFP());
   txn.SetIPAddressSpace(GetIPAddressSpace());
   txn.SetParentalControlsEnabled(GetParentalControlsEnabled());
+  // Playwright: propagate emulation overrides to the replacement context,
+  // e.g. on a cross-origin-opener-policy navigation. Touch events override
+  // is tracked in https://bugzilla.mozilla.org/show_bug.cgi?id=2014330
+  txn.SetPrefersReducedMotionOverride(GetPrefersReducedMotionOverride());
+  txn.SetForcedColorsOverride(GetForcedColorsOverride());
+  txn.SetPrefersColorSchemeOverride(GetPrefersColorSchemeOverride());
+  txn.SetPrefersContrastOverride(GetPrefersContrastOverride());
+  txn.SetMediumOverride(GetMediumOverride());
+  txn.SetOverrideDPPX(GetOverrideDPPX());
+  txn.SetTouchEventsOverrideInternal(GetTouchEventsOverrideInternal());
+  txn.SetInRDMPane(GetInRDMPane());
+  txn.SetHasScreenAreaOverride(GetHasScreenAreaOverride());
+  txn.SetScreenWidthOverride(GetScreenWidthOverride());
+  txn.SetScreenHeightOverride(GetScreenHeightOverride());
+  txn.SetHasOrientationOverride(GetHasOrientationOverride());
+  txn.SetCurrentOrientationType(GetCurrentOrientationType());
+  txn.SetCurrentOrientationAngle(GetCurrentOrientationAngle());
 
   if (!GetLanguageOverride().IsEmpty()) {
     // Reapply language override to update the corresponding realm.
@@ -1997,6 +2014,12 @@ void CanonicalBrowsingContext::LoadURI(nsIURI* aURI,
     (void)SetIsCaptivePortalTab(true);
   }
 
+  {
+    nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
+    if (observerService) {
+      observerService->NotifyObservers(ToSupports(this), "juggler-navigation-started-browser", NS_ConvertASCIItoUTF16(nsPrintfCString("%" PRIu64, loadState->GetLoadIdentifier())).get());
+    }
+  }
   LoadURI(loadState, true);
 }
 
diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp
index 5be2ef463856367597184671034c24117ed3b6d6..30a5dded874aeb39647cbbbbccf1d4a5d0e5ab1f 100644
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -354,6 +354,9 @@ nsDocShell::nsDocShell(BrowsingContext* aBrowsingContext,
       mAllowDNSPrefetch(true),
       mAllowWindowControl(true),
       mCSSErrorReportingEnabled(false),
+      mOverrideHasFocus(false),
+      mBypassCSPEnabled(false),
+      mForceActiveState(false),
       mAllowAuth(mItemType == typeContent),
       mAllowKeywordFixup(false),
       mDisableMetaRefreshWhenInactive(false),
@@ -2979,6 +2982,65 @@ nsDocShell::GetMessageManager(ContentFrameMessageManager** aMessageManager) {
   return NS_OK;
 }
 
+// =============== Juggler Begin =======================
+
+nsDocShell* nsDocShell::GetRootDocShell() {
+  nsCOMPtr<nsIDocShellTreeItem> rootAsItem;
+  GetInProcessSameTypeRootTreeItem(getter_AddRefs(rootAsItem));
+  nsCOMPtr<nsIDocShell> rootShell = do_QueryInterface(rootAsItem);
+  return nsDocShell::Cast(rootShell);
+}
+
+NS_IMETHODIMP
+nsDocShell::GetBypassCSPEnabled(bool* aEnabled) {
+  MOZ_ASSERT(aEnabled);
+  *aEnabled = mBypassCSPEnabled;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDocShell::SetBypassCSPEnabled(bool aEnabled) {
+  mBypassCSPEnabled = aEnabled;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDocShell::GetForceActiveState(bool* aEnabled) {
+  MOZ_ASSERT(aEnabled);
+  *aEnabled = mForceActiveState;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDocShell::SetForceActiveState(bool aEnabled) {
+  mForceActiveState = aEnabled;
+  ActivenessMaybeChanged();
+  return NS_OK;
+}
+
+bool nsDocShell::IsBypassCSPEnabled() {
+  return GetRootDocShell()->mBypassCSPEnabled;
+}
+
+NS_IMETHODIMP
+nsDocShell::GetOverrideHasFocus(bool* aEnabled) {
+  MOZ_ASSERT(aEnabled);
+  *aEnabled = mOverrideHasFocus;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDocShell::SetOverrideHasFocus(bool aEnabled) {
+  mOverrideHasFocus = aEnabled;
+  return NS_OK;
+}
+
+bool nsDocShell::ShouldOverrideHasFocus() const {
+  return mOverrideHasFocus;
+}
+
+// =============== Juggler End =======================
+
 NS_IMETHODIMP
 nsDocShell::GetIsNavigating(bool* aOut) {
   *aOut = mIsNavigating;
@@ -4706,7 +4768,7 @@ nsDocShell::GetVisibility(bool* aVisibility) {
 }
 
 void nsDocShell::ActivenessMaybeChanged() {
-  const bool isActive = mBrowsingContext->IsActive();
+  const bool isActive = mForceActiveState || mBrowsingContext->IsActive();
   if (RefPtr<PresShell> presShell = GetPresShell()) {
     presShell->ActivenessMaybeChanged();
   }
@@ -8998,6 +9060,16 @@ nsresult nsDocShell::InternalLoad(nsDocShellLoadState* aLoadState,
   attrs.SetFirstPartyDomain(isTopLevelDoc, aLoadState->URI());
 
   nsCOMPtr<nsIRequest> req;
+
+  // Juggler: report navigation started for non-same-document and non-javascript
+  // navigations.
+  if (!isJavaScript && !sameDocument) {
+    nsCOMPtr<nsIObserverService> observerService =
+        mozilla::services::GetObserverService();
+    if (observerService) {
+      observerService->NotifyObservers(GetAsSupports(this), "juggler-navigation-started-renderer", NS_ConvertASCIItoUTF16(nsPrintfCString("%" PRIu64, aLoadState->GetLoadIdentifier())).get());
+    }
+  }
   rv = DoURILoad(aLoadState, aCacheKey, getter_AddRefs(req));
 
   if (NS_SUCCEEDED(rv)) {
@@ -12115,6 +12187,9 @@ class OnLinkClickEvent : public CancelableRunnable, public SupportsWeakPtr {
       mHandler->OnLinkClickSync(mContent, mLoadState, mNoOpenerImplied,
                                 mTriggeringPrincipal);
     }
+    nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
+    observerService->NotifyObservers(ToSupports(mContent), "juggler-link-click-sync", nullptr);
+
     return NS_OK;
   }
 
@@ -12186,6 +12261,11 @@ nsresult nsDocShell::OnFormSubmit(HTMLFormElement* aForm,
     return OnLinkClickSync(aForm, aLoadState, false, aForm->NodePrincipal());
   }
 
+  nsCOMPtr<nsIObserverService> observerService =
+      mozilla::services::GetObserverService();
+  observerService->NotifyObservers(ToSupports(aForm), "juggler-link-click",
+                                   nullptr);
+
   auto result = OnLinkClickWithLoadState(aForm, aLoadState, false,
                                          aForm->NodePrincipal());
   if (result.isErr()) {
@@ -12324,6 +12404,8 @@ nsresult nsDocShell::OnLinkClick(
       ownerDoc->GetScriptTrackingFlags());
   loadState->SetHistoryBehavior(NavigationHistoryBehavior::Auto);
 
+  nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
+  observerService->NotifyObservers(ToSupports(aContent), "juggler-link-click", nullptr);
   auto result = OnLinkClickWithLoadState(aContent, loadState, noOpenerImplied,
                                          aTriggeringPrincipal);
   return result.isErr() ? result.unwrapErr() : NS_OK;
diff --git a/docshell/base/nsDocShell.h b/docshell/base/nsDocShell.h
index 27d9e920d135d8f94971cf303ef7ba3bfe4d512e..c298a90e271ffc26566fd78dce6e462fedb9f76c 100644
--- a/docshell/base/nsDocShell.h
+++ b/docshell/base/nsDocShell.h
@@ -384,6 +384,10 @@ class nsDocShell final : public nsDocLoader,
   void SetWillChangeProcess() { mWillChangeProcess = true; }
   bool WillChangeProcess() { return mWillChangeProcess; }
 
+  bool ShouldOverrideHasFocus() const;
+
+  bool IsBypassCSPEnabled();
+
   // Creates a real network channel (not a DocumentChannel) using the specified
   // parameters.
   // Used by nsDocShell when not using DocumentChannel, by DocumentLoadListener
@@ -1002,6 +1006,8 @@ class nsDocShell final : public nsDocLoader,
 
   bool CSSErrorReportingEnabled() const { return mCSSErrorReportingEnabled; }
 
+  nsDocShell* GetRootDocShell();
+
   // Handles retrieval of subframe session history for nsDocShell::LoadURI. If a
   // load is requested in a subframe of the current DocShell, the subframe
   // loadType may need to reflect the loadType of the parent document, or in
@@ -1336,6 +1342,10 @@ class nsDocShell final : public nsDocLoader,
   bool mAllowDNSPrefetch : 1;
   bool mAllowWindowControl : 1;
   bool mCSSErrorReportingEnabled : 1;
+  bool mOverrideHasFocus : 1;
+  bool mBypassCSPEnabled : 1;
+  bool mForceActiveState : 1;
+
   bool mAllowAuth : 1;
   bool mAllowKeywordFixup : 1;
   bool mDisableMetaRefreshWhenInactive : 1;
diff --git a/docshell/base/nsIDocShell.idl b/docshell/base/nsIDocShell.idl
index 011f9aef571fc0b1d5224fb2b321082af605509a..8bd2ddd6d4ecf0347abc21a02beab383a24ca7ee 100644
--- a/docshell/base/nsIDocShell.idl
+++ b/docshell/base/nsIDocShell.idl
@@ -685,6 +685,12 @@ interface nsIDocShell : nsIDocShellTreeItem
    */
   void synchronizeLayoutHistoryState();
 
+  attribute boolean overrideHasFocus;
+
+  attribute boolean bypassCSPEnabled;
+
+  attribute boolean forceActiveState;
+
   /**
    * This attempts to save any applicable layout history state (like
    * scroll position) in the nsISHEntry. This is normally done
diff --git a/dom/base/Document.cpp b/dom/base/Document.cpp
index 360645185a5a3dd6cf1d107c88b114a6f05445ab..b3658c0fb3ef5f64c9a8f09d77a04c540076ec48 100644
--- a/dom/base/Document.cpp
+++ b/dom/base/Document.cpp
@@ -3864,6 +3864,9 @@ void Document::SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages) {
 }
 
 void Document::ApplySettingsFromCSP(bool aSpeculative) {
+  if (mDocumentContainer && mDocumentContainer->IsBypassCSPEnabled())
+    return;
+
   nsresult rv = NS_OK;
   if (!aSpeculative) {
     nsIContentSecurityPolicy* csp = PolicyContainer::GetCSP(mPolicyContainer);
@@ -4000,6 +4003,14 @@ nsresult Document::InitCSP(nsIChannel* aChannel) {
     return rv;
   }
 
+  // Juggler: keep the empty CSP object, since callers rely on every document
+  // having one (e.g. PerformTrustedTypesPreNavigationCheck), but never apply
+  // any policies to it.
+  nsCOMPtr<nsIDocShell> shell(mDocumentContainer);
+  if (shell && nsDocShell::Cast(shell)->IsBypassCSPEnabled()) {
+    return NS_OK;
+  }
+
   nsCOMPtr<nsIPrincipal> principal = NodePrincipal();
   if ((principal->IsSystemPrincipal() ||
        (mDocumentURI && mDocumentURI->SchemeIs("chrome"))) &&
@@ -4991,6 +5002,10 @@ bool Document::HasFocus(ErrorResult& rv) const {
     return false;
   }
 
+  if (IsActive() && mDocumentContainer->ShouldOverrideHasFocus()) {
+    return true;
+  }
+
   if (!fm->IsInActiveWindow(bc)) {
     return false;
   }
diff --git a/dom/base/Navigator.cpp b/dom/base/Navigator.cpp
index f822db52921c5ec85d246431a0555ee11e1c7672..81d421990b75bca470e042a123b0f799bb7ba11f 100644
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -2376,7 +2376,8 @@ bool Navigator::Webdriver() {
   }
 #endif
 
-  return false;
+  // Playwright is automating the browser, so we should pretend to be a webdriver
+  return true;
 }
 
 AutoplayPolicy Navigator::GetAutoplayPolicy(AutoplayPolicyMediaType aType) {
diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp
index c640549a35fb49d1947ab62877b19ed6569d8cc5..52a6fc5f3c564cd2684b54db3e4f24cd545f5cf3 100644
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -10431,6 +10431,7 @@ Result<bool, nsresult> nsContentUtils::SynthesizeMouseEvent(
   EventMessage msg;
   Maybe<WidgetMouseEvent::ExitFrom> exitFrom;
   bool contextMenuKey = false;
+  bool isPWDragEventMessage = false;
   if (aType.EqualsLiteral("mousedown")) {
     msg = eMouseDown;
   } else if (aType.EqualsLiteral("mouseup")) {
@@ -10457,6 +10458,12 @@ Result<bool, nsresult> nsContentUtils::SynthesizeMouseEvent(
     msg = eMouseHitTest;
   } else if (aType.EqualsLiteral("MozMouseExploreByTouch")) {
     msg = eMouseExploreByTouch;
+  } else if (aType.EqualsLiteral("dragover")) {
+    msg = eDragOver;
+    isPWDragEventMessage = true;
+  } else if (aType.EqualsLiteral("drop")) {
+    msg = eDrop;
+    isPWDragEventMessage = true;
   } else {
     return Err(NS_ERROR_FAILURE);
   }
@@ -10468,7 +10475,14 @@ Result<bool, nsresult> nsContentUtils::SynthesizeMouseEvent(
 
   Maybe<WidgetPointerEvent> pointerEvent;
   Maybe<WidgetMouseEvent> mouseEvent;
-  if (IsPointerEventMessage(msg)) {
+  Maybe<WidgetDragEvent> pwDragEvent;
+
+  if (isPWDragEventMessage) {
+    pwDragEvent.emplace(true, msg, aWidget);
+    pwDragEvent->mReason = aOptions.mIsWidgetEventSynthesized
+                             ? WidgetMouseEvent::eSynthesized
+                             : WidgetMouseEvent::eReal;
+  } else if (IsPointerEventMessage(msg)) {
     if (MOZ_UNLIKELY(aOptions.mIsWidgetEventSynthesized)) {
       MOZ_ASSERT_UNREACHABLE(
           "The event shouldn't be dispatched as a synthesized event");
@@ -10496,6 +10510,7 @@ Result<bool, nsresult> nsContentUtils::SynthesizeMouseEvent(
   mozilla::widget::AutoSynthesizedEventCallbackNotifier notifier(callback);
 
   WidgetMouseEvent& mouseOrPointerEvent =
+      pwDragEvent.isSome() ? pwDragEvent.ref() :
       pointerEvent.isSome() ? pointerEvent.ref() : mouseEvent.ref();
   mouseOrPointerEvent.pointerId = aMouseEventData.mIdentifier;
   mouseOrPointerEvent.mModifiers =
diff --git a/dom/base/nsFocusManager.cpp b/dom/base/nsFocusManager.cpp
index 722f715e4593cd7ecc700a482b016c52be789edf..a192b8b55b1fe0af98360798348b6a347d17ff31 100644
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -1885,6 +1885,10 @@ Maybe<uint64_t> nsFocusManager::SetFocusInner(Element* aNewContent,
         (GetActiveBrowsingContext() == newRootBrowsingContext);
   }
 
+  // In Playwright, we want to send focus events even if the element
+  // isn't actually in the active window.
+  isElementInActiveWindow = true;
+
   // Exit fullscreen if a website focuses another window
   if (StaticPrefs::full_screen_api_exit_on_windowRaise() &&
       !isElementInActiveWindow && (aFlags & FLAG_RAISE)) {
@@ -2446,6 +2450,7 @@ bool nsFocusManager::BlurImpl(BrowsingContext* aBrowsingContextToClear,
                               bool aIsLeavingDocument, bool aAdjustWidget,
                               bool aRemainActive, Element* aElementToFocus,
                               uint64_t aActionId) {
+
   LOGFOCUS(("<<Blur begin actionid: %" PRIu64 ">>", aActionId));
 
   // hold a reference to the focused content, which may be null
@@ -2489,6 +2494,11 @@ bool nsFocusManager::BlurImpl(BrowsingContext* aBrowsingContextToClear,
     return true;
   }
 
+  // Playwright: emulate focused page by never bluring when leaving document.
+  if (XRE_IsContentProcess() && aIsLeavingDocument && docShell && nsDocShell::Cast(docShell)->ShouldOverrideHasFocus()) {
+    return true;
+  }
+
   // Keep a ref to presShell since dispatching the DOM event may cause
   // the document to be destroyed.
   RefPtr<PresShell> presShell = docShell->GetPresShell();
@@ -3259,7 +3269,9 @@ void nsFocusManager::RaiseWindow(nsPIDOMWindowOuter* aWindow,
     }
   }
 
-  if (sTestMode) {
+  // In Playwright, we still want to execte the embedder functions
+  // to actually show / focus windows.
+  if (false && sTestMode) {
     // In test mode, emulate raising the window. WindowRaised takes
     // care of lowering the present active window. This happens in
     // a separate runnable to avoid touching multiple windows in
diff --git a/dom/base/nsINode.cpp b/dom/base/nsINode.cpp
index 827fd79930e6409c8619a747573ae72b983a38a8..1394a2586d1d32c33afeced219a590ccf0ebd8a0 100644
--- a/dom/base/nsINode.cpp
+++ b/dom/base/nsINode.cpp
@@ -1982,6 +1982,61 @@ void nsINode::GetBoxQuadsFromWindowOrigin(const BoxQuadOptions& aOptions,
   mozilla::GetBoxQuadsFromWindowOrigin(this, aOptions, aResult, aRv);
 }
 
+static nsIFrame* GetFirstFrame(nsINode* aNode) {
+  if (!aNode->IsContent())
+    return nullptr;
+  nsIFrame* frame = aNode->AsContent()->GetPrimaryFrame(FlushType::Frames);
+  if (!frame) {
+    FlattenedChildIterator iter(aNode->AsContent());
+    for (nsIContent* child = iter.GetNextChild(); child; child = iter.GetNextChild()) {
+      frame = child->GetPrimaryFrame(FlushType::Frames);
+      if (frame) {
+        break;
+      }
+    }
+  }
+  return frame;
+}
+
+void nsINode::ScrollRectIntoViewIfNeeded(int32_t x, int32_t y,
+                                         int32_t w, int32_t h,
+                                         ErrorResult& aRv) {
+  aRv = NS_ERROR_UNEXPECTED;
+  nsCOMPtr<Document> document = OwnerDoc();
+  if (!document) {
+    return aRv.ThrowNotFoundError("Node is detached from document");
+  }
+  PresShell* presShell = document->GetPresShell();
+  if (!presShell) {
+    return aRv.ThrowNotFoundError("Node is detached from document");
+  }
+  nsIFrame* primaryFrame = GetFirstFrame(this);
+  if (!primaryFrame) {
+    return aRv.ThrowNotFoundError("Node does not have a layout object");
+  }
+  aRv = NS_OK;
+  nsRect rect;
+  if (x == -1 && y == -1 && w == -1 && h == -1) {
+    rect = primaryFrame->GetRectRelativeToSelf();
+  } else {
+    rect = nsRect(nsPresContext::CSSPixelsToAppUnits(x),
+                  nsPresContext::CSSPixelsToAppUnits(y),
+                  nsPresContext::CSSPixelsToAppUnits(w),
+                  nsPresContext::CSSPixelsToAppUnits(h));
+  }
+  presShell->ScrollFrameIntoView(
+      primaryFrame, Some(rect),
+      AxisScrollParams(WhereToScroll::Center, WhenToScroll::IfNotFullyVisible),
+      AxisScrollParams(WhereToScroll::Center, WhenToScroll::IfNotFullyVisible),
+      ScrollFlags::ScrollOverflowHidden);
+  // If a _visual_ scroll update is pending, cancel it; otherwise, it will
+  // clobber next scroll (e.g. subsequent window.scrollTo(0, 0) wlll break).
+  if (presShell->GetPendingVisualScrollUpdate()) {
+    presShell->AcknowledgePendingVisualScrollUpdate();
+    presShell->ClearPendingVisualScrollUpdate();
+  }
+}
+
 already_AddRefed<DOMQuad> nsINode::ConvertQuadFromNode(
     DOMQuad& aQuad, const GeometryNode& aFrom,
     const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
diff --git a/dom/base/nsINode.h b/dom/base/nsINode.h
index 0461bbf12daed6a3c55e1eb54c47d08373f6daf4..0f53e62988ef32325dbb7569b89b6d9a0b3eeb72 100644
--- a/dom/base/nsINode.h
+++ b/dom/base/nsINode.h
@@ -3064,6 +3064,10 @@ class nsINode : public mozilla::dom::EventTarget {
                                    nsTArray<RefPtr<DOMQuad>>& aResult,
                                    ErrorResult& aRv);
 
+  void ScrollRectIntoViewIfNeeded(int32_t x, int32_t y,
+                                  int32_t w, int32_t h,
+                                  ErrorResult& aRv);
+
   already_AddRefed<DOMQuad> ConvertQuadFromNode(
       DOMQuad& aQuad, const TextOrElementOrDocument& aFrom,
       const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
diff --git a/dom/chrome-webidl/BrowsingContext.webidl b/dom/chrome-webidl/BrowsingContext.webidl
index 38fd39f0661870235e96ea93729cb95550311591..0a492261db6a9074504a0bffa94350272313dc9f 100644
--- a/dom/chrome-webidl/BrowsingContext.webidl
+++ b/dom/chrome-webidl/BrowsingContext.webidl
@@ -72,6 +72,17 @@ enum PrefersReducedMotionOverride {
   "no-preference",
 };
 
+/**
+ * CSS prefers-contrast values.
+ */
+enum PrefersContrastOverride {
+  "none",
+  "no-preference",
+  "more",
+  "less",
+  "custom",
+};
+
 /**
  * Allowed overrides of platform/pref default behaviour for touch events.
  */
@@ -258,6 +269,9 @@ interface BrowsingContext {
   // Animation playbackRate multiplier, for Devtools
   [SetterThrows] attribute double animationsPlayBackRateMultiplier;
 
+  // Contrast simulation, for DevTools.
+  [SetterThrows] attribute PrefersContrastOverride prefersContrastOverride;
+
   /**
    * A unique identifier for the browser element that is hosting this
    * BrowsingContext tree. Every BrowsingContext in the element's tree will
diff --git a/dom/events/EventStateManager.cpp b/dom/events/EventStateManager.cpp
index 30b2680437397c794abb89e670717a6306b0d6a1..fa22c8ae5d482fcc6459d385a6a6fb2fa6e90282 100644
--- a/dom/events/EventStateManager.cpp
+++ b/dom/events/EventStateManager.cpp
@@ -2135,6 +2135,25 @@ static BrowserParent* GetBrowserParentAncestor(BrowserParent* aBrowserParent) {
   return bbp->Manager();
 }
 
+// Playwright: automation can move the mouse between different top-level
+// windows while expecting the previous window to keep its hover state.
+// Suppress the old remote's synthesized exit for that cross-window handoff.
+// See https://github.com/microsoft/playwright/issues/40562
+static bool PlaywrightSuppressMouseExit(
+    const WidgetMouseEvent* aMouseEvent, BrowserParent* aRemoteTarget,
+    BrowserParent* aOldRemoteTarget) {
+  if (!aMouseEvent->mFlags.mIsSynthesizedForTests || !aRemoteTarget ||
+      !aOldRemoteTarget) {
+    return false;
+  }
+
+  nsCOMPtr<nsIWidget> remoteTopLevelWidget = aRemoteTarget->GetTopLevelWidget();
+  nsCOMPtr<nsIWidget> oldRemoteTopLevelWidget =
+      aOldRemoteTarget->GetTopLevelWidget();
+  return remoteTopLevelWidget && oldRemoteTopLevelWidget &&
+         remoteTopLevelWidget != oldRemoteTopLevelWidget;
+}
+
 static void DispatchCrossProcessMouseExitEvents(WidgetMouseEvent* aMouseEvent,
                                                 BrowserParent* aRemoteTarget,
                                                 BrowserParent* aStopAncestor,
@@ -2258,7 +2277,7 @@ void EventStateManager::DispatchCrossProcessEvent(WidgetEvent* aEvent,
       if (mouseEvent->mReason == WidgetMouseEvent::eReal &&
           remote != oldRemote) {
         MOZ_ASSERT(mouseEvent->mMessage != eMouseExitFromWidget);
-        if (oldRemote) {
+        if (oldRemote && !PlaywrightSuppressMouseExit(mouseEvent, remote, oldRemote)) {
           BrowserParent* commonAncestor =
               nsContentUtils::GetCommonBrowserParentAncestor(remote, oldRemote);
           if (commonAncestor == oldRemote) {
diff --git a/dom/fetch/FetchService.cpp b/dom/fetch/FetchService.cpp
index 4ebdd3e5ffd55cb0b58f1d8ae97e6e08a528c4f8..015317937c020b63ce4f1ee6338f6804464372b1 100644
--- a/dom/fetch/FetchService.cpp
+++ b/dom/fetch/FetchService.cpp
@@ -267,6 +267,14 @@ RefPtr<FetchServicePromises> FetchService::FetchInstance::Fetch() {
       net::ClassificationFlags({0, 0})  // TrackingFlags
   );
 
+  /* --> Playwright: associate keep-alive fetch with the window */
+  if (mArgsType == FetchArgsType::MainThreadFetch) {
+    auto& args = mArgs.as<MainThreadFetchArgs>();
+    mFetchDriver->SetAssociatedBrowsingContextID(
+        args.mAssociatedBrowsingContextID);
+  }
+  /* <-- Playwright */
+
   if (mArgsType == FetchArgsType::WorkerFetch) {
     auto& args = mArgs.as<WorkerFetchArgs>();
     mFetchDriver->SetWorkerScript(args.mWorkerScript);
diff --git a/dom/geolocation/Geolocation.cpp b/dom/geolocation/Geolocation.cpp
index 51efcf97c062e106575b88232a14f1702470fddf..1c68b997e4efd8896ec182e962c9e085ab24e7c7 100644
--- a/dom/geolocation/Geolocation.cpp
+++ b/dom/geolocation/Geolocation.cpp
@@ -103,8 +103,12 @@ class nsGeolocationRequest final : public ContentPermissionRequestBase,
 
   NS_IMETHOD GetIgnoreAllowSitePermission(
       bool* aIgnoreAllowSitePermission) override {
+    RefPtr<GeolocationService> gs =
+        GeolocationService::GetGeolocationService(
+            mLocator->GetBrowsingContext());
     *aIgnoreAllowSitePermission =
-        mBehavior != geolocation::SystemGeolocationPermissionBehavior::NoPrompt;
+        mBehavior != geolocation::SystemGeolocationPermissionBehavior::NoPrompt &&
+        !gs->IsOverride();
     return NS_OK;
   }
 
@@ -393,7 +397,11 @@ nsGeolocationRequest::Allow(JS::Handle<JS::Value> aChoices) {
         self->Cancel();
       };
 
-  if (mBehavior != SystemGeolocationPermissionBehavior::NoPrompt) {
+  RefPtr<GeolocationService> gs =
+      GeolocationService::GetGeolocationService(
+          mLocator->GetBrowsingContext());
+  if (mBehavior != SystemGeolocationPermissionBehavior::NoPrompt &&
+      !gs->IsOverride()) {
     // Asynchronously present the system dialog or open system preferences
     // (RequestGeolocationPermissionFromUser will know which to do), and wait
     // for the permission to change or the request to be canceled.  If the
@@ -417,8 +425,6 @@ nsGeolocationRequest::Allow(JS::Handle<JS::Value> aChoices) {
     return NS_OK;
   }
 
-  RefPtr<GeolocationService> gs =
-      GeolocationService::GetGeolocationService(mLocator->GetBrowsingContext());
   bool canUseCache = false;
   CachedPositionAndAccuracy lastPosition = gs->GetCachedPosition();
   if (lastPosition.position) {
diff --git a/dom/media/systemservices/video_engine/desktop_capture_impl.cc b/dom/media/systemservices/video_engine/desktop_capture_impl.cc
index 9e1086527c293e95f92bd60b7f39de5e955a36ed..7b3b482cf10e87eb8e9f2423aef7b6ac7f8696bc 100644
--- a/dom/media/systemservices/video_engine/desktop_capture_impl.cc
+++ b/dom/media/systemservices/video_engine/desktop_capture_impl.cc
@@ -52,9 +52,10 @@ namespace webrtc {
 
 DesktopCaptureImpl* DesktopCaptureImpl::Create(int32_t aCaptureId,
                                                const char* aUniqueId,
-                                               const CaptureDeviceType aType) {
+                                               const CaptureDeviceType aType,
+                                               bool aCaptureCursor) {
   return new webrtc::RefCountedObject<DesktopCaptureImpl>(aCaptureId, aUniqueId,
-                                                          aType);
+                                                          aType, aCaptureCursor);
 }
 
 static DesktopCaptureOptions CreateDesktopCaptureOptions() {
@@ -154,8 +155,10 @@ static std::unique_ptr<DesktopCapturer> CreateTabCapturer(
 
 static std::unique_ptr<DesktopCapturer> CreateDesktopCapturerAndThread(
     CaptureDeviceType aDeviceType, DesktopCapturer::SourceId aSourceId,
-    nsIThread** aOutThread) {
+    nsIThread** aOutThread, bool aCaptureCursor) {
   DesktopCaptureOptions options = CreateDesktopCaptureOptions();
+  if (aCaptureCursor)
+    options.set_prefer_cursor_embedded(aCaptureCursor);
   auto ensureThread = [&]() {
     if (*aOutThread) {
       return *aOutThread;
@@ -253,7 +256,8 @@ static std::unique_ptr<DesktopCapturer> CreateDesktopCapturerAndThread(
 
 DesktopCaptureImpl::DesktopCaptureImpl(int32_t aCaptureId,
                                        const char* aUniqueId,
-                                       const CaptureDeviceType aType)
+                                       const CaptureDeviceType aType,
+                                       bool aCaptureCursor)
     : mTrackingId(mozilla::TrackingId(CaptureEngineToTrackingSourceStr([&] {
                                         switch (aType) {
                                           case CaptureDeviceType::Screen:
@@ -269,9 +273,13 @@ DesktopCaptureImpl::DesktopCaptureImpl(int32_t aCaptureId,
                                       aCaptureId)),
       mDeviceUniqueId(aUniqueId),
       mDeviceType(aType),
+      capture_cursor_(aCaptureCursor),
       mControlThread(mozilla::GetCurrentSerialEventTarget()),
       mNextFrameMinimumTime(Timestamp::Zero()),
-      mCallback("DesktopCaptureImpl::mCallback"),
+      // Playwright: make sure mCallback is initialized with nullptr instead of
+      // a random garbage; we'll use this to assert existance of data callback.
+      mCallback(static_cast<webrtc::VideoSinkInterface<VideoFrame>*>(nullptr),
+          "DesktopCaptureImpl::mCallback"),
       mBufferPool(false, 2) {}
 
 DesktopCaptureImpl::~DesktopCaptureImpl() {
@@ -290,6 +298,19 @@ void DesktopCaptureImpl::DeRegisterCaptureDataCallback() {
   *callback = nullptr;
 }
 
+void DesktopCaptureImpl::RegisterRawFrameCallback(RawFrameCallback* rawFrameCallback) {
+  webrtc::CritScope lock(&mApiCs);
+  _rawFrameCallbacks.insert(rawFrameCallback);
+}
+
+void DesktopCaptureImpl::DeRegisterRawFrameCallback(RawFrameCallback* rawFrameCallback) {
+  webrtc::CritScope lock(&mApiCs);
+  auto it = _rawFrameCallbacks.find(rawFrameCallback);
+  if (it != _rawFrameCallbacks.end()) {
+    _rawFrameCallbacks.erase(it);
+  }
+}
+
 int32_t DesktopCaptureImpl::SetCaptureRotation(VideoRotation aRotation) {
   MOZ_ASSERT_UNREACHABLE("Unused");
   return -1;
@@ -335,7 +356,7 @@ int32_t DesktopCaptureImpl::StartCapture(
     return -1;
   }
   std::unique_ptr capturer = CreateDesktopCapturerAndThread(
-      mDeviceType, sourceId, getter_AddRefs(mCaptureThread));
+      mDeviceType, sourceId, getter_AddRefs(mCaptureThread), capture_cursor_);
 
   MOZ_ASSERT(!capturer == !mCaptureThread);
   if (!capturer) {
@@ -445,6 +466,21 @@ void DesktopCaptureImpl::OnCaptureResult(DesktopCapturer::Result aResult,
   frameInfo.height = aFrame->size().height();
   frameInfo.videoType = VideoType::kARGB;
 
+  {
+    webrtc::CritScope cs(&mApiCs);
+    for (auto rawFrameCallback : _rawFrameCallbacks) {
+      rawFrameCallback->OnRawFrame(videoFrame, aFrame->stride(), frameInfo);
+    }
+  }
+
+  // Playwright: fast-return if only raw callback is registered.
+  {
+    auto callback = mCallback.Lock();
+    if (!*callback) {
+      return;
+    }
+  }
+
   size_t videoFrameLength =
       frameInfo.width * frameInfo.height * DesktopFrame::kBytesPerPixel;
 
diff --git a/dom/media/systemservices/video_engine/desktop_capture_impl.h b/dom/media/systemservices/video_engine/desktop_capture_impl.h
index 7f3e2e0360b5fb16265f5581faf3a5ee30f7b94a..7a01c0c3f474feb75d683a482ff08deed7edc98f 100644
--- a/dom/media/systemservices/video_engine/desktop_capture_impl.h
+++ b/dom/media/systemservices/video_engine/desktop_capture_impl.h
@@ -26,6 +26,7 @@
 #include "common_video/include/video_frame_buffer_pool.h"
 #include "modules/desktop_capture/desktop_capturer.h"
 #include "modules/video_capture/video_capture.h"
+#include "rtc_base/deprecated/recursive_critical_section.h"
 #include "mozilla/DataMutex.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/TimeStamp.h"
@@ -43,18 +44,45 @@ namespace webrtc {
 
 class VideoCaptureEncodeInterface;
 
+class RawFrameCallback {
+ public:
+  virtual ~RawFrameCallback() {}
+
+  virtual void OnRawFrame(uint8_t* videoFrame, size_t videoFrameLength, const VideoCaptureCapability& frameInfo) = 0;
+};
+
+class VideoCaptureModuleEx : public VideoCaptureModule {
+ public:
+  virtual ~VideoCaptureModuleEx() {}
+
+  virtual void RegisterRawFrameCallback(RawFrameCallback* rawFrameCallback) = 0;
+  virtual void DeRegisterRawFrameCallback(RawFrameCallback* rawFrameCallback) = 0;
+  int32_t StartCaptureCounted(const VideoCaptureCapability& aCapability) {
+    ++capture_counter_;
+    return capture_counter_ == 1 ? StartCapture(aCapability) : 0;
+  }
+
+  int32_t StopCaptureCounted() {
+    --capture_counter_;
+    return capture_counter_ == 0 ? StopCapture() : 0;
+  }
+
+ private:
+  int32_t capture_counter_ = 0;
+};
+
 // Reuses the video engine pipeline for screen sharing.
 // As with video, DesktopCaptureImpl is a proxy for screen sharing
 // and follows the video pipeline design
 class DesktopCaptureImpl : public mozilla::DesktopCaptureInterface,
                            public DesktopCapturer::Callback,
-                           public VideoCaptureModule {
+                           public VideoCaptureModuleEx {
  public:
   /* Create a screen capture modules object
    */
   static DesktopCaptureImpl* Create(
       int32_t aCaptureId, const char* aUniqueId,
-      const mozilla::camera::CaptureDeviceType aType);
+      const mozilla::camera::CaptureDeviceType aType, bool aCaptureCursor = true);
 
   [[nodiscard]] static std::shared_ptr<VideoCaptureModule::DeviceInfo>
   CreateDeviceInfo(const mozilla::camera::CaptureDeviceType aType);
@@ -65,6 +93,8 @@ class DesktopCaptureImpl : public mozilla::DesktopCaptureInterface,
   void RegisterCaptureDataCallback(
       RawVideoSinkInterface* dataCallback) override {}
   void DeRegisterCaptureDataCallback() override;
+  void RegisterRawFrameCallback(RawFrameCallback* rawFrameCallback) override;
+  void DeRegisterRawFrameCallback(RawFrameCallback* rawFrameCallback) override;
 
   int32_t SetCaptureRotation(VideoRotation aRotation) override;
   bool SetApplyRotation(bool aEnable) override;
@@ -87,7 +117,8 @@ class DesktopCaptureImpl : public mozilla::DesktopCaptureInterface,
 
  protected:
   DesktopCaptureImpl(const int32_t aCaptureId, const char* aUniqueId,
-                     const mozilla::camera::CaptureDeviceType aType);
+                     const mozilla::camera::CaptureDeviceType aType,
+                     bool aCaptureCusor);
   virtual ~DesktopCaptureImpl();
 
  private:
@@ -96,6 +127,9 @@ class DesktopCaptureImpl : public mozilla::DesktopCaptureInterface,
   void InitOnThread(std::unique_ptr<DesktopCapturer> aCapturer, int aFramerate);
   void UpdateOnThread(int aFramerate);
   void ShutdownOnThread();
+
+  webrtc::RecursiveCriticalSection mApiCs;
+  std::set<RawFrameCallback*> _rawFrameCallbacks;
   // DesktopCapturer::Callback interface.
   void OnCaptureResult(DesktopCapturer::Result aResult,
                        std::unique_ptr<DesktopFrame> aFrame) override;
@@ -103,6 +137,8 @@ class DesktopCaptureImpl : public mozilla::DesktopCaptureInterface,
   // Notifies all mCallbacks of OnFrame(). mCaptureThread only.
   void NotifyOnFrame(const VideoFrame& aFrame);
 
+  bool capture_cursor_ = true;
+
   // Control thread on which the public API is called.
   const nsCOMPtr<nsISerialEventTarget> mControlThread;
   // Set in StartCapture.
diff --git a/dom/script/ScriptSettings.cpp b/dom/script/ScriptSettings.cpp
index d1cf4b188f3f344a2c96718cfe385e80e6501a6a..dba6adb997b8919e5d8b464818cd832d01de0c54 100644
--- a/dom/script/ScriptSettings.cpp
+++ b/dom/script/ScriptSettings.cpp
@@ -146,6 +146,30 @@ ScriptSettingsStackEntry::~ScriptSettingsStackEntry() {
   MOZ_ASSERT_IF(mGlobalObject, mGlobalObject->HasJSGlobal());
 }
 
+static nsIGlobalObject* UnwrapSandboxGlobal(nsIGlobalObject* global) {
+  if (!global)
+    return global;
+  JSObject* globalObject = global->GetGlobalJSObject();
+  if (!globalObject)
+    return global;
+  JSContext* cx = nsContentUtils::GetCurrentJSContext();
+  if (!cx)
+    return global;
+  JS::Rooted<JSObject*> proto(cx);
+  JS::RootedObject rootedGlobal(cx, globalObject);
+  if (!JS_GetPrototype(cx, rootedGlobal, &proto))
+    return global;
+  if (!proto || !xpc::IsSandboxPrototypeProxy(proto))
+    return global;
+  // If this is a sandbox associated with a DOMWindow via a
+  // sandboxPrototype, use that DOMWindow. This supports GreaseMonkey
+  // and JetPack content scripts.
+  proto = js::CheckedUnwrapDynamic(proto, cx, /* stopAtWindowProxy = */ false);
+  if (!proto)
+    return global;
+  return xpc::WindowGlobalOrNull(proto);
+}
+
 // If the entry or incumbent global ends up being something that the subject
 // principal doesn't subsume, we don't want to use it. This never happens on
 // the web, but can happen with asymmetric privilege relationships (i.e.
@@ -173,7 +197,7 @@ static nsIGlobalObject* ClampToSubject(nsIGlobalObject* aGlobalOrNull) {
   NS_ENSURE_TRUE(globalPrin, GetCurrentGlobal());
   if (!nsContentUtils::SubjectPrincipalOrSystemIfNativeCaller()
            ->SubsumesConsideringDomain(globalPrin)) {
-    return GetCurrentGlobal();
+    return UnwrapSandboxGlobal(GetCurrentGlobal());
   }
 
   return aGlobalOrNull;
diff --git a/dom/security/nsCSPUtils.cpp b/dom/security/nsCSPUtils.cpp
index 11de03cf6eaf8fa6fff602cc12a78acc08f2e25f..51e5abd2ee8174d672ce70310b9d03fdda170a26 100644
--- a/dom/security/nsCSPUtils.cpp
+++ b/dom/security/nsCSPUtils.cpp
@@ -31,6 +31,7 @@
 #include "nsSandboxFlags.h"
 #include "nsServiceManagerUtils.h"
 #include "nsWhitespaceTokenizer.h"
+#include "nsDocShell.h"
 
 using namespace mozilla;
 using mozilla::dom::SRIMetadata;
@@ -134,6 +135,11 @@ void CSP_ApplyMetaCSPToDoc(mozilla::dom::Document& aDoc,
     return;
   }
 
+  if (aDoc.GetDocShell() &&
+      nsDocShell::Cast(aDoc.GetDocShell())->IsBypassCSPEnabled()) {
+    return;
+  }
+
   nsAutoString policyStr(
       nsContentUtils::TrimWhitespace<nsContentUtils::IsHTMLWhitespace>(
           aPolicyStr));
diff --git a/dom/webidl/GeometryUtils.webidl b/dom/webidl/GeometryUtils.webidl
index 584d39da5f04f6d8fc6a87547557b0eeeb35d168..65eb7014356a90aa01ab517c9937ed650c2ee8fd 100644
--- a/dom/webidl/GeometryUtils.webidl
+++ b/dom/webidl/GeometryUtils.webidl
@@ -16,6 +16,8 @@ dictionary GeometryUtilsOptions {
   boolean createFramesForSuppressedWhitespace = true;
   [ChromeOnly]
   boolean flush = true;
+  [ChromeOnly]
+  boolean recurseWhenNoFrame = false;
 };
 
 dictionary BoxQuadOptions : GeometryUtilsOptions {
@@ -34,6 +36,9 @@ interface mixin GeometryUtils {
   [Throws, Func="nsINode::HasBoxQuadsSupport", NeedsCallerType]
   sequence<DOMQuad> getBoxQuads(optional BoxQuadOptions options = {});
 
+  [ChromeOnly, Throws, Func="nsINode::HasBoxQuadsSupport"]
+  undefined scrollRectIntoViewIfNeeded(long x, long y, long w, long h);
+
   /* getBoxQuadsFromWindowOrigin is similar to getBoxQuads, but the
    * returned quads are further translated relative to the window
    * origin -- which is not the layout origin. Further translation
diff --git a/dom/workers/ScriptLoader.cpp b/dom/workers/ScriptLoader.cpp
index 62feea3137dd9fe55d31045fdda68f3d672e2366..09b2486cfc4c5b220e2a01cd8f7428fe7e3c9e60 100644
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -1169,6 +1169,14 @@ bool WorkerScriptLoader::EvaluateScript(JSContext* aCx,
   mWorkerRef->Private()->AssertIsOnWorkerThread();
   MOZ_ASSERT(!IsDynamicImport(aRequest));
 
+  // ----- Playwright begin -----
+  ++mEvaluatingScriptCount;
+  auto decrementEvaluatingCount = MakeScopeExit([&] {
+    MOZ_ASSERT(mEvaluatingScriptCount > 0);
+    --mEvaluatingScriptCount;
+  });
+  // ----- Playwright end -------
+
   WorkerLoadContext* loadContext = aRequest->GetWorkerLoadContext();
 
   NS_ASSERTION(!loadContext->mChannel, "Should no longer have a channel!");
diff --git a/dom/workers/ScriptLoader.h b/dom/workers/ScriptLoader.h
index 6ea3f0a9ed4f1e31a36e9657010b694177bd79d3..496b805f198f266751f0cc9fc64035ba81be11cc 100644
--- a/dom/workers/ScriptLoader.h
+++ b/dom/workers/ScriptLoader.h
@@ -157,6 +157,10 @@ class WorkerScriptLoader : public JS::loader::ScriptLoaderInterface,
   bool mExecutionAborted = false;
   bool mMutedErrorFlag = false;
 
+  // ----- Playwright begin -----
+  uint32_t mEvaluatingScriptCount = 0;
+  // ----- Playwright end -------
+
   // Count of loading module requests. mLoadingRequests doesn't keep track of
   // child module requests.
   // This member should be accessed on worker thread.
@@ -228,7 +232,9 @@ class WorkerScriptLoader : public JS::loader::ScriptLoaderInterface,
   bool ProcessPendingRequests(JSContext* aCx);
 
   bool AllScriptsExecuted() {
-    return mLoadingRequests.isEmpty() && mLoadedRequests.isEmpty();
+    // https://github.com/microsoft/playwright/issues/42565
+    return mEvaluatingScriptCount == 0 && mLoadingRequests.isEmpty() &&
+           mLoadedRequests.isEmpty();
   }
 
   bool IsDebuggerScript() const { return mWorkerScriptType == DebuggerScript; }
diff --git a/layout/base/GeometryUtils.cpp b/layout/base/GeometryUtils.cpp
index eaaf69687f669a4859a37f3f97b99e6ca519c420..6f965a110db3a1c86466d72f09ead23bef767e5e 100644
--- a/layout/base/GeometryUtils.cpp
+++ b/layout/base/GeometryUtils.cpp
@@ -21,6 +21,7 @@
 #include "nsContentUtils.h"
 #include "nsIFrame.h"
 #include "nsLayoutUtils.h"
+#include "ChildIterator.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
@@ -263,10 +264,27 @@ static bool CheckFramesInSameTopLevelBrowsingContext(nsIFrame* aFrame1,
   return false;
 }
 
+static nsIFrame* GetFrameForNodeRecursive(nsINode* aNode,
+                                 const GeometryUtilsOptions& aOptions,
+                                 bool aRecurseWhenNoFrame) {
+  nsIFrame* frame = GetFrameForNode(aNode, aOptions);
+  if (!frame && aRecurseWhenNoFrame && aNode->IsContent()) {
+    dom::FlattenedChildIterator iter(aNode->AsContent());
+    for (nsIContent* child = iter.GetNextChild(); child; child = iter.GetNextChild()) {
+      frame = GetFrameForNodeRecursive(child, aOptions, aRecurseWhenNoFrame);
+      if (frame) {
+        break;
+      }
+    }
+  }
+  return frame;
+}
+
 void GetBoxQuads(nsINode* aNode, const dom::BoxQuadOptions& aOptions,
                  nsTArray<RefPtr<DOMQuad>>& aResult, CallerType aCallerType,
                  ErrorResult& aRv) {
-  nsIFrame* frame = GetFrameForNode(aNode, aOptions);
+  nsIFrame* frame =
+      GetFrameForNodeRecursive(aNode, aOptions, aOptions.mRecurseWhenNoFrame);
   if (!frame) {
     // No boxes to return
     return;
@@ -280,7 +298,8 @@ void GetBoxQuads(nsINode* aNode, const dom::BoxQuadOptions& aOptions,
   // EnsureFrameForTextNode call. We need to get the first frame again
   // when that happens and re-check it.
   if (!weakFrame.IsAlive()) {
-    frame = GetFrameForNode(aNode, aOptions);
+    frame =
+        GetFrameForNodeRecursive(aNode, aOptions, aOptions.mRecurseWhenNoFrame);
     if (!frame) {
       // No boxes to return
       return;
diff --git a/layout/base/PresShell.cpp b/layout/base/PresShell.cpp
index c88f6f63f05043dd4f22761f446b5843ac0a5b40..284a49113d808e7352d22e301e99d6c00b2a5adc 100644
--- a/layout/base/PresShell.cpp
+++ b/layout/base/PresShell.cpp
@@ -12022,7 +12022,9 @@ bool PresShell::ComputeActiveness() const {
     if (!browserChild->IsVisible()) {
       MOZ_LOG(gLog, LogLevel::Debug,
               (" > BrowserChild %p is not visible", browserChild));
-      return false;
+      bool isActive;
+      root->GetDocShell()->GetForceActiveState(&isActive);
+      return isActive;
     }
 
     // If the browser is visible but just due to be preserving layers
diff --git a/layout/style/nsMediaFeatures.cpp b/layout/style/nsMediaFeatures.cpp
index 1f9613b8cd936fa9d884be010a8dd6167251faa6..0346bccc1c469446376c5bee3250e3dcfd9b6d81 100644
--- a/layout/style/nsMediaFeatures.cpp
+++ b/layout/style/nsMediaFeatures.cpp
@@ -322,6 +322,20 @@ bool Gecko_MediaFeatures_MacRTL(const Document* aDocument) {
 // as a signal.
 StylePrefersContrast Gecko_MediaFeatures_PrefersContrast(
     const Document* aDocument) {
+  if (auto* bc = aDocument->GetBrowsingContext()) {
+    switch (bc->Top()->PrefersContrastOverride()) {
+      case dom::PrefersContrastOverride::No_preference:
+        return StylePrefersContrast::NoPreference;
+      case dom::PrefersContrastOverride::Less:
+        return StylePrefersContrast::Less;
+      case dom::PrefersContrastOverride::More:
+        return StylePrefersContrast::More;
+      case dom::PrefersContrastOverride::Custom:
+        return StylePrefersContrast::Custom;
+    }
+  }
+
+
   if (aDocument->ShouldResistFingerprinting(RFPTarget::CSSPrefersContrast)) {
     return StylePrefersContrast::NoPreference;
   }
diff --git a/modules/libpref/init/StaticPrefList.yaml b/modules/libpref/init/StaticPrefList.yaml
index 964f67c02018235a45804508807728578b599065..3d886dd62bdcac70a1d1857b7d98d676da872dbe 100644
--- a/modules/libpref/init/StaticPrefList.yaml
+++ b/modules/libpref/init/StaticPrefList.yaml
@@ -13704,18 +13704,20 @@
 # Use the libwebrtc ScreenCaptureKit desktop capture backend on Mac by default.
 # When disabled, or on a host where not supported (< macOS 14), the older
 # CoreGraphics backend is used instead.
+# PLAYWRIGHT: disable this preference to avoid this kicking during screencast.
 -   name: media.getdisplaymedia.screencapturekit.enabled
     type: bool
-    value: true
+    value: false
     mirror: once
 
 # Use SCContentSharingPicker for source picking when the libwebrtc
 # ScreenCaptureKit desktop capture backend is used. When this is true and the
 # backend supports SCContentSharingPicker, this takes precendence over the
 # enumeration pref below.
+# PLAYWRIGHT: disable this preference to avoid this kicking during screencast.
 -   name: media.getdisplaymedia.screencapturekit.picker.enabled
     type: bool
-    value: true
+    value: false
     mirror: once
 
 # Use the libwebrtc ScreenCaptureKit desktop capture backend on Mac for screen
diff --git a/netwerk/base/LoadInfo.cpp b/netwerk/base/LoadInfo.cpp
index 9d64a00363fcfcdd6f2d99c40b085b0651f7b0b7..1ff2a1f606fc9e883f1d2395d4bf4ac2a5bc39bb 100644
--- a/netwerk/base/LoadInfo.cpp
+++ b/netwerk/base/LoadInfo.cpp
@@ -759,7 +759,8 @@ LoadInfo::LoadInfo(const LoadInfo& rhs)
       mInterceptionInfo(rhs.mInterceptionInfo),
       mSchemelessInput(rhs.mSchemelessInput),
       mUserNavigationInvolvement(rhs.mUserNavigationInvolvement),
-      mSkipHTTPSUpgrade(rhs.mSkipHTTPSUpgrade) {
+      mSkipHTTPSUpgrade(rhs.mSkipHTTPSUpgrade),
+      mJugglerLoadIdentifier(rhs.mJugglerLoadIdentifier) {
 }
 
 LoadInfo::LoadInfo(
@@ -2141,4 +2142,16 @@ void LoadInfo::UpdateParentAddressSpaceInfo() {
   }
 }
 
+NS_IMETHODIMP
+LoadInfo::GetJugglerLoadIdentifier(uint64_t* aResult) {
+  *aResult = mJugglerLoadIdentifier;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+LoadInfo::SetJugglerLoadIdentifier(uint64_t aID) {
+  mJugglerLoadIdentifier = aID;
+  return NS_OK;
+}
+
 }  // namespace mozilla::net
diff --git a/netwerk/base/LoadInfo.h b/netwerk/base/LoadInfo.h
index a6a44ac715a637ddf1cc5c23ff0dd8440dd45eaf..1fbbf4dd7341f56fcecadf8a6c04de7b5a12f1e5 100644
--- a/netwerk/base/LoadInfo.h
+++ b/netwerk/base/LoadInfo.h
@@ -519,6 +519,8 @@ class LoadInfo final : public nsILoadInfo {
       dom::UserNavigationInvolvement::None;
 
   bool mSkipHTTPSUpgrade = false;
+
+  uint64_t mJugglerLoadIdentifier = 0;
 };
 // This is exposed solely for testing purposes and should not be used outside of
 // LoadInfo
diff --git a/netwerk/base/TRRLoadInfo.cpp b/netwerk/base/TRRLoadInfo.cpp
index 0cba54550072adc8a0ad11b1c9a502ff97a7bd7e..d4d68b981a4f9e7e448f56f60983a0a6e0db9de1 100644
--- a/netwerk/base/TRRLoadInfo.cpp
+++ b/netwerk/base/TRRLoadInfo.cpp
@@ -571,5 +571,15 @@ TRRLoadInfo::GetFetchDestination(nsACString& aDestination) {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
+NS_IMETHODIMP
+TRRLoadInfo::GetJugglerLoadIdentifier(uint64_t* aResult) {
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+TRRLoadInfo::SetJugglerLoadIdentifier(uint64_t aResult) {
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
 }  // namespace net
 }  // namespace mozilla
diff --git a/netwerk/base/nsILoadInfo.idl b/netwerk/base/nsILoadInfo.idl
index a3e7384515b976681d9e12318cbc1156415a9a50..86327e3e8581acc004f53d5eecb5a45afccf97d2 100644
--- a/netwerk/base/nsILoadInfo.idl
+++ b/netwerk/base/nsILoadInfo.idl
@@ -1748,4 +1748,6 @@ interface nsILoadInfo : nsISupports
       return static_cast<mozilla::dom::UserNavigationInvolvement>(userNavigationInvolvement);
     }
 %}
+
+  [infallible] attribute unsigned long long jugglerLoadIdentifier;
 };
diff --git a/netwerk/base/nsINetworkInterceptController.idl b/netwerk/base/nsINetworkInterceptController.idl
index 3654f3ed20f6b22d36c4238be40417e77e8f6867..f685e7668ad3310cac8bc8425124a6fe6ed0405d 100644
--- a/netwerk/base/nsINetworkInterceptController.idl
+++ b/netwerk/base/nsINetworkInterceptController.idl
@@ -59,6 +59,16 @@ interface nsIInterceptedChannel : nsISupports
      */
     void resetInterception(in boolean bypass);
 
+    // ----- Playwright begin -----
+
+    // Same as resetInterception, but updates the URI.
+    void resetInterceptionWithURI(in nsIURI aURI);
+
+    // After resetInterception is called, this request will be intercepted again.
+    void interceptAfterServiceWorkerResets();
+
+    // ----- Playwright end -------
+
     /**
      * Set the status and reason for the forthcoming synthesized response.
      * Multiple calls overwrite existing values.
diff --git a/netwerk/ipc/DocumentLoadListener.cpp b/netwerk/ipc/DocumentLoadListener.cpp
index 2a62fcd56dc97757c8e7d11cc5a5560899510e67..b36c8357e73f5e196ef9986fd93ddef11a7b1e0e 100644
--- a/netwerk/ipc/DocumentLoadListener.cpp
+++ b/netwerk/ipc/DocumentLoadListener.cpp
@@ -205,6 +205,7 @@ static auto CreateDocumentLoadInfo(CanonicalBrowsingContext* aBrowsingContext,
       aLoadState->GetTextDirectiveUserActivation() ||
       aLoadState->HasLoadFlags(nsIWebNavigation::LOAD_FLAGS_FROM_EXTERNAL));
   loadInfo->SetIsMetaRefresh(aLoadState->IsMetaRefresh());
+  loadInfo->SetJugglerLoadIdentifier(aLoadState->GetLoadIdentifier());
 
   return loadInfo.forget();
 }
diff --git a/netwerk/protocol/http/InterceptedHttpChannel.cpp b/netwerk/protocol/http/InterceptedHttpChannel.cpp
index d8c47fb9a4dc7cd529895e64d9b2137cacaedc75..90b268fc65331520932ce17e9e9a58e8d3696e5f 100644
--- a/netwerk/protocol/http/InterceptedHttpChannel.cpp
+++ b/netwerk/protocol/http/InterceptedHttpChannel.cpp
@@ -729,10 +729,33 @@ NS_IMPL_ISUPPORTS(ResetInterceptionHeaderVisitor, nsIHttpHeaderVisitor)
 
 }  // anonymous namespace
 
+NS_IMETHODIMP
+InterceptedHttpChannel::InterceptAfterServiceWorkerResets() {
+  mInterceptAfterServiceWorkerResets = true;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+InterceptedHttpChannel::ResetInterceptionWithURI(nsIURI* aURI) {
+  if (aURI) {
+    mURI = aURI;
+  }
+  return ResetInterception(true);
+}
+
 NS_IMETHODIMP
 InterceptedHttpChannel::ResetInterception(bool aBypass) {
   INTERCEPTED_LOG(("InterceptedHttpChannel::ResetInterception [%p] bypass: %s",
                    this, aBypass ? "true" : "false"));
+  if (mInterceptAfterServiceWorkerResets) {
+    mInterceptAfterServiceWorkerResets = false;
+    nsCOMPtr<nsINetworkInterceptController> controller;
+    GetCallback(controller);
+    if (!controller)
+      return NS_ERROR_DOM_INVALID_STATE_ERR;
+    return controller->ChannelIntercepted(this);
+  }
+
   if (mCanceled) {
     return mStatus;
   }
@@ -1151,11 +1174,18 @@ InterceptedHttpChannel::OnStartRequest(nsIRequest* aRequest) {
     GetCallback(mProgressSink);
   }
 
+  // Playwright: main requests in firefox do not have loading principal.
+  // As they are intercepted by Playwright, they don't have
+  // serviceWorkerTainting as well.
+  // Thus these asserts are wrong for Playwright world.
+  // Note: these checks were added in https://github.com/mozilla-firefox/firefox/commit/bb16ca6496682c3b0ddd452d0dd4c1dd46ff71f8
+  /*
   MOZ_ASSERT_IF(!mLoadInfo->GetServiceWorkerTaintingSynthesized(),
                 mLoadInfo->GetLoadingPrincipal());
   // No need to do ORB checks if these conditions hold.
   MOZ_DIAGNOSTIC_ASSERT(mLoadInfo->GetServiceWorkerTaintingSynthesized() ||
                         mLoadInfo->GetLoadingPrincipal()->IsSystemPrincipal());
+  */
 
   if (mPump && mLoadFlags & LOAD_CALL_CONTENT_SNIFFERS) {
     RefPtr<nsInputStreamPump> pump(mPump);
diff --git a/netwerk/protocol/http/InterceptedHttpChannel.h b/netwerk/protocol/http/InterceptedHttpChannel.h
index ab440756a6745ce3c4785f211db32173c6bd27c5..2ba8db70059b5143e72063ffb588c55dd2734c62 100644
--- a/netwerk/protocol/http/InterceptedHttpChannel.h
+++ b/netwerk/protocol/http/InterceptedHttpChannel.h
@@ -89,6 +89,11 @@ class InterceptedHttpChannel final
   Atomic<bool> mCallingStatusAndProgress;
   bool mInterceptionReset{false};
 
+  // ----- Playwright begin -----
+  // After resetInterception is called, this request will call into interceptors again.
+  bool mInterceptAfterServiceWorkerResets{false};
+  // ----- Playwright end -------
+
   /**
    *  InterceptionTimeStamps is used to record the time stamps of the
    *  interception.
diff --git a/netwerk/protocol/http/nsHttpChannel.cpp b/netwerk/protocol/http/nsHttpChannel.cpp
index 63df4c9dfa2acf744306c3de2d2923d3361d03f9..dd72781ce0f728d4724b7be6b35e06989622e3af 100644
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -949,11 +949,9 @@ nsresult nsHttpChannel::OnBeforeConnect() {
   // SecurityInfo.sys.mjs
   mLoadInfo->SetHstsStatus(isSecureURI);
 
-  RefPtr<mozilla::dom::BrowsingContext> bc;
-  mLoadInfo->GetBrowsingContext(getter_AddRefs(bc));
   // If bypassing the cache and we're forced offline
   // we can just return the error here.
-  if (bc && bc->Top()->GetForceOffline() &&
+  if (IsForcedOffline() &&
       BYPASS_LOCAL_CACHE(mLoadFlags, LoadPreferCacheLoadOverBypass())) {
     return NS_ERROR_OFFLINE;
   }
@@ -1073,9 +1071,7 @@ nsresult nsHttpChannel::MaybeUseHTTPSRRForUpgrade(bool aShouldUpgrade,
     return aStatus;
   }
 
-  RefPtr<mozilla::dom::BrowsingContext> bc;
-  mLoadInfo->GetBrowsingContext(getter_AddRefs(bc));
-  bool forceOffline = bc && bc->Top()->GetForceOffline();
+  bool forceOffline = IsForcedOffline();
 
   if (mURI->SchemeIs("https") || aShouldUpgrade || !LoadUseHTTPSSVC() ||
       forceOffline) {
@@ -1550,15 +1546,14 @@ nsresult nsHttpChannel::ContinueConnect() {
                      "CORS preflight must have been finished by the time we "
                      "do the rest of ContinueConnect");
 
-  RefPtr<mozilla::dom::BrowsingContext> bc;
-  mLoadInfo->GetBrowsingContext(getter_AddRefs(bc));
+  bool isForcedOffline = IsForcedOffline();
 
   // we may or may not have a cache entry at this point
   if (mCacheEntry) {
     // read straight from the cache if possible...
     if (CachedContentIsValid()) {
       // If we're forced offline, and set to bypass the cache, return offline.
-      if (bc && bc->Top()->GetForceOffline() &&
+      if (isForcedOffline &&
           BYPASS_LOCAL_CACHE(mLoadFlags, LoadPreferCacheLoadOverBypass())) {
         return NS_ERROR_OFFLINE;
       }
@@ -1600,7 +1595,7 @@ nsresult nsHttpChannel::ContinueConnect() {
   }
 
   // We're about to hit the network. Don't if we're forced offline.
-  if (bc && bc->Top()->GetForceOffline()) {
+  if (isForcedOffline) {
     return NS_ERROR_OFFLINE;
   }
 
@@ -1708,12 +1703,9 @@ void nsHttpChannel::SpeculativeConnect() {
   // don't speculate if we are offline, when doing http upgrade (i.e.
   // websockets bootstrap), or if we can't do keep-alive (because then we
   // couldn't reuse the speculative connection anyhow).
-  RefPtr<mozilla::dom::BrowsingContext> bc;
-  mLoadInfo->GetBrowsingContext(getter_AddRefs(bc));
-
   if (gIOService->IsOffline() || mUpgradeProtocolCallback ||
       !(mCaps & NS_HTTP_ALLOW_KEEPALIVE) ||
-      (bc && bc->Top()->GetForceOffline())) {
+      IsForcedOffline()) {
     return;
   }
 
@@ -5066,7 +5058,7 @@ nsresult nsHttpChannel::OpenCacheEntryInternal(bool isHttps) {
     return NS_OK;
   }
 
-  bool forceOffline = bc && bc->Top()->GetForceOffline();
+  bool forceOffline = IsForcedOffline();
   if (offline || (mLoadFlags & INHIBIT_CACHING) || forceOffline) {
     if (BYPASS_LOCAL_CACHE(mLoadFlags, LoadPreferCacheLoadOverBypass()) &&
         !offline && !forceOffline) {
@@ -8558,6 +8550,20 @@ void nsHttpChannel::MaybeStartDNSPrefetch() {
   }
 }
 
+bool nsHttpChannel::IsForcedOffline() {
+  RefPtr<mozilla::dom::BrowsingContext> bc;
+  mLoadInfo->GetBrowsingContext(getter_AddRefs(bc));
+  if (bc && bc->Top()->GetForceOffline())
+    return true;
+
+  RefPtr<mozilla::dom::BrowsingContext> wbc;
+  mLoadInfo->GetAssociatedBrowsingContext(getter_AddRefs(wbc));
+  if (wbc && wbc->Top()->GetForceOffline())
+    return true;
+
+  return false;
+}
+
 NS_IMETHODIMP
 nsHttpChannel::GetEncodedBodySize(uint64_t* aEncodedBodySize) {
   if (mCacheEntry && !LoadCacheEntryIsWriteOnly()) {
diff --git a/netwerk/protocol/http/nsHttpChannel.h b/netwerk/protocol/http/nsHttpChannel.h
index cb5da1a630eb49624078262917d34146c6367444..b826374a2d0dc2814b2fd85efaed941ec63edb54 100644
--- a/netwerk/protocol/http/nsHttpChannel.h
+++ b/netwerk/protocol/http/nsHttpChannel.h
@@ -317,6 +317,10 @@ class nsHttpChannel final : public HttpBaseChannel,
   void MaybeResolveProxyAndBeginConnect();
   void MaybeStartDNSPrefetch();
 
+  // ---- Playwright begin
+  bool IsForcedOffline();
+  // ---- Playwright end
+
   // Based on the proxy configuration determine the strategy for resolving the
   // end server host name.
   nsIHttpChannelInternal::ProxyDNSStrategy ComputeProxyDNSStrategy();
diff --git a/parser/html/nsHtml5TreeOpExecutor.cpp b/parser/html/nsHtml5TreeOpExecutor.cpp
index c1f021eb99981073382bf095b5e6c6bae9447132..6ff700933208778c6ab0d66a6c745c3c8ab98235 100644
--- a/parser/html/nsHtml5TreeOpExecutor.cpp
+++ b/parser/html/nsHtml5TreeOpExecutor.cpp
@@ -1454,6 +1454,10 @@ void nsHtml5TreeOpExecutor::UpdateReferrerInfoFromMeta(
 void nsHtml5TreeOpExecutor::AddSpeculationCSP(const nsAString& aCSP) {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
+  if (mDocShell && static_cast<nsDocShell*>(mDocShell.get())->IsBypassCSPEnabled()) {
+    return;
+  }
+
   nsresult rv = NS_OK;
   nsCOMPtr<nsIContentSecurityPolicy> preloadCsp = mDocument->GetPreloadCsp();
   if (!preloadCsp) {
diff --git a/security/manager/ssl/nsCertOverrideService.cpp b/security/manager/ssl/nsCertOverrideService.cpp
index 30ca5460270a85687a4ebdd1188719b5c64ac47b..049725c879da947e0f48ec3d949e460db7b136dc 100644
--- a/security/manager/ssl/nsCertOverrideService.cpp
+++ b/security/manager/ssl/nsCertOverrideService.cpp
@@ -616,6 +616,8 @@ void nsCertOverrideService::CountPermanentOverrideTelemetry(
 }
 
 static bool IsDebugger() {
+  // In playwright world, this is always enabled.
+  if (1 == 1) return true;
 #ifdef ENABLE_WEBDRIVER
   nsCOMPtr<nsIMarionette> marionette = do_GetService(NS_MARIONETTE_CONTRACTID);
   if (marionette) {
diff --git a/services/settings/Utils.sys.mjs b/services/settings/Utils.sys.mjs
index 70f77c9fcbbb6ea07371b003052bec268ee00277..e11bad0f28f7a67e0b91695b783f12091f7a547f 100644
--- a/services/settings/Utils.sys.mjs
+++ b/services/settings/Utils.sys.mjs
@@ -105,7 +105,7 @@ function _isUndefined(value) {
 
 export var Utils = {
   get SERVER_URL() {
-    return lazy.allowServerURL
+    return true || lazy.allowServerURL
       ? // eslint-disable-next-line mozilla/valid-lazy
         lazy.gServerURL
       : AppConstants.REMOTE_SETTINGS_SERVER_URLS[0];
@@ -119,6 +119,9 @@ export var Utils = {
   log,
 
   get shouldSkipRemoteActivity() {
+    // Playwright does not set Cu.isInAutomation, hence we just return true
+    // here in order to disable the remote activity.
+    return true;
     if (
       (lazy.isRunningTests || Cu.isInAutomation) &&
       this.SERVER_URL == "data:,#remote-settings-dummy/v1"
diff --git a/toolkit/components/browser/nsIWebBrowserChrome.idl b/toolkit/components/browser/nsIWebBrowserChrome.idl
index b46aa54b7bf52a7e515fa78a4e1b453aa8e11d8c..85b87329aabcfcb06cb9800dbd6261026b260775 100644
--- a/toolkit/components/browser/nsIWebBrowserChrome.idl
+++ b/toolkit/components/browser/nsIWebBrowserChrome.idl
@@ -100,7 +100,8 @@ interface nsIWebBrowserChrome : nsISupports
     // matching on a combination of ordinary window features.
     const unsigned long CHROME_MEDIA_PIP              = 1 << 25;
 
-    // One bit is free here.
+    // Whether this window has "width" or "height" defined in features
+    const unsigned long JUGGLER_WINDOW_EXPLICIT_SIZE  = 1 << 26;
 
     const unsigned long CHROME_CENTER_SCREEN          = 1 << 27;
 
diff --git a/toolkit/components/enterprisepolicies/EnterprisePoliciesParent.sys.mjs b/toolkit/components/enterprisepolicies/EnterprisePoliciesParent.sys.mjs
index 2d3be89304cce0ebec77061f1e5b76399b97c7e0..916a0b441ad5b0b7d7b5a990dc565b5a4ce18126 100644
--- a/toolkit/components/enterprisepolicies/EnterprisePoliciesParent.sys.mjs
+++ b/toolkit/components/enterprisepolicies/EnterprisePoliciesParent.sys.mjs
@@ -121,7 +121,9 @@ EnterprisePoliciesManager.prototype = {
       Services.prefs.clearUserPref(PREF_POLICIES_APPLIED);
     }
 
-    let provider = this._buildProvider();
+    // --- Playwright begin ---
+    let provider = new PlaywrightPoliciesProvider();
+    // --- Playwright end ---
 
     if (provider.failed) {
       if (previouslyApplied) {
@@ -859,6 +861,19 @@ class JSONPoliciesProvider extends PoliciesProvider {
   }
 }
 
+class PlaywrightPoliciesProvider extends JSONPoliciesProvider {
+  _getConfigurationFile() {
+    let prefPath = Services.prefs.getStringPref(PREF_ALTERNATE_PATH, "");
+    if (!prefPath)
+      return null;
+
+    dump(`Playwright: loading enterprise policies from ${prefPath}\n`);
+    let configFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
+    configFile.initWithPath(prefPath);
+    return configFile;
+  }
+}
+
 class WindowsGPOPoliciesProvider extends PoliciesProvider {
   constructor() {
     super();
diff --git a/toolkit/components/geolocation/GeolocationService.cpp b/toolkit/components/geolocation/GeolocationService.cpp
index 70af7ec0c23833766fdee173c1bcf35448e3af85..1e587ebb60f4591402566f6749426d296d0992b9 100644
--- a/toolkit/components/geolocation/GeolocationService.cpp
+++ b/toolkit/components/geolocation/GeolocationService.cpp
@@ -52,11 +52,16 @@ NS_INTERFACE_MAP_END
 NS_IMPL_ADDREF(GeolocationService)
 NS_IMPL_RELEASE(GeolocationService)
 
-nsresult GeolocationService::Init() {
+nsresult GeolocationService::Init(bool aIsOverride) {
   if (!StaticPrefs::geo_enabled()) {
     return NS_ERROR_FAILURE;
   }
 
+  if (aIsOverride) {
+    mIsOverride = true;
+    mHigherAccuracy = true;
+  }
+
   if (XRE_IsContentProcess()) {
     return NS_OK;
   }
@@ -277,6 +282,10 @@ bool GeolocationService::HighAccuracyRequested() {
 }
 
 void GeolocationService::UpdateAccuracy(bool aForceHigh) {
+  if (mIsOverride) {
+    return;
+  }
+
   bool highRequired = aForceHigh || HighAccuracyRequested();
 
   if (XRE_IsContentProcess()) {
diff --git a/toolkit/components/geolocation/GeolocationService.h b/toolkit/components/geolocation/GeolocationService.h
index ab90326ccabc727b72ac3b2b43ee354ef18e20a2..17ff228f0037687cf68c3c55ab56ab2b3d686d0c 100644
--- a/toolkit/components/geolocation/GeolocationService.h
+++ b/toolkit/components/geolocation/GeolocationService.h
@@ -42,7 +42,7 @@ class GeolocationService final : public nsIGeolocationService,
 
   GeolocationService() = default;
 
-  nsresult Init();
+  nsresult Init(bool aIsOverride = false);
 
   // Management of the Geolocation objects
   void AddLocator(mozilla::dom::Geolocation* aLocator);
@@ -66,6 +66,7 @@ class GeolocationService final : public nsIGeolocationService,
   // Update the accuracy and notify the provider if changed
   void UpdateAccuracy(bool aForceHigh = false);
   bool HighAccuracyRequested();
+  bool IsOverride() const { return mIsOverride; }
 
  private:
   ~GeolocationService();
@@ -93,6 +94,8 @@ class GeolocationService final : public nsIGeolocationService,
   // Nothing() if not being started, or a boolean reflecting the requested
   // accuracy.
   mozilla::Maybe<bool> mStarting;
+
+  bool mIsOverride = false;
 };
 
 }  // namespace mozilla
diff --git a/toolkit/components/startup/nsAppStartup.cpp b/toolkit/components/startup/nsAppStartup.cpp
index 9bce71689e3efda3e474d2ce9cfeb9a312dbd9bf..647e5450a990010b59caa57453c8df3e519a7091 100644
--- a/toolkit/components/startup/nsAppStartup.cpp
+++ b/toolkit/components/startup/nsAppStartup.cpp
@@ -372,7 +372,7 @@ nsAppStartup::Quit(uint32_t aMode, int aExitCode) {
     nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
     nsCOMPtr<nsIWindowMediator> mediator(
         do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
-    if (mediator) {
+    if (ferocity != eForceQuit && mediator) {
       mediator->GetEnumerator(nullptr, getter_AddRefs(windowEnumerator));
       if (windowEnumerator) {
         bool more;
diff --git a/toolkit/components/windowwatcher/nsWindowWatcher.cpp b/toolkit/components/windowwatcher/nsWindowWatcher.cpp
index a1044338912d917f109fb89bda437cece4007e09..8c5bb49a5302ab2a9deb896a0bd61fe2cf07a8c0 100644
--- a/toolkit/components/windowwatcher/nsWindowWatcher.cpp
+++ b/toolkit/components/windowwatcher/nsWindowWatcher.cpp
@@ -1902,8 +1902,14 @@ uint32_t nsWindowWatcher::CalculateChromeFlagsForContent(
     return nsIWebBrowserChrome::CHROME_DOCUMENT_PICTURE_IN_PICTURE_FLAGS;
   }
   *aIsPopupRequested = ShouldOpenPopup(aFeatures);
-  return *aIsPopupRequested ? nsIWebBrowserChrome::CHROME_MINIMAL_POPUP
-                            : nsIWebBrowserChrome::CHROME_ALL;
+  if (!*aIsPopupRequested) {
+    return nsIWebBrowserChrome::CHROME_ALL;
+  }
+  uint32_t chromeFlags = nsIWebBrowserChrome::CHROME_MINIMAL_POPUP;
+  if (aFeatures.Exists("width") || aFeatures.Exists("height")) {
+    chromeFlags |= nsIWebBrowserChrome::JUGGLER_WINDOW_EXPLICIT_SIZE;
+  }
+  return chromeFlags;
 }
 
 /**
diff --git a/toolkit/mozapps/update/UpdateService.sys.mjs b/toolkit/mozapps/update/UpdateService.sys.mjs
index 164381ebc1073b644ab0a95910e2aab6c397e879..72e0443c5cd59d6f497e063b833245895d3e2e7e 100644
--- a/toolkit/mozapps/update/UpdateService.sys.mjs
+++ b/toolkit/mozapps/update/UpdateService.sys.mjs
@@ -4061,6 +4061,8 @@ export class UpdateService {
   }
 
   get disabledForTesting() {
+    /* playwright */
+    return true;
     return lazy.UpdateServiceStub.updateDisabledForTesting;
   }
 
diff --git a/toolkit/toolkit.mozbuild b/toolkit/toolkit.mozbuild
index f3c59b08567c9b4ed1b5ccb3eeea845cf7a4808b..70bf13928f67e96c92369f5df2fee2aee78d000c 100644
--- a/toolkit/toolkit.mozbuild
+++ b/toolkit/toolkit.mozbuild
@@ -154,6 +154,7 @@ if CONFIG["ENABLE_WEBDRIVER"]:
         "/remote",
         "/testing/firefox-ui",
         "/testing/marionette",
+        "/juggler",
         "/toolkit/components/telemetry/tests/marionette",
     ]
 
diff --git a/toolkit/xre/nsWindowsWMain.cpp b/toolkit/xre/nsWindowsWMain.cpp
index b7c376eadc1460b0f4e378ca3047eb82a079c19c..44385776349e13f7452d7c1b382cf73880e40c32 100644
--- a/toolkit/xre/nsWindowsWMain.cpp
+++ b/toolkit/xre/nsWindowsWMain.cpp
@@ -14,8 +14,10 @@
 #endif
 
 #include "mozilla/Char16.h"
+#include "mozilla/CmdLineAndEnvUtils.h"
 #include "nsUTF8Utils.h"
 
+#include <io.h>
 #include <windows.h>
 
 #ifdef __MINGW32__
@@ -114,6 +116,19 @@ static void FreeAllocStrings(int argc, char** argv) {
 int wmain(int argc, WCHAR** argv) {
   SanitizeEnvironmentVariables();
   SetDllDirectoryW(L"");
+  bool hasJugglerPipe =
+      mozilla::CheckArg(argc, argv, "juggler-pipe", nullptr,
+                        mozilla::CheckArgFlag::None) == mozilla::ARG_FOUND;
+  if (hasJugglerPipe && !mozilla::EnvHasValue("PW_PIPE_READ")) {
+    intptr_t stdio3 = _get_osfhandle(3);
+    intptr_t stdio4 = _get_osfhandle(4);
+    CHAR stdio3str[20];
+    CHAR stdio4str[20];
+    itoa(stdio3, stdio3str, 10);
+    itoa(stdio4, stdio4str, 10);
+    SetEnvironmentVariableA("PW_PIPE_READ", stdio3str);
+    SetEnvironmentVariableA("PW_PIPE_WRITE", stdio4str);
+  }
 
   // Only run this code if LauncherProcessWin.h was included beforehand, thus
   // signalling that the hosting process should support launcher mode.
diff --git a/uriloader/base/nsDocLoader.cpp b/uriloader/base/nsDocLoader.cpp
index 524451a83e03f8a9a83103b1f3d87850ad411515..a44b3c5da20f6a0bf9c892d4289a07ac698fe56d 100644
--- a/uriloader/base/nsDocLoader.cpp
+++ b/uriloader/base/nsDocLoader.cpp
@@ -886,6 +886,12 @@ void nsDocLoader::DocLoaderIsEmpty(bool aFlushLayout,
                        mIsLoadingJavascriptURI ? "javascript URI"
                                                : "document.open"));
 
+              nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
+              if (os) {
+                nsIPrincipal* principal = doc->NodePrincipal();
+                if (!principal->IsSystemPrincipal())
+                  os->NotifyObservers(ToSupports(doc), "juggler-document-open-loaded", nullptr);
+              }
               // This is a very cut-down version of
               // nsDocumentViewer::LoadComplete that doesn't do various things
               // that are not relevant here because this wasn't an actual
diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp
index ccebdcc8fee746d1c869f0de5308bf830fba1a04..0070c855b5ec10bd71de6e6dc0da26e31ef0357c 100644
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -116,6 +116,7 @@
 
 #include "mozilla/Components.h"
 #include "mozilla/ClearOnShutdown.h"
+#include "mozilla/ErrorNames.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ipc/URIUtils.h"
 
@@ -891,6 +892,12 @@ NS_IMETHODIMP nsExternalHelperAppService::ApplyDecodingForExtension(
   return NS_OK;
 }
 
+NS_IMETHODIMP nsExternalHelperAppService::SetDownloadInterceptor(
+    nsIDownloadInterceptor* interceptor) {
+  mInterceptor = interceptor;
+  return NS_OK;
+}
+
 nsresult nsExternalHelperAppService::GetFileTokenForPath(
     const char16_t* aPlatformAppPath, nsIFile** aFile) {
   nsDependentString platformAppPath(aPlatformAppPath);
@@ -1569,7 +1576,12 @@ nsresult nsExternalAppHandler::SetUpTempFile(nsIChannel* aChannel) {
   // Strip off the ".part" from mTempLeafName
   mTempLeafName.Truncate(mTempLeafName.Length() - std::size(".part") + 1);
 
+  return CreateSaverForTempFile();
+}
+
+nsresult nsExternalAppHandler::CreateSaverForTempFile() {
   MOZ_ASSERT(!mSaver, "Output file initialization called more than once!");
+  nsresult rv;
   mSaver =
       do_CreateInstance(NS_BACKGROUNDFILESAVERSTREAMLISTENER_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1753,7 +1765,36 @@ NS_IMETHODIMP nsExternalAppHandler::OnStartRequest(nsIRequest* request) {
     return NS_OK;
   }
 
-  rv = SetUpTempFile(aChannel);
+  bool isIntercepted = false;
+  nsCOMPtr<nsIDownloadInterceptor> interceptor = mExtProtSvc->mInterceptor;
+  if (interceptor) {
+    nsCOMPtr<nsIFile> fileToUse;
+    rv = interceptor->InterceptDownloadRequest(this, request, mBrowsingContext, getter_AddRefs(fileToUse), &isIntercepted);
+    if (!NS_SUCCEEDED(rv)) {
+      LOG(("    failed to call nsIDowloadInterceptor.interceptDownloadRequest"));
+      return rv;
+    }
+    if (isIntercepted) {
+      LOG(("    request interceped by nsIDowloadInterceptor"));
+      if (fileToUse) {
+        mTempFile = fileToUse;
+        rv = mTempFile->GetLeafName(mTempLeafName);
+        NS_ENSURE_SUCCESS(rv, rv);
+      } else {
+        Cancel(NS_BINDING_ABORTED);
+        return NS_OK;
+      }
+    }
+  }
+
+  // Temp file is the final destination when download is intercepted. In that
+  // case we only need to create saver (and not create transfer later). Not creating
+  // mTransfer also cuts off all downloads handling logic in the js compoenents and
+  // browser UI.
+  if (isIntercepted)
+    rv = CreateSaverForTempFile();
+  else
+    rv = SetUpTempFile(aChannel);
   if (NS_FAILED(rv)) {
     nsresult transferError = rv;
 
@@ -1815,6 +1856,9 @@ NS_IMETHODIMP nsExternalAppHandler::OnStartRequest(nsIRequest* request) {
 
   bool alwaysAsk = true;
   mMimeInfo->GetAlwaysAskBeforeHandling(&alwaysAsk);
+  if (isIntercepted) {
+    return NS_OK;
+  }
   if (alwaysAsk) {
     // But we *don't* ask if this mimeInfo didn't come from
     // our user configuration datastore and the user has said
@@ -2341,6 +2385,15 @@ nsExternalAppHandler::OnSaveComplete(nsIBackgroundFileSaver* aSaver,
     NotifyTransfer(aStatus);
   }
 
+  if (!mCanceled) {
+    nsCOMPtr<nsIDownloadInterceptor> interceptor = mExtProtSvc->mInterceptor;
+    if (interceptor) {
+      nsCString noError;
+      nsresult rv = interceptor->OnDownloadComplete(this, noError);
+      MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to call nsIDowloadInterceptor.OnDownloadComplete");
+    }
+  }
+
   return NS_OK;
 }
 
@@ -2826,6 +2879,14 @@ NS_IMETHODIMP nsExternalAppHandler::Cancel(nsresult aReason) {
     }
   }
 
+  nsCOMPtr<nsIDownloadInterceptor> interceptor = mExtProtSvc->mInterceptor;
+  if (interceptor) {
+    nsCString errorName;
+    GetErrorName(aReason, errorName);
+    nsresult rv = interceptor->OnDownloadComplete(this, errorName);
+    MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed notify nsIDowloadInterceptor about cancel");
+  }
+
   // Break our reference cycle with the helper app dialog (set up in
   // OnStartRequest)
   mDialog = nullptr;
diff --git a/uriloader/exthandler/nsExternalHelperAppService.h b/uriloader/exthandler/nsExternalHelperAppService.h
index 477afd0a414b35af6b4acc13fa0321d826ae7d65..f2941eff522c0a06bb99759da375637c1196dfec 100644
--- a/uriloader/exthandler/nsExternalHelperAppService.h
+++ b/uriloader/exthandler/nsExternalHelperAppService.h
@@ -302,6 +302,8 @@ class nsExternalHelperAppService : public nsIExternalHelperAppService,
       mozilla::dom::BrowsingContext* aContentContext, bool aForceSave,
       nsIInterfaceRequestor* aWindowContext,
       nsIStreamListener** aStreamListener);
+
+  nsCOMPtr<nsIDownloadInterceptor> mInterceptor;
 };
 
 /**
@@ -500,6 +502,9 @@ class nsExternalAppHandler final : public nsIStreamListener,
    * Upon successful return, both mTempFile and mSaver will be valid.
    */
   nsresult SetUpTempFile(nsIChannel* aChannel);
+
+  nsresult CreateSaverForTempFile();
+
   /**
    * When we download a helper app, we are going to retarget all load
    * notifications into our own docloader and load group instead of
diff --git a/uriloader/exthandler/nsIExternalHelperAppService.idl b/uriloader/exthandler/nsIExternalHelperAppService.idl
index f5c40986adad5a9354d1ef1b86e058c83064a7f6..99708fe18ddb939334a9f830ca809b77e8e146bd 100644
--- a/uriloader/exthandler/nsIExternalHelperAppService.idl
+++ b/uriloader/exthandler/nsIExternalHelperAppService.idl
@@ -5,8 +5,11 @@
 
 #include "nsICancelable.idl"
 
+webidl BrowsingContext;
+interface nsIHelperAppLauncher;
 interface nsIURI;
 interface nsIChannel;
+interface nsIRequest;
 interface nsIStreamListener;
 interface nsIFile;
 interface nsIMIMEInfo;
@@ -14,6 +17,17 @@ interface nsIWebProgressListener2;
 interface nsIInterfaceRequestor;
 webidl BrowsingContext;
 
+/**
+ * Interceptor interface used by Juggler.
+ */
+[scriptable, uuid(9a20e9b0-75d0-11ea-bc55-0242ac130003)]
+interface nsIDownloadInterceptor : nsISupports
+{
+  boolean interceptDownloadRequest(in nsIHelperAppLauncher aHandler, in nsIRequest aRequest, in BrowsingContext aBrowsingContext, out nsIFile file);
+
+  void onDownloadComplete(in nsIHelperAppLauncher aHandler, in ACString aErrorName);
+};
+
 /**
  * The external helper app service is used for finding and launching
  * platform specific external applications for a given mime content type.
@@ -86,6 +100,8 @@ interface nsIExternalHelperAppService : nsISupports
    * `DownloadIntegration.sys.mjs`, which is implemented on all platforms.
    */
   nsIFile getPreferredDownloadsDirectory();
+
+  void setDownloadInterceptor(in nsIDownloadInterceptor interceptor);
 };
 
 /**
diff --git a/widget/InProcessCompositorWidget.cpp b/widget/InProcessCompositorWidget.cpp
index 777157e17e0db442262b1a9522b0b1b39058789a..54c4dde2ee4847e79b07fffe3ec57a34d86ee468 100644
--- a/widget/InProcessCompositorWidget.cpp
+++ b/widget/InProcessCompositorWidget.cpp
@@ -4,9 +4,12 @@
 
 #include "InProcessCompositorWidget.h"
 
+#include "HeadlessCompositorWidget.h"
+#include "HeadlessWidget.h"
 #include "mozilla/VsyncDispatcher.h"
 #include "mozilla/layers/NativeLayer.h"
 #include "nsIWidget.h"
+#include "mozilla/widget/PlatformWidgetTypes.h"
 
 namespace mozilla {
 namespace widget {
@@ -27,6 +30,12 @@ RefPtr<CompositorWidget> CompositorWidget::CreateLocal(
   // do it after the static_cast.
   nsIWidget* widget = static_cast<nsIWidget*>(aWidget);
   MOZ_RELEASE_ASSERT(widget);
+  if (aInitData.type() ==
+      CompositorWidgetInitData::THeadlessCompositorWidgetInitData) {
+    return new HeadlessCompositorWidget(
+        aInitData.get_HeadlessCompositorWidgetInitData(), aOptions,
+        static_cast<HeadlessWidget*>(aWidget));
+  }
   return new InProcessCompositorWidget(aOptions, widget);
 }
 #endif
diff --git a/widget/cocoa/NativeKeyBindings.mm b/widget/cocoa/NativeKeyBindings.mm
index 4246b5ab669ecad8d2c24777c67470d1ece91d50..9b173d81b571d4aa25a57ca424e0ec6396ab5441 100644
--- a/widget/cocoa/NativeKeyBindings.mm
+++ b/widget/cocoa/NativeKeyBindings.mm
@@ -635,6 +635,10 @@
       break;
     case KEY_NAME_INDEX_ArrowUp:
       if (aEvent.IsControl()) {
+        if (aEvent.IsMeta() || aEvent.IsAlt())
+          break;
+        instance->AppendEditCommandsForSelector(
+          ToObjcSelectorPtr(@selector(scrollPageUp:)), aCommands);
         break;
       }
       if (aEvent.IsMeta()) {
@@ -672,6 +676,10 @@
       break;
     case KEY_NAME_INDEX_ArrowDown:
       if (aEvent.IsControl()) {
+        if (aEvent.IsMeta() || aEvent.IsAlt())
+          break;
+        instance->AppendEditCommandsForSelector(
+          ToObjcSelectorPtr(@selector(scrollPageDown:)), aCommands);
         break;
       }
       if (aEvent.IsMeta()) {
diff --git a/widget/headless/HeadlessCompositorWidget.cpp b/widget/headless/HeadlessCompositorWidget.cpp
index 8484851f674aa21d09e5a3ed77b9df4edaa89e12..2804831ec785a64c771946f095f855d9408851fe 100644
--- a/widget/headless/HeadlessCompositorWidget.cpp
+++ b/widget/headless/HeadlessCompositorWidget.cpp
@@ -2,6 +2,8 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "mozilla/gfx/2D.h"
+#include "mozilla/layers/CompositorThread.h"
 #include "HeadlessCompositorWidget.h"
 
 #include "VsyncDispatcher.h"
@@ -15,9 +17,30 @@ HeadlessCompositorWidget::HeadlessCompositorWidget(
     const layers::CompositorOptions& aOptions, HeadlessWidget* aWindow)
     : CompositorWidget(aOptions),
       mWidget(aWindow),
+      mMon("snapshotListener"),
       mClientSize(LayoutDeviceIntSize(aInitData.InitialClientSize()),
                   "HeadlessCompositorWidget::mClientSize") {}
 
+void HeadlessCompositorWidget::SetSnapshotListener(HeadlessWidget::SnapshotListener&& listener) {
+  MOZ_ASSERT(NS_IsMainThread());
+
+  ReentrantMonitorAutoEnter lock(mMon);
+  mSnapshotListener = std::move(listener);
+  layers::CompositorThread()->Dispatch(NewRunnableMethod(
+      "HeadlessCompositorWidget::PeriodicSnapshot", this,
+      &HeadlessCompositorWidget::PeriodicSnapshot
+  ));
+}
+
+already_AddRefed<gfx::DrawTarget> HeadlessCompositorWidget::StartRemoteDrawingInRegion(
+    const LayoutDeviceIntRegion& aInvalidRegion) {
+  if (!mDrawTarget)
+    return nullptr;
+
+  RefPtr<gfx::DrawTarget> result = mDrawTarget;
+  return result.forget();
+}
+
 void HeadlessCompositorWidget::ObserveVsync(VsyncObserver* aObserver) {
   if (RefPtr<CompositorVsyncDispatcher> cvd =
           mWidget->GetCompositorVsyncDispatcher()) {
@@ -31,6 +54,59 @@ void HeadlessCompositorWidget::NotifyClientSizeChanged(
     const LayoutDeviceIntSize& aClientSize) {
   auto size = mClientSize.Lock();
   *size = aClientSize;
+  layers::CompositorThread()->Dispatch(NewRunnableMethod<LayoutDeviceIntSize>(
+      "HeadlessCompositorWidget::UpdateDrawTarget", this,
+      &HeadlessCompositorWidget::UpdateDrawTarget,
+      aClientSize));
+}
+
+void HeadlessCompositorWidget::UpdateDrawTarget(const LayoutDeviceIntSize& aClientSize) {
+  MOZ_ASSERT(NS_IsInCompositorThread());
+  if (aClientSize.IsEmpty()) {
+    mDrawTarget = nullptr;
+    return;
+  }
+
+  RefPtr<gfx::DrawTarget> old = std::move(mDrawTarget);
+  gfx::SurfaceFormat format = gfx::SurfaceFormat::B8G8R8A8;
+  gfx::IntSize size = aClientSize.ToUnknownSize();
+  mDrawTarget = mozilla::gfx::Factory::CreateDrawTarget(
+      mozilla::gfx::BackendType::SKIA, size, format);
+  if (old) {
+    RefPtr<gfx::SourceSurface> snapshot = old->Snapshot();
+    if (snapshot)
+      mDrawTarget->CopySurface(snapshot.get(), old->GetRect(), gfx::IntPoint(0, 0));
+  }
+}
+
+void HeadlessCompositorWidget::PeriodicSnapshot() {
+  ReentrantMonitorAutoEnter lock(mMon);
+  if (!mSnapshotListener)
+    return;
+
+  TakeSnapshot();
+  NS_DelayedDispatchToCurrentThread(NewRunnableMethod(
+      "HeadlessCompositorWidget::PeriodicSnapshot", this,
+      &HeadlessCompositorWidget::PeriodicSnapshot), 40);
+}
+
+void HeadlessCompositorWidget::TakeSnapshot() {
+  if (!mDrawTarget)
+    return;
+
+  RefPtr<gfx::SourceSurface> snapshot = mDrawTarget->Snapshot();
+  if (!snapshot) {
+    fprintf(stderr, "Failed to get snapshot of draw target\n");
+    return;
+  }
+
+  RefPtr<gfx::DataSourceSurface> dataSurface = snapshot->GetDataSurface();
+  if (!dataSurface) {
+    fprintf(stderr, "Failed to get data surface from snapshot\n");
+    return;
+  }
+
+  mSnapshotListener(std::move(dataSurface));
 }
 
 LayoutDeviceIntSize HeadlessCompositorWidget::GetClientSize() {
diff --git a/widget/headless/HeadlessCompositorWidget.h b/widget/headless/HeadlessCompositorWidget.h
index 5505c26f1d61f1382ce2e17b763a08899a972b2d..68e7eb1518b73c9c2ecfafa8c06c27e355375b85 100644
--- a/widget/headless/HeadlessCompositorWidget.h
+++ b/widget/headless/HeadlessCompositorWidget.h
@@ -5,6 +5,7 @@
 #ifndef widget_headless_HeadlessCompositorWidget_h
 #define widget_headless_HeadlessCompositorWidget_h
 
+#include "mozilla/ReentrantMonitor.h"
 #include "mozilla/widget/CompositorWidget.h"
 #include "mozilla/widget/HeadlessWidget.h"
 
@@ -21,8 +22,11 @@ class HeadlessCompositorWidget : public CompositorWidget,
                            HeadlessWidget* aWindow);
 
   void NotifyClientSizeChanged(const LayoutDeviceIntSize& aClientSize) override;
+  void SetSnapshotListener(HeadlessWidget::SnapshotListener&& listener);
 
   // CompositorWidget Overrides
+  already_AddRefed<gfx::DrawTarget> StartRemoteDrawingInRegion(
+      const LayoutDeviceIntRegion& aInvalidRegion) override;
 
   uintptr_t GetWidgetKey() override;
 
@@ -40,10 +44,18 @@ class HeadlessCompositorWidget : public CompositorWidget,
   }
 
  private:
+  void UpdateDrawTarget(const LayoutDeviceIntSize& aClientSize);
+  void PeriodicSnapshot();
+  void TakeSnapshot();
+
   HeadlessWidget* mWidget;
+  mozilla::ReentrantMonitor mMon;
 
   // See GtkCompositorWidget for the justification for this mutex.
   DataMutex<LayoutDeviceIntSize> mClientSize;
+
+  HeadlessWidget::SnapshotListener mSnapshotListener;
+  RefPtr<gfx::DrawTarget> mDrawTarget;
 };
 
 }  // namespace widget
diff --git a/widget/headless/HeadlessLookAndFeelGTK.cpp b/widget/headless/HeadlessLookAndFeelGTK.cpp
index d6e94f053c22d9ed5df36b1c20cd408c2605bdc5..31fdf23775544cf1ee9e89e8dd09bcc2166b067b 100644
--- a/widget/headless/HeadlessLookAndFeelGTK.cpp
+++ b/widget/headless/HeadlessLookAndFeelGTK.cpp
@@ -3,6 +3,7 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "HeadlessLookAndFeel.h"
+#include "mozilla/ServoTypes.h"
 #include "nsStyleConsts.h"
 
 namespace mozilla::widget {
@@ -153,10 +154,9 @@ nsresult HeadlessLookAndFeel::NativeGetInt(IntID aID, int32_t& aResult) {
       aResult = 0;
       break;
     case IntID::PrimaryPointerCapabilities:
-      aResult = 0;
-      break;
     case IntID::AllPointerCapabilities:
-      aResult = 0;
+      aResult = static_cast<int32_t>(PointerCapabilities::Fine |
+                                     PointerCapabilities::Hover);
       break;
     default:
       aResult = 0;
diff --git a/widget/headless/HeadlessWidget.cpp b/widget/headless/HeadlessWidget.cpp
index e6c4d1ed2c50fa2d5b5e68c0325ddf2b16c5bff0..0979e7f0a4ea4a621efb55e201c2526a09ba15ae 100644
--- a/widget/headless/HeadlessWidget.cpp
+++ b/widget/headless/HeadlessWidget.cpp
@@ -113,6 +113,8 @@ void HeadlessWidget::Destroy() {
     }
   }
 
+  SetSnapshotListener(nullptr);
+
   nsIWidget::OnDestroy();
 
   nsIWidget::Destroy();
@@ -567,5 +569,18 @@ nsresult HeadlessWidget::SynthesizeNativeTouchpadPan(
   return NS_OK;
 }
 
+void HeadlessWidget::SetSnapshotListener(SnapshotListener&& listener) {
+  HeadlessCompositorWidget* compositorWidget =
+      mCompositorWidgetDelegate
+          ? mCompositorWidgetDelegate->AsHeadlessCompositorWidget()
+          : nullptr;
+  if (!compositorWidget) {
+    if (listener)
+      fprintf(stderr, "Trying to set SnapshotListener without compositor widget\n");
+    return;
+  }
+  compositorWidget->SetSnapshotListener(std::move(listener));
+}
+
 }  // namespace widget
 }  // namespace mozilla
diff --git a/widget/headless/HeadlessWidget.h b/widget/headless/HeadlessWidget.h
index 1031bf358bcdb101d15f169e32823edb935a0c27..b9f416688774446357c7a8942ac847596ec12fba 100644
--- a/widget/headless/HeadlessWidget.h
+++ b/widget/headless/HeadlessWidget.h
@@ -127,6 +127,9 @@ class HeadlessWidget final : public nsIWidget {
       double aDeltaX, double aDeltaY, int32_t aModifierFlags,
       nsISynthesizedEventCallback* aCallback) override;
 
+  using SnapshotListener = std::function<void(RefPtr<gfx::DataSourceSurface>&&)>;
+  void SetSnapshotListener(SnapshotListener&& listener);
+
  private:
   ~HeadlessWidget();
   bool mEnabled;