mozilla / geckodriver

WebDriver for Firefox
https://firefox-source-docs.mozilla.org/testing/geckodriver/
Mozilla Public License 2.0
7.03k stars 1.51k forks source link

OpenQA.Selenium.NoSuchWindowException: 'Browsing context has been discarded' #2136

Closed ozerkon closed 6 months ago

ozerkon commented 9 months ago

System

Testcase

Hi. I have an net.core desktop app. The main purpose of this application is to open the message sent by the administrator and click on the "Okudum" (it means 'i read') button on the opened iframe. After the click the next unread message appears automatically and the method wants to test that the iframe is loaded.

error2 fw

At this point geckodriver throws an exception: OpenQA.Selenium.NoSuchWindowException: 'Browsing context has been discarded' error fw

It works flawlessly with Chromedriver. In fact, I was using the application very often about 4 months ago and it was working smoothly with geckodriver. I needed the application again and frankly I would like it to work properly with firefox as well.

Here is the complete method:

        public bool ConfirmMessages(out string msg) {
          lblReport.Text += "* mebbis.meb.gov.tr sayfası açıldı.\r\n";
          msg = "";
          WinHelpers.WaitForPageLoad(out Common.msg);
          if (Common.driver.PageSource.Contains("Doğrulaması Aktif")) {
            Common.mebAjandaActive = true;
            fLogin f = new fLogin(true);
            while (Common.driver.PageSource.Contains("Doğrulaması Aktif") || Common.driver.PageSource.Contains("Doğrulama Gerçekleşmedi")) {
              if (f.ShowDialog() == DialogResult.OK) {
                Common.mebAjandaText = WinHelpers.GetElementBy("i", "txtDogrulamaKodu", out Common.msg);
                Common.mebAjandaButton = WinHelpers.GetElementBy("i", "btnDogrula", out Common.msg);
                if (Common.mebAjandaText != null && Common.mebAjandaButton != null) {
                  Common.mebAjandaText.Clear();
                  Common.mebAjandaText.SendKeys(Common.captcha);
                  Common.mebAjandaButton.Click();
                }
              } else {
                lblMessage.Text = "İşlem iptal edildi";
                Common.driver.Dispose();
                return false;
              }
            }
          }

          IWebElement ? dysFlipMenu = GetDysLink();
          if (dysFlipMenu == null) {
            lblMessage.Text = "DYS giriş linki bulunamadı\r\nLütfen daha sonra tekrar deneyin";
            Common.driver.Dispose();
            return false;
          }
          Actions action = new Actions(Common.driver);
          action.MoveToElement(dysFlipMenu).Perform();

          int tryCount = 0;
          Thread.Sleep(1000);
          if (Common.bgwConfirm.CancellationPending) {
            return false;
          }
          IWebElement ? dysgiris = GetLoginLink();
          if (dysgiris == null) {
            lblMessage.Text = "DYS giriş linki bulunamadı\r\nLütfen daha sonra tekrar deneyin";
            Common.driver.Dispose();
            return false;
          }
          dysgiris.Click();

          if (Common.driver.WindowHandles.Count > 1) {
            Common.driver.SwitchTo().Window(Common.driver.WindowHandles[1]);
            WinHelpers.WaitForPageLoad(out Common.msg);
            if (Common.bgwConfirm.CancellationPending) {
              return false;
            }
          }
          tryCount = 0;
          lblReport.Text += "* dysweb.meb.gov.tr sekmesine geçildi.\r\n";
          List < IWebElement > ? tree = null;

          while (tree == null) {
            Thread.Sleep(100);
            tree = Common.driver.FindElements(By.CssSelector("li[id^='menuForm:roller_tree:']")).ToList();
            tryCount++;
            if (tryCount == 300) {
              lblMessage.Text = "Sayfa 30 saniye boyunca yanıt vermediği için işlem iptal edildi";
              Common.driver.Dispose();
              return false;
            }
            if (Common.bgwConfirm.CancellationPending) {
              return false;
            }
          }

          if (tree.Count > 9) {
            Common.isManager = true;
            Common.mdLink = GetMdLink();
            if (Common.mdLink == null) {
              lblMessage.Text = "İdareci mesajları listelenemdi\r\nLütfen daha sonra tekrar deneyin";
              Common.driver.Dispose();
              return false;
            }
            Common.mdLink.Click();
            if (Common.bgwConfirm.CancellationPending) {
              return false;
            }
          }

          while (!Common.driver.PageSource.Contains("listelenmektedir")) {
            Thread.Sleep(100);
            if (Common.driver.PageSource.Contains("evrak bulunmamaktadır")) {
              lblReport.Text += "* Onaylanmamış mesaj yok.\r\n";
              lblMessage.Text = "Onaylanmamış mesaj yok";
              return false;
            }
            tryCount++;
            if (tryCount == 300) {
              lblReport.Text += "* Sayfa 30 saniye boyunca yanıt vermediği için işlem iptal edildi.\r\n";
              lblMessage.Text = "Sayfa 30 saniye boyunca yanıt vermediği için işlem iptal edildi";
              Common.driver.Dispose();
              return false;
            }
            if (Common.bgwConfirm.CancellationPending) {
              return false;
            }
          }
          IWebElement isler = WinHelpers.GetElementBy("i", "form:etiketFilter", out Common.msg);

          string sayi = isler.Text.Substring(23, isler.Text.Substring(23).IndexOf(" "));

          try {
            Common.totalMessages = Convert.ToInt32(sayi);
            pbProcess.Maximum = Common.totalMessages;
            lblReport.Text += $ "* {Common.totalMessages} adet okunmamış mesaj bulundu.\r\n";
            Common.ilksatir = WinHelpers.GetButtonElementBy("x", "/html/body/div[2]/div[4]/form/div[1]/div/div/div[2]/div/div[2]/table/tbody/tr[1]/td[6]", out Common.msg);
            Common.ilksatir?.Click();
            while (!Common.driver.PageSource.Contains("Gelen Evrak Gözden Geçirme") && !Common.driver.PageSource.Contains("Evrak Görüntüleme")) {
              Thread.Sleep(1000);
              if (Common.bgwConfirm.CancellationPending) {
                return false;
              }
            }

            lblReport.Text += "* Onaylama işlemi başlatılıyor...\r\n";

            for (int i = 0; i < Common.totalMessages; i++) {
              while (!Common.driver.PageSource.Contains("Gelen Evrak Gözden Geçirme") && !Common.driver.PageSource.Contains("Evrak Görüntüleme")) {
                Thread.Sleep(100);
                if (Common.bgwConfirm.CancellationPending) {
                  return false;
                }
              }

              IList < IWebElement > hiddenElements = Common.driver.FindElements(By.CssSelector("ui-dialog"));
              foreach(IWebElement item in hiddenElements) {
                Common.wait?.Until(e => ((IJavaScriptExecutor) Common.driver).ExecuteScript("arguments[0].setAttribute('style', 'display:none')", item));
                if (Common.bgwConfirm.CancellationPending) {
                  return false;
                }
              }

              IWebElement ? iframe = null;
              while (iframe == null) {
                iframe = WinHelpers.GetElementBy("i", "gozdenGecirmeEkraniId", out Common.msg);
                Thread.Sleep(500);
                if (Common.bgwConfirm.CancellationPending) {
                  return false;
                }
                if (Screen.PrimaryScreen?.Bounds.Height < 1080) WinHelpers.ZoomOut();
              }
              Common.driver.SwitchTo().Frame("gozdenGecirmeEkraniId");

              IWebElement ? okudum = null;
              if (Common.driver.PageSource.Contains("Okudum")) {
                okudum = WinHelpers.GetButtonElementBy("x", "//*[@id=\"formspanel:okudumBtn\"]", out Common.msg);
              }
              if (okudum != null) {
                okudum.Click();
                Common.confirmedMessages++;
                pbProcess.Value = Common.confirmedMessages;
                if (Common.bgwConfirm.CancellationPending) {
                  return false;
                }
              } else {
                IWebElement ? kapat = WinHelpers.GetButtonElementBy("x", "//*[@id=\"formspanel:_08001kapat2\"]", out Common.msg);
                if (kapat != null) {
                  kapat.Click();
                  Common.nonConfirmedMessages++;
                  if (Common.bgwConfirm.CancellationPending) {
                    return false;
                  }
                }
                continue;
              }
              while (!Common.driver.PageSource.Contains("Gelen Evrak Gözden Geçirme")) { // throws an error here
                Thread.Sleep(1000);
                if (Common.bgwConfirm.CancellationPending) {
                  return false;
                }
              }
            }
            return true;
          } catch (Exception ex) {
            Common.confirmError = true;
            msg = ex.Message;
            return false;
          }
        }
