Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Playwright throws exception "Browser closed" when testing against MS Edge #17448

Closed
arc95 opened this issue Sep 12, 2022 · 8 comments
Closed

Comments

@arc95
Copy link

arc95 commented Sep 12, 2022

Context:

  • Playwright Version: 1.25.0
  • Operating System: Windows 10 x64
  • .NET version: .NET 6
  • Browser: MS Edge
  • Extra: Visual Studio Enterprise 17.3.2

Code Snippet

[TestMethod]
public async Task LoadPlaywrightPage()
{
    var playwright = await Playwright.CreateAsync();
    var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
    {
        Headless = false,
        Channel = "msedge"
    });
    var context = await browser.NewContextAsync();
    var page = await context.NewPageAsync();
    await page.GotoAsync("https://playwright.dev/dotnet/");

    Assert.IsTrue((await page.TitleAsync()).Contains("Playwright .NET"));
}

Describe the bug

Running Visual Studio Enterprise in non-admin, the above code throws this exception:

Test method PlaywrightTests.PlaywrightTests.LoadPlaywrightPage threw exception: 
   Microsoft.Playwright.PlaywrightException: Browser closed. 
==================== Browser output: ==================== 
C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe --disable-field-trial-config --disable-background-networking 
--enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling 
--disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad 
--disable-client-side-phishing-detection --disable-component-extensions-with-background-pages 
--disable-default-apps --disable-dev-shm-usage --disable-extensions 
--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,
MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,
CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate 
--allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking 
--disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb 
--metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain 
--no-service-autorun --export-tagged-pdf --no-sandbox 
--user-data-dir=C:\Users\MyUserId\AppData\Local\Temp\1\playwright_chromiumdev_profile-XJmwuh 
--remote-debugging-pipe --no-startup-window pid=35316 [pid=35316][out] Opening in existing browser session. 
=========================== logs =========================== 
C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe --disable-field-trial-config --disable-background-networking 
--enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling 
--disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad 
--disable-client-side-phishing-detection --disable-component-extensions-with-background-pages 
--disable-default-apps --disable-dev-shm-usage --disable-extensions 
--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,
MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,
CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate 
--allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking 
--disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb 
--metrics-recording-only --no-first-run --enable-automation --password-store=basic 
--use-mock-keychain --no-service-autorun --export-tagged-pdf --no-sandbox 
--user-data-dir=C:\Users\MyUserId\AppData\Local\Temp\1\playwright_chromiumdev_profile-XJmwuh 
--remote-debugging-pipe --no-startup-window pid=35316 [pid=35316][out] Opening in existing browser session. 
============================================================ 
at Microsoft.Playwright.Transport.Connection.InnerSendMessageToServerAsync[T](String guid, String method, Object args) in 
//src/Playwright/Transport/Connection.cs:line 167 at Microsoft.Playwright.Transport.Connection.WrapApiCallAsync[T](Func`1 
action, Boolean isInternal) at Microsoft.Playwright.Core.BrowserType.LaunchAsync(BrowserTypeLaunchOptions options) in 
//src/Playwright/Core/BrowserType.cs:line 61 at PlaywrightTests.PlaywrightTests.LoadPlaywrightPage() in 
C:\MyProjects\PlaywrightPlayground\PlaywrightTests\PlaywrightTests.cs:line 115 at 
Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action action)

If I open Visual Studio with "Run as administrator", the test runs fine and MS Edge opens successfully. I have a Stack Overflow post about this here: https://stackoverflow.com/questions/73651755/playwright-throws-exception-browser-closed-when-testing-against-ms-edge/

Thank you.

@mxschmitt
Copy link
Member

could you open Microsoft Edge and go to edge://policy? To see if there is relevant policies configured.

Also maybe se the $Env:DEBUG="pw:protocol" env before launching your script which should give us more output.

It might be a duplicate / the same as #13631 but we'd need to confirm via looking at the protocol (setting the env gives us the needed output).

@arc95
Copy link
Author

arc95 commented Sep 13, 2022

Thanks, @mxschmitt. What part of the policy would be useful to share? Also, setting $Env:DEBUG="pw:protocol" didn't alter the exception output; it produced the same result.

@mxschmitt
Copy link
Member

@arc95 since we have no clue yet about which one might be useful, I'd recommend sharing all of them! Do you have ExtensionInstallForcelist policy set?

If you execute it via PowerShell, then you need to execute $Env:DEBUG="pw:protocol" before running tests via dotnet test. If you set the var in VS then DEBUG="pw:protocol" is right. Not sure where to see the stderr in VS.

@arc95
Copy link
Author

arc95 commented Sep 19, 2022

@mxschmitt, I exported the policies; please see below (sensitive data has been replaced with ...). Also, how do you run the DEBUG="pw:protocol" (or similar commands) from VS? Thanks.

