From 8cd56ed2cf3b543fcc6d895932a6f13e6b9400fd Mon Sep 17 00:00:00 2001
From: Bjoern Esswein <692-bessw@users.noreply.gl.kwarc.info>
Date: Fri, 12 Jul 2024 21:52:15 +0200
Subject: [PATCH] fixed race condition in tab.getDocument by replacing it with
 an awaitable property

---
 Runtime/ChromeDevtools/BrowserTab.cs | 29 ++++++++++++++++------------
 1 file changed, 17 insertions(+), 12 deletions(-)

diff --git a/Runtime/ChromeDevtools/BrowserTab.cs b/Runtime/ChromeDevtools/BrowserTab.cs
index 4f0bbe5..5cc23db 100644
--- a/Runtime/ChromeDevtools/BrowserTab.cs
+++ b/Runtime/ChromeDevtools/BrowserTab.cs
@@ -25,7 +25,22 @@ namespace bessw.Unity.WebView.ChromeDevTools
 
         public Dictionary<int, DomNodeWrapper> domNodes = new Dictionary<int, DomNodeWrapper>();
 
-        private DomNodeWrapper document;
+        private Task<DomNodeWrapper> _document;
+        public Task<DomNodeWrapper> Document
+        {
+            get
+            {
+                if (_document is null)
+                {
+                    _document = DomNodeWrapper.getDocumentAsync(this);
+                    // unset _document on error, so it will be re-fetched on next access
+                    _document.ContinueWith(_ => _document = null, TaskContinuationOptions.NotOnRanToCompletion);
+                }
+                return _document;
+            }
+        }
+
+
         private Dictionary<string, Action<string>> runtimeBindings = new();
 
         public BrowserTab(PageTargetInfo pageTarget)
@@ -52,7 +67,7 @@ namespace bessw.Unity.WebView.ChromeDevTools
         {
             // clear the domNodes dictionary
             domNodes.Clear();
-            document = null;
+            _document = null;
         }
 
         public IEnumerator Update()
@@ -227,16 +242,6 @@ namespace bessw.Unity.WebView.ChromeDevTools
             _ = devtools.SendCommandAsync(new cancelDragging());
         }
 
-        /// <summary>
-        /// returns the cached document DomNodeWrapper or fetches it from the browser
-        /// </summary>
-        /// <returns></returns>
-        public async Task<DomNodeWrapper> GetDocument()
-        {
-            if (document is not null) return document;
-            else return await DomNodeWrapper.getDocumentAsync(this);
-        }
-
         /// <summary>
         /// returns the cached node if it exists, otherwise fetches it from the browser
         /// </summary>
-- 
GitLab