whimboo commented 9 months ago

@ozerkon when you mark the message as read, is the current iframe maybe removed, and a new one created for the new message? If yes, you would have to switch to the parent frame first and then find and select the new iframe. A trace log would be kinda helpful here. Maybe you can attach one (please not paste directly in here)?

ozerkon commented 8 months ago

First of all, I apologize for being late in responding. As for the answer to your question; No, the iframe does not disappear when a message is marked as read. As I said before, "the system works fine with Google Chrome".

whimboo commented 8 months ago

Ok, so given the lack of running this testcase maybe you can provide a trace log as requested in my last comment? Thanks.

ozerkon commented 8 months ago

firefoxOptions.LogLevel = FirefoxDriverLogLevel.Trace; string logPath = Path.Combine(Application.StartupPath, "geckodriver.log"); firefoxOptions.AddArgument($"-moz-log={logPath}");

Did I make a mistake somewhere? The "geckodriver.log" file is not created.

Frankly, I don't know where else I can get the "trace log" output. I couldn't find any results from my searches on the internet.

whimboo commented 8 months ago

Which Selenium binding is that? Geckodriver always logs to stdout so it would be a Selenium question then. In case of our documentation is outdated we should update it once the solution has been found.

ozerkon commented 8 months ago

Selenium.WebDriver 4.13.0

whimboo commented 8 months ago

This is only the version but not the binding (language).

ozerkon commented 8 months ago

I did not understand your question. When you say language, do you mean programming language? (I write in C#)

whimboo commented 8 months ago

Yes, that is what a binding is for Selenium. Thanks. So does it mean the following lines do not work?

ozerkon commented 8 months ago

Yes, unfortunately it doesn't work.

whimboo commented 8 months ago

Hm, then I don't know how to activate the trace logs in C#. @titusfortner do you know?

whimboo commented 7 months ago

@ozerkon until we know how to create a trace log would you mind in which line of the test the failure actually happens? Maybe we could iterate forward and find the solution.

whimboo commented 6 months ago

No further reply from reporter. Closing as incomplete.

titusfortner commented 5 months ago

Hm, then I don't know how to activate the trace logs in C#. @titusfortner do you know?

Sorry, I missed this. We just added support in 4.16, but we don't have the examples in our docs, yet

whimboo commented 5 months ago

@titusfortner what has been changed to what we have listed at: https://firefox-source-docs.mozilla.org/testing/geckodriver/TraceLogs.html#c-sharp?

titusfortner commented 5 months ago

How didn't that work?

        [TestMethod]
        public void FirefoxLogging()
        {
            var options = new FirefoxOptions();
            options.LogLevel = FirefoxDriverLogLevel.Trace;
            driver = new FirefoxDriver(options);
            driver.Url = "https://www.selenium.dev";
        }

Run with this command:

dotnet test --filter FirefoxLogging     

This goes to console:

  Determining projects to restore...
  All projects are up-to-date for restore.
  SeleniumDocs -> /Users/titusfortner/code/seleniumhq.github.io/examples/dotnet/SeleniumDocs/bin/Debug/net6.0/SeleniumDocs.dll
Test run for /Users/titusfortner/code/seleniumhq.github.io/examples/dotnet/SeleniumDocs/bin/Debug/net6.0/SeleniumDocs.dll (.NETCoreApp,Version=v6.0)
Microsoft (R) Test Execution Command Line Tool Version 17.3.3 (x64)
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
1706650623605   geckodriver     INFO    Listening on 127.0.0.1:59837
1706650623674   mozrunner::runner       INFO    Running command: MOZ_CRASHREPORTER="1" MOZ_CRASHREPORTER_NO_REPORT="1" MOZ_CRASHREPORTER_SHUTDOWN="1" MOZ_NO_REMOTE="1" "/App ... "--marionette" "-foreground" "-no-remote" "-profile" "/var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy"
1706650623675   geckodriver::marionette DEBUG   Waiting 60s to connect to browser on 127.0.0.1
1706650623675   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650623675   geckodriver::marionette TRACE   Retrying in 100ms
1706650623779   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650623779   geckodriver::marionette TRACE   Retrying in 100ms
1706650623880   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650623880   geckodriver::marionette TRACE   Retrying in 100ms
1706650623984   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650623984   geckodriver::marionette TRACE   Retrying in 100ms
console.warn: services.settings: Ignoring preference override of remote settings server
console.warn: services.settings: Allow by setting MOZ_REMOTE_SETTINGS_DEVTOOLS=1 in the environment
1706650624088   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624088   geckodriver::marionette TRACE   Retrying in 100ms
1706650624192   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624192   geckodriver::marionette TRACE   Retrying in 100ms
1706650624295   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624295   geckodriver::marionette TRACE   Retrying in 100ms
1706650624370   Marionette      INFO    Marionette enabled
1706650624373   RemoteAgent     DEBUG   Setting recommended pref apz.content_response_timeout to 60000
1706650624373   RemoteAgent     DEBUG   Setting recommended pref browser.contentblocking.introCount to 99
1706650624373   RemoteAgent     DEBUG   Setting recommended pref browser.download.panel.shown to true
1706650624373   RemoteAgent     DEBUG   Setting recommended pref browser.newtabpage.activity-stream.showSponsoredTopSites to false
1706650624373   RemoteAgent     DEBUG   Setting recommended pref browser.newtabpage.enabled to false
1706650624373   RemoteAgent     DEBUG   Setting recommended pref browser.pagethumbnails.capturing_disabled to true
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.region.network.url to 
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.safebrowsing.blockedURIs.enabled to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.safebrowsing.downloads.enabled to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.safebrowsing.malware.enabled to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.safebrowsing.phishing.enabled to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.search.update to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.startup.couldRestoreSession.count to -1
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.tabs.closeWindowWithLastTab to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.tabs.unloadOnLowMemory to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.tabs.warnOnClose to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.tabs.warnOnCloseOtherTabs to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.tabs.warnOnOpen to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.toolbars.bookmarks.visibility to never
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.topsites.contile.enabled to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.usedOnWindows10.introURL to 
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.urlbar.merino.endpointURL to 
1706650624374   RemoteAgent     DEBUG   Setting recommended pref browser.urlbar.suggest.searches to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref datareporting.policy.dataSubmissionPolicyAccepted to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref dom.disable_open_during_load to false
1706650624374   RemoteAgent     DEBUG   Setting recommended pref dom.file.createInChild to true
1706650624374   RemoteAgent     DEBUG   Setting recommended pref dom.input_events.security.minNumTicks to 0
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.input_events.security.minTimeElapsedInMS to 0
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.max_chrome_script_run_time to 0
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.max_script_run_time to 0
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.navigation.locationChangeRateLimit.count to 0
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.push.connection.enabled to false
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.screenorientation.allow-lock to true
1706650624375   RemoteAgent     DEBUG   Setting recommended pref dom.successive_dialog_time_limit to 0
1706650624375   RemoteAgent     DEBUG   Setting recommended pref extensions.getAddons.cache.enabled to false
1706650624375   RemoteAgent     DEBUG   Setting recommended pref extensions.getAddons.discovery.api_url to data:, 
1706650624375   RemoteAgent     DEBUG   Setting recommended pref extensions.blocklist.detailsURL to http://%(server)s/extensions-dummy/blocklistDetailsURL
1706650624375   RemoteAgent     DEBUG   Setting recommended pref extensions.blocklist.itemURL to http://%(server)s/extensions-dummy/blocklistItemURL
1706650624375   RemoteAgent     DEBUG   Setting recommended pref extensions.hotfix.url to http://%(server)s/extensions-dummy/hotfixURL
1706650624375   RemoteAgent     DEBUG   Setting recommended pref extensions.systemAddon.update.url to http://%(server)s/dummy-system-addons.xml
1706650624376   RemoteAgent     DEBUG   Setting recommended pref extensions.update.background.url to http://%(server)s/extensions-dummy/updateBackgroundURL
1706650624376   RemoteAgent     DEBUG   Setting recommended pref extensions.update.url to http://%(server)s/extensions-dummy/updateURL
1706650624376   RemoteAgent     DEBUG   Setting recommended pref extensions.getAddons.get.url to http://%(server)s/extensions-dummy/repositoryGetURL
1706650624376   RemoteAgent     DEBUG   Setting recommended pref extensions.getAddons.search.browseURL to http://%(server)s/extensions-dummy/repositoryBrowseURL
1706650624376   RemoteAgent     DEBUG   Setting recommended pref geo.provider.network.url to 
1706650624376   RemoteAgent     DEBUG   Setting recommended pref identity.fxaccounts.auth.uri to https://{server}/dummy/fxa
1706650624376   RemoteAgent     DEBUG   Setting recommended pref network.connectivity-service.enabled to false
1706650624376   RemoteAgent     DEBUG   Setting recommended pref network.http.phishy-userpass-length to 255
1706650624379   RemoteAgent     DEBUG   Setting recommended pref network.http.prompt-temp-redirect to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref privacy.trackingprotection.enabled to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref security.fileuri.strict_origin_policy to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref security.notification_enable_delay to 0
1706650624379   RemoteAgent     DEBUG   Setting recommended pref security.remote_settings.intermediates.enabled to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref signon.autofillForms to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref signon.rememberSignons to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref toolkit.telemetry.server to https://%(server)s/telemetry-dummy/
1706650624379   RemoteAgent     DEBUG   Setting recommended pref widget.windows.window_occlusion_tracking.enabled to false
1706650624379   RemoteAgent     DEBUG   Setting recommended pref dom.disable_beforeunload to true
1706650624400   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624401   geckodriver::marionette TRACE   Retrying in 100ms
1706650624504   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624504   geckodriver::marionette TRACE   Retrying in 100ms
1706650624605   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624605   geckodriver::marionette TRACE   Retrying in 100ms
1706650624706   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624706   geckodriver::marionette TRACE   Retrying in 100ms
1706650624809   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624809   geckodriver::marionette TRACE   Retrying in 100ms
1706650624912   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650624912   geckodriver::marionette TRACE   Retrying in 100ms
1706650625017   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650625017   geckodriver::marionette TRACE   Retrying in 100ms
1706650625121   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650625121   geckodriver::marionette TRACE   Retrying in 100ms
1706650625207   Marionette      TRACE   Received observer notification final-ui-startup
1706650625221   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650625221   geckodriver::marionette TRACE   Retrying in 100ms
1706650625322   geckodriver::browser    TRACE   Failed to open /var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy/MarionetteActivePort
1706650625322   geckodriver::marionette TRACE   Retrying in 100ms
1706650625335   Marionette      INFO    Listening on port 59846
1706650625340   Marionette      DEBUG   Marionette is listening
Read port: 59846
1706650625755   Marionette      DEBUG   Accepted connection 0 from 127.0.0.1:59847
1706650625909   geckodriver::marionette DEBUG   Connection to Marionette established on 127.0.0.1:59846.
1706650625939   Marionette      DEBUG   0 -> [0,1,"WebDriver:NewSession",{"browserName":"firefox"}]
1706650625943   Marionette      DEBUG   Waiting for initial application window
1706650627828   Marionette      TRACE   Received observer notification browser-idle-startup-tasks-finished
1706650627836   RemoteAgent     TRACE   [9] ProgressListener Start: expectNavigation=false resolveWhenStarted=false unloadTimeout=5000 waitForExplicitStart=false
1706650627836   RemoteAgent     TRACE   [9] ProgressListener Setting unload timer (5000ms)
1706650627836   RemoteAgent     TRACE   [9] Document already finished loading: about:blank
1706650627836   RemoteAgent     TRACE   [9] ProgressListener Stop: has error=false
1706650627848   Marionette      DEBUG   0 <- [1,1,null,{"sessionId":"8c26c746-c19e-4794-8d43-8d3e0a500f5c","capabilities":{"browserName":"firefox","browserVersion":"121.0.1","platformName":"mac","acceptInsecureCerts":false,"pageLoadStrategy":"normal","setWindowRect":true,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"strictFileInteractability":false,"unhandledPromptBehavior":"dismiss and notify","moz:accessibilityChecks":false,"moz:buildID":"20240108143603","moz:headless":false,"moz:platformVersion":"22.5.0","moz:processID":2499,"moz:profile":"/var/folders/rh/25cw4qq10_157fjpztk0psx80000gn/T/rust_mozprofileyL6UTy","moz:shutdownTimeout":60000,"moz:webdriverClick":true,"moz:windowless":false,"proxy":{}}}]
1706650627852   webdriver::server       DEBUG   <- 200 OK {"value":{"sessionId":"8c26c746-c19e-4794-8d43-8d3e0a500f5c","capabilities":{"acceptInsecureCerts":false,"browserNa ... ctability":false,"timeouts":{"implicit":0,"pageLoad":300000,"script":30000},"unhandledPromptBehavior":"dismiss and notify"}}}
1706650627862   webdriver::server       DEBUG   -> POST /session/8c26c746-c19e-4794-8d43-8d3e0a500f5c/url {"url":"https://www.selenium.dev"}
1706650627862   Marionette      DEBUG   0 -> [0,2,"WebDriver:Navigate",{"url":"https://www.selenium.dev"}]
1706650627866   Marionette      TRACE   [9] Received event beforeunload for about:blank
1706650627959   Marionette      TRACE   Remoteness change detected. Set new top-level browsing context to 11
1706650627968   Marionette      TRACE   [11] Received event beforeunload for about:blank
1706650627973   Marionette      TRACE   [11] Received event pagehide for about:blank
1706650628537   Marionette      TRACE   [11] Received event DOMContentLoaded for https://www.selenium.dev/
1706650628773   Marionette      TRACE   [11] Received event pageshow for https://www.selenium.dev/
1706650628774   Marionette      DEBUG   0 <- [1,2,null,{"value":null}]
1706650628774   webdriver::server       DEBUG   <- 200 OK {"value":null}
1706650628777   webdriver::server       DEBUG   -> DELETE /session/8c26c746-c19e-4794-8d43-8d3e0a500f5c 
1706650628779   Marionette      DEBUG   0 -> [0,3,"Marionette:Quit",{"flags":["eForceQuit"]}]
1706650628779   Marionette      INFO    Stopped listening on port 59846
1706650629180   Marionette      TRACE   Received observer notification quit-application
1706650629183   Marionette      TRACE   Received observer notification quit-application
1706650629183   RemoteAgent     DEBUG   Resetting recommended pref apz.content_response_timeout
1706650629183   RemoteAgent     DEBUG   Resetting recommended pref browser.contentblocking.introCount
1706650629183   RemoteAgent     DEBUG   Resetting recommended pref browser.download.panel.shown
1706650629183   RemoteAgent     DEBUG   Resetting recommended pref browser.newtabpage.activity-stream.showSponsoredTopSites
1706650629185   RemoteAgent     DEBUG   Resetting recommended pref browser.newtabpage.enabled
1706650629185   RemoteAgent     DEBUG   Resetting recommended pref browser.pagethumbnails.capturing_disabled
1706650629185   RemoteAgent     DEBUG   Resetting recommended pref browser.region.network.url
1706650629185   RemoteAgent     DEBUG   Resetting recommended pref browser.safebrowsing.blockedURIs.enabled
1706650629187   RemoteAgent     DEBUG   Resetting recommended pref browser.safebrowsing.downloads.enabled
1706650629189   RemoteAgent     DEBUG   Resetting recommended pref browser.safebrowsing.malware.enabled
1706650629192   RemoteAgent     DEBUG   Resetting recommended pref browser.safebrowsing.phishing.enabled
1706650629194   RemoteAgent     DEBUG   Resetting recommended pref browser.search.update
1706650629194   RemoteAgent     DEBUG   Resetting recommended pref browser.startup.couldRestoreSession.count
1706650629194   RemoteAgent     DEBUG   Resetting recommended pref browser.tabs.closeWindowWithLastTab
1706650629194   RemoteAgent     DEBUG   Resetting recommended pref browser.tabs.unloadOnLowMemory
1706650629194   RemoteAgent     DEBUG   Resetting recommended pref browser.tabs.warnOnClose
1706650629194   RemoteAgent     DEBUG   Resetting recommended pref browser.tabs.warnOnCloseOtherTabs
1706650629195   RemoteAgent     DEBUG   Resetting recommended pref browser.tabs.warnOnOpen
1706650629195   RemoteAgent     DEBUG   Resetting recommended pref browser.toolbars.bookmarks.visibility
1706650629195   RemoteAgent     DEBUG   Resetting recommended pref browser.topsites.contile.enabled
1706650629195   RemoteAgent     DEBUG   Resetting recommended pref browser.usedOnWindows10.introURL
1706650629195   RemoteAgent     DEBUG   Resetting recommended pref browser.urlbar.merino.endpointURL
1706650629196   RemoteAgent     DEBUG   Resetting recommended pref browser.urlbar.suggest.searches
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref datareporting.policy.dataSubmissionPolicyAccepted
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref dom.disable_open_during_load
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref dom.file.createInChild
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref dom.input_events.security.minNumTicks
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref dom.input_events.security.minTimeElapsedInMS
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref dom.max_chrome_script_run_time
1706650629197   RemoteAgent     DEBUG   Resetting recommended pref dom.max_script_run_time
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref dom.navigation.locationChangeRateLimit.count
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref dom.push.connection.enabled
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref dom.screenorientation.allow-lock
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref dom.successive_dialog_time_limit
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.getAddons.cache.enabled
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.getAddons.discovery.api_url
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.blocklist.detailsURL
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.blocklist.itemURL
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.hotfix.url
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.systemAddon.update.url
1706650629198   RemoteAgent     DEBUG   Resetting recommended pref extensions.update.background.url
1706650629199   RemoteAgent     DEBUG   Resetting recommended pref extensions.update.url
1706650629199   RemoteAgent     DEBUG   Resetting recommended pref extensions.getAddons.get.url
1706650629199   RemoteAgent     DEBUG   Resetting recommended pref extensions.getAddons.search.browseURL
1706650629199   RemoteAgent     DEBUG   Resetting recommended pref geo.provider.network.url
1706650629199   RemoteAgent     DEBUG   Resetting recommended pref identity.fxaccounts.auth.uri
1706650629200   RemoteAgent     DEBUG   Resetting recommended pref network.connectivity-service.enabled
1706650629200   RemoteAgent     DEBUG   Resetting recommended pref network.http.phishy-userpass-length
1706650629200   RemoteAgent     DEBUG   Resetting recommended pref network.http.prompt-temp-redirect
1706650629201   RemoteAgent     DEBUG   Resetting recommended pref privacy.trackingprotection.enabled
1706650629201   RemoteAgent     DEBUG   Resetting recommended pref security.fileuri.strict_origin_policy
1706650629201   RemoteAgent     DEBUG   Resetting recommended pref security.notification_enable_delay
1706650629201   RemoteAgent     DEBUG   Resetting recommended pref security.remote_settings.intermediates.enabled
1706650629201   RemoteAgent     DEBUG   Resetting recommended pref signon.autofillForms
1706650629202   RemoteAgent     DEBUG   Resetting recommended pref signon.rememberSignons
1706650629202   RemoteAgent     DEBUG   Resetting recommended pref toolkit.telemetry.server
1706650629202   RemoteAgent     DEBUG   Resetting recommended pref widget.windows.window_occlusion_tracking.enabled
1706650629202   RemoteAgent     DEBUG   Resetting recommended pref dom.disable_beforeunload
1706650629203   Marionette      DEBUG   Marionette stopped listening
1706650629203   Marionette      DEBUG   0 <- [1,3,null,{"cause":"shutdown","forced":false,"in_app":true}]
1706650629434   webdriver::server       DEBUG   Teardown session
1706650629494   Marionette      DEBUG   Closed connection 0
1706650629845   geckodriver::browser    DEBUG   Browser process stopped: exit status: 0
1706650629889   webdriver::server       DEBUG   <- 200 OK {"value":null}
whimboo commented 5 months ago

Thanks @titusfortner! @ozerkon would you mind checking if that solution works for you?

titusfortner commented 5 months ago

Selenium is working on improving how this logging can be done in the dotnet service class, but it isn't an issue with Firefox explicitly.

ozerkon commented 4 months ago

Thanks @titusfortner! @ozerkon would you mind checking if that solution works for you?

First of all, I apologize for the late reply. Here is the test result:

Determining projects to restore...
  All projects are up-to-date for restore.
  TestProject -> C:\Users\ozerk\iCloudDrive\PROJECTS\DYS\TestProject\bin\Debug\net8.0\TestProject.dll
Test run for C:\Users\ozerk\iCloudDrive\PROJECTS\DYS\TestProject\bin\Debug\net8.0\TestProject.dll (.NETCoreApp,Version=v8.0)
Microsoft (R) Test Execution Command Line Tool Version 17.8.0 (x64)
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.

Passed!  - Failed:     0, Passed:     1, Skipped:     0, Total:     1, Duration: 8 s - TestProject.dll (net8.0)
PS C:\Users\ozerk\iCloudDrive\PROJECTS\DYS> dotnet test --filter FirefoxLogging
  Determining projects to restore...
  All projects are up-to-date for restore.
  TestProject -> C:\Users\ozerk\iCloudDrive\PROJECTS\DYS\TestProject\bin\Debug\net8.0\TestProject.dll
Test run for C:\Users\ozerk\iCloudDrive\PROJECTS\DYS\TestProject\bin\Debug\net8.0\TestProject.dll (.NETCoreApp,Version=v8.0)
Microsoft (R) Test Execution Command Line Tool Version 17.8.0 (x64)
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.

Passed!  - Failed:     0, Passed:     1, Skipped:     0, Total:     1, Duration: 7 s - TestProject.dll (net8.0)
whimboo commented 4 months ago

@ozerkon I'm not sure how to ready / parse your reply. Does it mean that the test, which was failing before, now passes? I don't see a failure in the listed output.

If not then I really need the geckodriver trace logs for further investigations.

gerbernoah commented 3 months ago

Hello, I just stumpled into the same error in JS (geckodriver and firefox aswell). In my code this happens after await driver.close().

If i put an "await delay(0)" in front of it. it works somehow. my stacktrace is:

Error [NoSuchWindowError]: Browsing context has been discarded at Object.throwDecodedError (C:\Users\noahg\Code\twittery\node_modules\.pnpm\selenium-webdriver@4.18.1\node_modules\selenium-webdriver\lib\error.js:521:15) at parseHttpResponse (C:\Users\noahg\Code\twittery\node_modules\.pnpm\selenium-webdriver@4.18.1\node_modules\selenium-webdriver\lib\http.js:510:13) at Executor.execute (C:\Users\noahg\Code\twittery\node_modules\.pnpm\selenium-webdriver@4.18.1\node_modules\selenium-webdriver\lib\http.js:443:28) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Driver.execute (C:\Users\noahg\Code\twittery\node_modules\.pnpm\selenium-webdriver@4.18.1\node_modules\selenium-webdriver\lib\webdriver.js:740:17) Emitted 'error' event on Worker instance at: at [kOnErrorMessage] (node:internal/worker:300:10) at [kOnMessage] (node:internal/worker:311:37) at MessagePort.<anonymous> (node:internal/worker:212:57) at [nodejs.internal.kHybridDispatch] (node:internal/event_target:741:20) at exports.emitMessage (node:internal/per_context/messageport:23:28) { remoteStacktrace: 'RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8\n' + 'WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:191:5\n' + 'NoSuchWindowError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:662:5\n' + 'assert.that/<@chrome://remote/content/shared/webdriver/Assert.sys.mjs:485:13\n' + 'assert.open@chrome://remote/content/shared/webdriver/Assert.sys.mjs:147:4\n' + 'GeckoDriver.prototype.clickElement@chrome://remote/content/marionette/driver.sys.mjs:1718:39\n' + 'despatch@chrome://remote/content/marionette/server.sys.mjs:318:40\n' + 'execute@chrome://remote/content/marionette/server.sys.mjs:289:16\n' + 'onPacket/<@chrome://remote/content/marionette/server.sys.mjs:262:20\n' + 'onPacket@chrome://remote/content/marionette/server.sys.mjs:263:9\n' + '_onJSONObjectReady/<@chrome://remote/content/marionette/transport.sys.mjs:494:20\n' }

The important lines are this:

`for (let i: number = 0; i < all_chats.length; i++) { const inboxLog = 'Chat [' + (i + 1) + '/' + all_chats.length + ']';

const membersLink = await all_chats[i].getAttribute('href');

let chatLink;
if (membersLink) {
  chatLink = membersLink.replace('/participants', '');
} else {
  logging.error(inboxLog + ' - Link not found - Skipped chat.');
  continue;
}

if (chatLink in processedChatLinks) {
  logging.warning(inboxLog + ' - Already checked - Skipped chat.');
  continue;
}

await driver.switchTo().newWindow('tab');
await driver.get(chatLink);

processedChatLinks.add(chatLink);
logging.info(inboxLog + ' - Processing.');

await processChat(
  driver,
  repostingEnabled,
  autoMessageEnabled,
  processedProfileLinks,
  inboxLog
);
await delay(0); //IMPORTANT - If removed... code crashes
await driver.close();
await driver.switchTo().window(inboxHandle);

}`

It happens in the 1. Iteration of the loop already.

I fixed this for me with the awayt delay(0). But maybe my stack trace helps you.

whimboo commented 3 months ago

@gerbernoah what is processChat() doing? As the Error shows this is related to clickElement. I assume you may miss an await for the call to Element click?

gerbernoah commented 3 months ago

Since this code is out of production I can provide it to you:

import { By, Key, Builder, Browser, WebDriver, WebElement } from 'selenium-webdriver';
import firefox from 'selenium-webdriver/firefox';
import { parentPort, isMainThread } from 'worker_threads';

if (isMainThread) {
  throw new Error('Bot running on main thread');
}

const autoMessageDistance = 3;

type Config = {
  token: string | null;
  username: string | null;
  password: string | null;
  phonenumber: string | null;
  verification: string | null;
  dropuser: string | null;
  running: boolean;
};

const config: Config = {
  token: null,
  username: null,
  password: null,
  phonenumber: null,
  verification: null,
  dropuser: null,
  running: false,
};

enum LogLevel {
  Info = 'Info',
  Warning = 'Warning',
  Error = 'Error',
}

export type Log = {
  message: string;
  level: {};
};

class Logging {
  info(message: string) {
    console.info(message);

    const log: Log = { message, level: LogLevel.Info };
    parentPort?.postMessage(JSON.stringify({ payload: 'log', data: log }));
  }

  warning(message: string) {
    console.warn(message);

    const log: Log = { message, level: LogLevel.Warning };
    parentPort?.postMessage(JSON.stringify({ payload: 'log', data: log }));
  }

  error(message: string) {
    console.error(message);

    const log: Log = { message, level: LogLevel.Error };
    parentPort?.postMessage(JSON.stringify({ payload: 'log', data: log }));
  }
}

const requestProperty = async (config: Config, propertyName: string, timeout: number): Promise<boolean> => {
  if (!config.running) {
    return false;
  }
  let property = config[propertyName as keyof Config];
  if (property) {
    logging.info(`${propertyName} already available.`);
    return true;
  }

  logging.info(`${propertyName} not available - Requesting.`);
  parentPort?.postMessage(JSON.stringify({ payload: 'request', data: propertyName }));

  let start = Date.now();
  while (true) {
    let property = config[propertyName as keyof Config];

    if (property) {
      logging.info(`${propertyName} available.`);
      return true;
    }

    if (!config.running) {
      return false;
    }

    if (Date.now() - start > timeout * 1000) {
      logging.error(`Waited ${timeout} seconds. No ${propertyName} provided. Terminating.`);
      return false;
    }

    await delay(5000);
  }
};
const click = async (element: WebElement | null): Promise<boolean> => {
  if (!element) {
    return false;
  }
  try {
    await element.click();
  } catch {
    return false;
  }
  return true;
};

const findOrNull = async (parent: WebElement | WebDriver, cssSelector: string): Promise<WebElement | null> => {
  let match: WebElement;
  try {
    match = await parent.findElement(By.css(cssSelector));
  } catch {
    return null;
  }
  return match;
};

const delay = (ms: number) => new Promise((res) => setTimeout(res, ms));

const defaultDelayTime = () => {
  return Math.random() * 1000 + 500;
};

const autoMessage = (): string => {
  return (
    '📌 HIT MY CLIENT! NOT ME! 📌\n' +
    '\n' +
    `@${config.dropuser} @${config.dropuser}\n` +
    `@${config.dropuser} @${config.dropuser}\n` +
    `@${config.dropuser} @${config.dropuser}\n` +
    '\n' +
    '✨PLEASE RETWEET! THANK YOU✨\n' +
    'ᴀᴅᴅ ᴍᴇ ᴛᴏ ᴀɴʏ 𝟷𝟶ᴋ + ɢɪғ ɢʀᴏᴜᴘ'
  );
};

const logging: Logging = new Logging();

parentPort?.on('message', (msg) => {
  const message = JSON.parse(msg);
  console.log(message);
  switch (message.payload) {
    case 'token': {
      config.token = message.data;
      break;
    }
    case 'username': {
      config.username = message.data;
      break;
    }
    case 'password': {
      config.password = message.data;
      break;
    }
    case 'phonenumber': {
      config.phonenumber = message.data;
      break;
    }
    case 'verification': {
      config.verification = message.data;
      break;
    }
    case 'mentioned-user': {
      config.dropuser = message.data;
      break;
    }
    case 'command': {
      switch (message.data) {
        case 'start': {
          config.running = true;
          twitterBot();
          break;
        }
        case 'stop': {
          logging.info('Init shuttdown.');
          config.running = false;
          break;
        }
      }
    }
  }
});

const setupDriver = async () => {
  const options = new firefox.Options();
  options.addArguments('--width=2560');
  options.addArguments('--height=1440');
  options.addArguments('--headless');

  const driver = await new Builder().forBrowser(Browser.FIREFOX).setFirefoxOptions(options).build();
  await driver.manage().setTimeouts({ implicit: 4000 });

  return driver;
};

const twitterBot = async () => {
  logging.info('Starting bot.');
  let driver;
  try {
    driver = await setupDriver();

    await driver.get('https://twitter.com/messages');

    if (!(await login(driver))) {
      logging.error('Log in failed. Terminating.');
      return;
    }

    if (!(await requestProperty(config, 'dropuser', 600))) {
      config.dropuser = 'DeesNetwork';
    }

    const allow_cookies = await findOrNull(driver, "div[data-testid='BottomBar'] div[role='button']");

    await delay(defaultDelayTime());
    if (await click(allow_cookies)) {
      logging.info('Accepted cookies.');
    } else {
      logging.info('No cookies to accept.');
    }

    let msgAndRepostTime: number = 0;
    let repostTime: number = 0;
    let firstRun = true;

    while (config.running) {
      let currentTtime: number = Date.now();
      let autoMessageEnabled = false;
      let repostingEnabled = false;

      if (firstRun || currentTtime - msgAndRepostTime > 120000) {
        autoMessageEnabled = true;
        repostingEnabled = true;
        msgAndRepostTime = Date.now();
      } else if (currentTtime - repostTime) {
        repostingEnabled = true;
        repostTime = Date.now();
      }

      logging.info(`Starting ${repostingEnabled ? 'reposting' : ''} ${autoMessageEnabled ? 'and drop' : ''}.`);

      await processInbox(driver, repostingEnabled, autoMessageEnabled);

      logging.info(`Finished ${repostingEnabled ? 'reposting' : ''} ${autoMessageEnabled ? 'and drop' : ''}.`);

      firstRun = false;
    }
    logging.info('Terminated!');
  } catch (e) {
    logging.error('Terminated due to error!');
    console.log(e);
    config.running = false;
  } finally {
    await driver?.quit();
  }
};

const login = async (driver: WebDriver): Promise<boolean> => {
  let tokenLogin = false;

  if (config.token) {
    if (config.token) {
      logging.info('Logging in with token.');
      await driver.manage().addCookie({ name: 'auth_token', value: config.token });
      await driver.get('https://twitter.com/messages');

      tokenLogin = !(await findOrNull(driver, "div[data-testid='confirmationSheetConfirm']"));

      if (tokenLogin) {
        logging.info('Logging in with token - Succesfull.');
        return true;
      } else {
        logging.warning('Logging in with token - Failed.');
      }
    }
  }

  let delayMultiplier = 2;
  let loginTry = 1;
  const maxLoginTries = 5;

  while (!(await findOrNull(driver, "a[data-testid='AppTabBar_Home_Link']"))) {
    if (loginTry > maxLoginTries) {
      logging.error('Logging in failed - Terminating.');
      return false;
    } else {
      if (loginTry > 1) {
        logging.warning(`Log in failed - Retrying.`);
      }
      logging.info(`Logging in [${loginTry} / ${maxLoginTries}].`);
    }

    logging.info('Logging in with credentials.');

    const confirmError = await findOrNull(driver, "div[data-testid='confirmationSheetConfirm']");
    if (confirmError) {
      await driver.manage().deleteAllCookies();
      await delay(defaultDelayTime() * delayMultiplier);
      await driver.get('https://twitter.com/messages');
    }

    const usernameInput = await findOrNull(driver, "input[autocomplete='username']");
    if (usernameInput) {
      logging.info('Filling in username.');

      if (!(await requestProperty(config, 'username', 600))) {
        return false;
      }

      logging.info(`Using username [${config.username}]`);

      await delay(defaultDelayTime() * delayMultiplier);
      await usernameInput.sendKeys(config.username!);
      await usernameInput.sendKeys(Key.ENTER);
    }

    const passwordInput = await findOrNull(driver, "input[autocomplete='current-password']");
    if (passwordInput) {
      logging.info('Filling in password.');

      if (!(await requestProperty(config, 'password', 600))) {
        return false;
      }

      logging.info(`Using password [${config.password}]`);

      await delay(defaultDelayTime() * delayMultiplier);
      await passwordInput.sendKeys(config.password!);
      await passwordInput.sendKeys(Key.ENTER);
    }

    const verificationInput = await findOrNull(driver, "input[data-testid='ocfEnterTextTextInput'][autocomplete='on']");
    if (verificationInput) {
      logging.info('Filling in verification.');

      if (!(await requestProperty(config, 'verification', 600))) {
        return false;
      }

      logging.info(`Using verification [${config.verification}]`);

      await delay(defaultDelayTime() * delayMultiplier);
      await verificationInput.sendKeys(config.username!);
      await verificationInput.sendKeys(Key.ENTER);
    }

    const phoneInput = await findOrNull(driver, "input[autocomplete='tel']");
    if (phoneInput) {
      logging.info('Filling in phonenumber.');

      if (!(await requestProperty(config, 'phonenumber', 600))) {
        return false;
      }

      logging.info(`Using phonenumber [${config.phonenumber}]`);

      await delay(defaultDelayTime() * delayMultiplier);
      await phoneInput.sendKeys(config.phonenumber!);
      await phoneInput.sendKeys(Key.ENTER);
    }
    loginTry += 1;
  }

  logging.info('Log in succesfull.');
  return true;
};

const processInbox = async (driver: WebDriver, repostingEnabled: boolean, autoMessageEnabled: boolean) => {
  const inboxHandle = await driver.getWindowHandle();

  await driver.get('https://twitter.com/messages');
  await delay(defaultDelayTime());

  let all_chats = await driver.findElements(By.css("a[data-testid='DM_Conversation_Avatar']"));

  if (all_chats.length == 0) {
    logging.warning('No chats found. Trying to wait 2 minutes');
    await delay(60000 * 2);
    let all_chats = await driver.findElements(By.css("a[data-testid='DM_Conversation_Avatar']"));

    if (all_chats.length == 0) {
      logging.error('No chats found. Restarting');
      return;
    }
  }

  const processedChatLinks = new Set<string>();
  const processedProfileLinks = new Set<string>();

  for (let i: number = 0; i < all_chats.length; i++) {
    const inboxLog = `Chat [${i + 1}/${all_chats.length}]`;

    const membersLink = await all_chats[i].getAttribute('href');

    let chatLink;
    if (membersLink) {
      chatLink = membersLink.replace('/participants', '');
    } else {
      logging.error(`${inboxLog} - Link not found - Skipped chat.`);
      continue;
    }

    if (processedChatLinks.has(chatLink)) {
      logging.error(`${inboxLog} - Already checked - Skipped chat.`);
      continue;
    }

    await delay(defaultDelayTime());
    await driver.switchTo().newWindow('tab');
    await driver.get(chatLink);
    await delay(defaultDelayTime());

    processedChatLinks.add(chatLink);
    logging.info(`${inboxLog} - Processing.`);

    await processChat(driver, repostingEnabled, autoMessageEnabled, processedProfileLinks, inboxLog);

    await delay(defaultDelayTime());
    await delay(0); //IMPORTANT - If removed... code crashes (Error [NoSuchWindowError]: Browsing context has been discarded)
    await driver.close();
    await driver.switchTo().window(inboxHandle);
    await delay(defaultDelayTime());

    if (!config.running) break;
  }
};

const processChat = async (
  driver: WebDriver,
  repostingEnabled: boolean,
  autoMessageEnabled: boolean,
  processedProfileLinks: Set<string>,
  inboxLog: string
) => {
  const chatHandle = await driver.getWindowHandle();

  const scrollDownButton = await findOrNull(driver, "div[data-testid='DmScrollToNewestButton'] div[role='button']");

  await delay(defaultDelayTime());

  if (await click(scrollDownButton)) {
    logging.info(`${inboxLog} - Scrolled down.`);
  } else {
    logging.info(`${inboxLog} - Can not scroll down.`);
  }

  if (autoMessageEnabled && (await checkAutoMessage(driver, inboxLog))) {
    logging.info(
      `${inboxLog} - No own message within last [${autoMessageDistance}] messages - Performing auto message.`
    );

    await performAutoMessage(driver, inboxLog);
  }

  logging.info(`${inboxLog} - Drop done.`);

  if (repostingEnabled) {
    const allForeignUserLinks = await driver.findElements(
      By.css("div[data-testid='messageEntry'] div[data-testid='UserAvatar-Container-unknown'] a") //could get linkElement directly here and iter over link elems
    );

    if (allForeignUserLinks.length == 0) {
      logging.warning(`${inboxLog} - No foreign user link found.`);
      return;
    }

    const foreignUserLinksToCheck = allForeignUserLinks.slice(-3);

    for (let i = 0; i < foreignUserLinksToCheck.length; i++) {
      const chatLog = `${inboxLog} - Message [${i + 1}/${foreignUserLinksToCheck.length}]`;

      let profileLink;
      try {
        profileLink = await foreignUserLinksToCheck[i].getAttribute('href');
      } catch {
        profileLink = null;
      }

      if (!profileLink) {
        logging.error(`${inboxLog} - No attribute href found in profile link.`);
        continue;
      }

      if (processedProfileLinks.has(profileLink)) {
        logging.info(`${chatLog} - Profile already checked - Skipping profile.`);
        continue;
      }

      await delay(defaultDelayTime());
      await driver.switchTo().newWindow('tab');
      await driver.get(profileLink);
      await delay(defaultDelayTime());

      processedProfileLinks.add(profileLink);
      logging.info(`${chatLog} - Processing.`);

      await processProfile(driver, chatLog);

      await delay(defaultDelayTime());
      await delay(0); //IMPORTANT - If removed... code crashes (Error [NoSuchWindowError]: Browsing context has been discarded)
      await driver.close();
      await driver.switchTo().window(chatHandle);
      await delay(defaultDelayTime());

      if (!config.running) break;
    }
  }
  logging.info(`${inboxLog} - Reposting done.`);
};

const checkAutoMessage = async (driver: WebDriver, inboxLog: string): Promise<boolean> => {
  const allMessages = await driver.findElements(By.css("div[data-testid='messageEntry']"));
  const messagesToCheck = allMessages.slice(-autoMessageDistance);

  for (let i: number = 0; i < messagesToCheck.length; i++) {
    const chatLog = `${inboxLog} - Message [${i + 1}/${messagesToCheck.length}]`;

    if (!(await findOrNull(allMessages[i], "[data-testid='UserAvatar-Container-unknown']"))) {
      logging.info(`${chatLog} - is own message - Skipping auto message.`);
      return false;
    }
  }

  return true;
};

const performAutoMessage = async (driver: WebDriver, inboxLog: string) => {
  const textInputField = await findOrNull(driver, "div[data-testid='dmComposerTextInput']");

  if (!textInputField) {
    logging.error(`${inboxLog} - Could not find text input field.`);
    return;
  }

  await delay(defaultDelayTime());
  for (let line of autoMessage().split('\n')) {
    await textInputField.sendKeys(line);
    await textInputField.sendKeys(Key.SHIFT, Key.ENTER);
  }

  await textInputField.sendKeys(Key.ENTER);
};

let failedRetweets = 0;
const maxFailedRetweets = 5;
const processProfile = async (driver: WebDriver, chatLog: string) => {
  const retweetButtons = await driver.findElements(By.css("article[data-testid='tweet'] div[data-testid='retweet']"));
  const retweetButtonsToCheck = retweetButtons.slice(0, 1);

  for (let i = 0; i < retweetButtonsToCheck.length; i++) {
    const profielLog = `${chatLog} - Tweet [${i + 1}/${retweetButtonsToCheck.length}]`;
    let tweetFailed = false;

    await delay(defaultDelayTime());
    if (!(await click(retweetButtonsToCheck[i]), driver)) {
      logging.error(`${profielLog} - Error retweeting tweet - Skipping tweet.`);
      tweetFailed = true;
    }

    if (!tweetFailed) {
      const retweetConfirmButton = await findOrNull(driver, "div[data-testid='retweetConfirm']");

      await delay(defaultDelayTime());
      if (!(await click(retweetConfirmButton))) {
        logging.error(`${profielLog} - Error confirming retweeting - Skipping tweet.`);
        tweetFailed = true;
      }
    }

    if (!tweetFailed) {
      let testid: string;
      try {
        testid = await retweetButtonsToCheck[i].getAttribute('data-testid');

        if (testid == 'unretweet') {
          logging.info(`${profielLog} - Successfully retweeted.`);
        } else {
          logging.error(`${profielLog} - Cannot confirm retweet.`);
          tweetFailed = true;
        }
      } catch {
        logging.error(`${profielLog} - Could not find retweet/unretweet button - Skipping confirmation.`);
        tweetFailed = true;
      }
    }

    if (tweetFailed) {
      failedRetweets += 1;

      if (failedRetweets < maxFailedRetweets) {
        logging.warning(
          `${profielLog} - [${failedRetweets}/${maxFailedRetweets}] unconfirmed retweets - Skipping profile.`
        );
        return;
      } else {
        logging.error(
          `${profielLog} - [${failedRetweets}/${maxFailedRetweets}] unconfirmed retweets - Waiting 10 minutes.`
        );
        failedRetweets = 0;
        await delay(60000 * 10);
        return;
      }
    } else {
      failedRetweets = 0;
    }

    if (!config.running) break;
  }
};

For us this bug isn't a thing anymore. If it helps you feel free to look at the code. Not for commercial use tho