{
   "chromeMetadata": {
      "OS": "Windows 10 Version 21H2 (Build 19044.1889)",
      "application": "Microsoft Edge",
      "revision": "ca9c37b5a3be4f51d17650fdb43398de8da7988b",
      "version": "105.0.1343.27 (Official build) (64-bit)"
   },
   "edgePolicies": {
      "AuthSchemes": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": "basic,ntlm"
      },
      "AutofillAddressEnabled": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "AutofillCreditCardEnabled": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "BackgroundModeEnabled": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "BlockThirdPartyCookies": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "DefaultNotificationsSetting": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": 2
      },
      "DefaultPopupsSetting": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": 2
      },
      "DefaultSearchProviderEnabled": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": true
      },
      "DefaultSearchProviderName": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": ""
      },
      "DefaultSearchProviderSearchURL": {
         "error": "Use a valid search URL.",
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": "https://encrypted.google.com"
      },
      "ExemptDomainFileTypePairsFromFileTypeDownloadWarnings": {
         "deprecated": true,
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": [  ]
      },
      "ExtensionInstallForcelist": {
         "error": "List entry \"1\": Value doesn't match expected format.",
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": [ "gmgoamodcdcjnbaobigkjelfplakmdhh;https://edge.microsoft.com/extensionwebstorebase/v1/crx", "(Adblock Plus)" ]
      },
      "ForceEphemeralProfiles": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "HideFirstRunExperience": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": true
      },
      "ImportPaymentInfo": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "ImportSavedPasswords": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "InternetExplorerIntegrationLevel": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": 1
      },
      "InternetExplorerIntegrationSiteList": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": "..."
      },
      "MetricsReportingEnabled": {
         "error": "Unknown policy.",
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": 0
      },
      "PasswordManagerEnabled": {
         "info": "This policy is working as intended but the same value is set elsewhere and is superseded by this policy.",
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "superseded": [ {
            "level": "recommended",
            "scope": "machine",
            "source": "platform",
            "value": false
         } ],
         "value": false
      },
      "PluginsAllowedForUrls": {
         "error": "Unknown policy.",
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": {
            "1": "...",
            "2": "...",
            "3": "...",
            "4": "..."
         }
      },
      "PopupsAllowedForUrls": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": [ ... ]
      },
      "QuicAllowed": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "SavingBrowserHistoryDisabled": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": false
      },
      "UserDataDir": {
         "level": "mandatory",
         "scope": "machine",
         "source": "platform",
         "value": "'${local_app_data}\\Microsoft\\Edge\\User Data'"
      }
   },
   "extensionPolicies": {
   },
   "status": {
      "updater": {
         "domain": "...",
         "timeSinceLastRefresh": "24 mins ago",
         "version": "..."
      }
   }
}

@mxschmitt
Copy link
Member

This was really helpful! Turns out the UserDataDir policy breaks Google Chrome and Microsoft Edge if you run the browser headed, this ends up in getting the Opening in existing browser session. when launching the browser. I'll talk with our team later today what to do then, but most likely nothing we can fix on our side.

I'd recommend contacting your IT to move this group policy from Microsoft Edge to Microsoft Edge - Default Settings (users can override). So the setting is not enforced, and Playwright can change it.

@mxschmitt
Copy link
Member

Closing as per above and we added a note about that in the docs: #17449

@arc95
Copy link
Author

arc95 commented Sep 21, 2022

Thanks, @mxschmitt, for working on this. Your help is much appreciated.

@wyying
Copy link

wyying commented Jul 21, 2023

java使用

`        WebKitScreenshot model = new WebKitScreenshot();
        Map<String,String> map = new HashMap();
        map.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "1");
        String userDataDirPath = "/Users/wyy/AppData/Local/Microsoft/Edge/User Data";
        Path userDataDir = Paths.get(userDataDirPath);

        //跳过下载浏览器后配置浏览器位置
        //map.put("PLAYWRIGHT_BROWSERS_PATH", "C:\\Users\\wyy\\AppData\\Local\\ms-playwright");
        Playwright playwright = Playwright.create(new Playwright.CreateOptions().setEnv(map));
        BrowserType.LaunchPersistentContextOptions options = new BrowserType.LaunchPersistentContextOptions().setHeadless(false).setDevtools(true)//打开浏览器开发者工具,默认不打开
                .setExecutablePath(Paths.get("C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"));

        BrowserType chromium = playwright.chromium();
        BrowserContext browserContext = chromium.launchPersistentContext(userDataDir,options);`
    have a error


   ```

`Exception in thread "main" com.microsoft.playwright.PlaywrightException: Error {
message='Browser closed.
==================== Browser output: ====================
C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --auto-open-devtools-for-tabs --no-sandbox --user-data-dir=\Users\wyy\AppData\Local\Microsoft\Edge\User Data --remote-debugging-pipe about:blank
pid=66804
[pid=66804][out] ��������������Ự�д򿪡�
=========================== logs ===========================
C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe --disable-field-trial-config --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-back-forward-cache --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --auto-open-devtools-for-tabs --no-sandbox --user-data-dir=\Users\wyy\AppData\Local\Microsoft\Edge\User Data --remote-debugging-pipe about:blank
pid=66804
[pid=66804][out] ��������������Ự�д򿪡�

name='Error
stack='Error: Browser closed.`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants