Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# 1.3.3

Released on Tuesday, November 17 2026.

- Fixed `XMLHttpRequest` changing its `readyState` before the `readystatechange` of the previous state was fired

# 1.3.2

Released on Friday, November 13 2026.
Expand Down
2 changes: 1 addition & 1 deletion src/AngleSharp.Io.Docs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anglesharp/io",
"version": "1.3.2",
"version": "1.3.3",
"preview": true,
"description": "The doclet for the AngleSharp.Io documentation.",
"keywords": [
Expand Down
80 changes: 78 additions & 2 deletions src/AngleSharp.Io.Tests/Dom/ProgressEventTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,39 @@ public async Task SuccessfulRequestFiresProgressEventsInSpecOrder()
recorder.Names);
}

[Test]
public async Task ReadyStateChangesWithTheEventsOfAQueuingEventLoop()
{
var response = CreateResponse("https://api.example.test/data", "hello world", HttpStatusCode.OK);
var loader = new TestDocumentLoader(request => new TestDownload(request.Target, Task.FromResult<IResponse>(response)));
var loop = new QueuingEventLoop();
var xhr = await CreateRequesterAsync(loader, loop).ConfigureAwait(false);
var recorder = new EventRecorder(xhr);

xhr.Open("GET", "https://api.example.test/data");
xhr.Send();

// the response arrives completely before the loop runs any of its tasks
await Task.Delay(200).ConfigureAwait(false);
Assert.AreEqual(RequesterState.Opened, xhr.ReadyState);
loop.RunQueued();
await recorder.WaitForLoadEnd().ConfigureAwait(false);

CollectionAssert.AreEqual(
new[]
{
"readystatechange:1",
"loadstart",
"readystatechange:2",
"readystatechange:3",
"progress",
"readystatechange:4",
"load",
"loadend",
},
recorder.Names);
}

[Test]
public async Task LoadEventCarriesLoadedAndTotalFromContentLength()
{
Expand Down Expand Up @@ -294,11 +327,11 @@ public async Task RequestWithoutBodyFiresNoUploadEvents()

#region Helpers

private static async Task<XmlHttpRequest> CreateRequesterAsync(IDocumentLoader loader)
private static async Task<XmlHttpRequest> CreateRequesterAsync(IDocumentLoader loader, IEventLoop loop = null)
{
var config = Configuration.Default
.WithOnly<IDocumentLoader>(_ => loader)
.WithOnly<IEventLoop>(_ => new ImmediateEventLoop());
.WithOnly<IEventLoop>(_ => loop ?? new ImmediateEventLoop());

var context = BrowsingContext.New(config);
var document = await context.OpenAsync(req => req.Address("https://origin.example.test/").Content("<!doctype html>")).ConfigureAwait(false);
Expand Down Expand Up @@ -558,6 +591,49 @@ public void Spin()
}
}

private sealed class QueuingEventLoop : IEventLoop
{
private readonly Queue<Action<CancellationToken>> _queue = new Queue<Action<CancellationToken>>();

public ICancellable Enqueue(Action<CancellationToken> action, TaskPriority priority)
{
lock (_queue)
{
_queue.Enqueue(action);
}

return new CompletedCancellable();
}

public void RunQueued()
{
while (true)
{
Action<CancellationToken> action;

lock (_queue)
{
if (_queue.Count == 0)
{
return;
}

action = _queue.Dequeue();
}

action(CancellationToken.None);
}
}

public void CancelAll()
{
}

public void Spin()
{
}
}

private sealed class CompletedCancellable : ICancellable
{
public Boolean IsCompleted => true;
Expand Down
36 changes: 31 additions & 5 deletions src/AngleSharp.Io/Dom/XmlHttpRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,31 @@ private set
}
}

/// <summary>
/// Changes the state as the response arrives: in the task that tells the script about it,
/// so that each readystatechange listener sees the state it is fired for (with the changes
/// made right away, a listener of headers received already saw the request done, and a
/// script loading something on readyState 4 loaded it four times, e.g. Lottie's animations).
/// </summary>
private void ChangeReadyState(RequesterState value)
{
if (!_async || GetEventLoop() is null)
{
ReadyState = value;
return;
}

Enqueue(() =>
{
// an abort meanwhile is the last change
if (!_aborted)
{
_readyState = value;
Dispatch(new Event(ReadyStateChangeEvent));
}
});
}

/// <summary>
/// Gets or sets the timeout of the request in milliseconds.
/// </summary>
Expand Down Expand Up @@ -187,7 +212,8 @@ public Boolean WithCredentials
[DomName("abort")]
public void Abort()
{
if (_readyState == RequesterState.HeadersReceived || _readyState == RequesterState.Loading)
// a response may be on its way already, which the script does not know of yet
if (_readyState == RequesterState.HeadersReceived || _readyState == RequesterState.Loading || (_readyState == RequesterState.Opened && _download != null))
{
_aborted = true;
_download?.Cancel();
Expand Down Expand Up @@ -390,13 +416,13 @@ private async Task Receive(IDocumentLoader loader, DocumentRequest request)

_responseUrl = response.Address.Href;
_responseStatus = response.StatusCode;
ReadyState = RequesterState.HeadersReceived;
ChangeReadyState(RequesterState.HeadersReceived);
await ReadBody(response.Content).ConfigureAwait(false);

if (!_aborted)
{
FinishUpload(LoadEvent);
ReadyState = RequesterState.Done;
ChangeReadyState(RequesterState.Done);
FireProgress(LoadEvent);
FireProgress(LoadEndEvent);
}
Expand All @@ -420,7 +446,7 @@ private async Task Receive(IDocumentLoader loader, DocumentRequest request)
private async Task ReadBody(Stream content)
{
SetResponseTotal();
ReadyState = RequesterState.Loading;
ChangeReadyState(RequesterState.Loading);

var encoding = GetResponseEncoding();
var decoder = encoding.GetDecoder();
Expand Down Expand Up @@ -478,7 +504,7 @@ private void Fail(String eventName)
if (!_aborted)
{
FinishUpload(eventName);
ReadyState = RequesterState.Done;
ChangeReadyState(RequesterState.Done);
FireProgress(eventName);
FireProgress(LoadEndEvent);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Providers additional requesters and IO helpers for AngleSharp.</Description>
<Product>AngleSharp.Io</Product>
<Version>1.3.2</Version>
<Version>1.3.3</Version>
<LangVersion>latest</LangVersion>
<SignAssembly>true</SignAssembly>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Expand Down
Loading