Skip to content

Commit 52b9a03

Browse files
authored
Gracefully handle multiple contexts for secondary DOM World (#1102)
* Gracefully handle multiple contexts for secondary DOM World * Fix HasContext property
1 parent d485d03 commit 52b9a03

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

lib/PuppeteerSharp.Tests/PuppeteerTests/PuppeteerConnectTests.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,31 @@ public async Task ShouldBeAbleToReconnectToADisconnectedBrowser()
9595
}
9696
}
9797

98+
[Fact]
99+
public async Task ShouldBeAbleToConnectToTheSamePageSimultaneously()
100+
{
101+
var browserOne = await Puppeteer.LaunchAsync(new LaunchOptions());
102+
var browserTwo = await Puppeteer.ConnectAsync(new ConnectOptions
103+
{
104+
BrowserWSEndpoint = browserOne.WebSocketEndpoint
105+
});
106+
var tcs = new TaskCompletionSource<Page>();
107+
async void TargetCreated(object sender, TargetChangedArgs e)
108+
{
109+
tcs.TrySetResult(await e.Target.PageAsync());
110+
browserOne.TargetCreated -= TargetCreated;
111+
}
112+
browserOne.TargetCreated += TargetCreated;
113+
var page2Task = browserOne.NewPageAsync();
114+
115+
await Task.WhenAll(tcs.Task, page2Task);
116+
var page1 = tcs.Task.Result;
117+
var page2 = page2Task.Result;
118+
119+
Assert.Equal(56, await page1.EvaluateExpressionAsync<int>("7 * 8"));
120+
Assert.Equal(42, await page1.EvaluateExpressionAsync<int>("7 * 6"));
121+
await browserOne.CloseAsync();
122+
}
98123
[Fact]
99124
public async Task ShouldSupportCustomWebSocket()
100125
{

lib/PuppeteerSharp/DOMWorld.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ internal void SetContext(ExecutionContext context)
4747
}
4848
}
4949

50+
internal bool HasContext => _contextResolveTaskWrapper?.Task.IsCompleted == true;
51+
5052
internal void Detach()
5153
{
5254
_detached = true;

lib/PuppeteerSharp/FrameManager.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,8 +258,11 @@ private async Task OnExecutionContextCreatedAsync(ContextPayload contextPayload)
258258
{
259259
world = frame.MainWorld;
260260
}
261-
else if (contextPayload.Name == UtilityWorldName)
261+
else if (contextPayload.Name == UtilityWorldName && !frame.SecondaryWorld.HasContext)
262262
{
263+
// In case of multiple sessions to the same target, there's a race between
264+
// connections so we might end up creating multiple isolated worlds.
265+
// We can use either.
263266
world = frame.SecondaryWorld;
264267
}
265268
}

0 commit comments

Comments
 (0)