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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# 1.2.2

Released on Sunday, November 15 2026.

- Added the `Audio` constructor (`new Audio(src)`)
- Added `window.event`, the event a listener or an event handler runs for, undefined otherwise

# 1.2.1

Released on Saturday, November 7 2026.
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ AngleSharp.Js contains code written by (in order of first pull request / commit)
* [Bogdan Maltcev](https://github.com/badnickname)
* [arekdygas](https://github.com/arekdygas)
* [Przemysław Kłys](https://github.com/PrzemyslawKlys)
* [Michael Thyregod](https://github.com/michaelthyregod)

Without these awesome people AngleSharp.Js could not exist. Thanks to everyone for your contributions! :beers:

Expand Down
2 changes: 1 addition & 1 deletion src/AngleSharp.Js.Docs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anglesharp/js",
"version": "1.2.1",
"version": "1.2.2",
"preview": true,
"description": "The doclet for the AngleSharp.Js documentation.",
"keywords": [
Expand Down
14 changes: 14 additions & 0 deletions src/AngleSharp.Js.Tests/InstanceOfTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,20 @@ public async Task ImageIsAnInstanceOfHtmlImageElement()
Assert.AreEqual("True", result);
}

[Test]
public async Task AudioIsAnInstanceOfHtmlAudioElement()
{
var result = await "new Audio() instanceof HTMLAudioElement".EvalScriptAsync();
Assert.AreEqual("True", result);
}

[Test]
public async Task AudioGetsItsSourceAndPreloads()
{
var result = await "(function (a) { return a.getAttribute('src') + ' ' + a.preload; })(new Audio('sound.mp3'))".EvalScriptAsync();
Assert.AreEqual("sound.mp3 auto", result);
}

// A DOM constructor is a function, so it inherits from Function.prototype.

[Test]
Expand Down
70 changes: 70 additions & 0 deletions src/AngleSharp.Js.Tests/WindowEventTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
namespace AngleSharp.Js.Tests
{
using NUnit.Framework;
using System;
using System.Threading.Tasks;

/// <summary>
/// window.event is the event a listener runs for, and undefined otherwise - a script reading
/// the global event outside of a listener (Elementor's carousels) threw a ReferenceError.
/// </summary>
[TestFixture]
public class WindowEventTests
{
[Test]
public async Task EventIsUndefinedOutsideOfListeners()
{
var document = await OpenAsync();

Assert.AreEqual("undefined", document.ExecuteScript("typeof event"));
Assert.AreEqual("undefined", document.ExecuteScript("typeof window.event"));
Assert.AreEqual("true", document.ExecuteScript("'event' in window").ToString().ToLowerInvariant());
}

[Test]
public async Task EventIsTheOneOfTheListenerRunning()
{
var document = await OpenAsync();

var result = document.ExecuteScript("""
var seen = [];
var p = document.querySelector('p');
p.addEventListener('click', function (e) {
seen.push(event === e, window.event === e);
p.dispatchEvent(new Event('inner'));
seen.push(event === e);
});
p.addEventListener('inner', function (e) { seen.push(event.type); });
p.dispatchEvent(new Event('click'));
seen.push(typeof event);
seen.join(',')
""");

Assert.AreEqual("true,true,inner,true,undefined", result);
}

[Test]
public async Task EventHandlersSeeTheEventToo()
{
var document = await OpenAsync("<p onclick=\"window.seen = window.event.type\">x</p>");

var result = document.ExecuteScript("document.querySelector('p').click(); window.seen");

Assert.AreEqual("click", result);
}

[Test]
public async Task EventCanBeReplacedByScript()
{
var document = await OpenAsync();

Assert.AreEqual("5", document.ExecuteScript("window.event = 5; window.event").ToString());
}

private static Task<AngleSharp.Dom.IDocument> OpenAsync(String body = "<p>x</p>")
{
var context = BrowsingContext.New(Configuration.Default.WithJs());
return context.OpenAsync(m => m.Content("<!doctype html>" + body));
}
}
}
20 changes: 20 additions & 0 deletions src/AngleSharp.Js/Dom/WindowExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,26 @@ public static IHtmlImageElement Image(this IWindow window, int? width = null, in
return imageElement;
}

/// <summary>
/// Creates a new IHtmlAudioElement instance, which preloads its source.
/// </summary>
/// <param name="window"></param>
/// <param name="src">The source of the audio, if any.</param>
/// <returns></returns>
[DomConstructorFunction("Audio")]
public static IHtmlAudioElement Audio(this IWindow window, String src = null)
{
var audioElement = window.Document.CreateElement(TagNames.Audio) as IHtmlAudioElement;
audioElement.Preload = "auto";

if (src != null)
{
audioElement.Source = src;
}

return audioElement;
}

private static IWindow GetWindow(IBrowsingContext context) => context?.Active?.DefaultView;
}
}
34 changes: 34 additions & 0 deletions src/AngleSharp.Js/EngineInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ sealed class EngineInstance
private JsValue _domException;
private JsValue _lastReportedError;
private Int32 _inlineModules;
private JsValue _currentEvent = JsValue.Undefined;
private readonly List<KeyValuePair<JsValue, JsValue>> _unhandledRejections = new List<KeyValuePair<JsValue, JsValue>>();

#endregion
Expand Down Expand Up @@ -128,6 +129,12 @@ public EngineInstance(IWindow window, IDictionary<String, Object> assignments, I

_engine.Global.Prototype = _window.Prototype;
_engine.Advanced.PromiseRejectionTracker += OnPromiseRejection;

// window.event is the event a listener runs for, undefined otherwise (HTML 7.2.2.3);
// scripts read it as a global, so a missing one throws (e.g. Elementor's carousels)
var currentEvent = CreateCurrentEventProperty();
_window.FastSetProperty("event", currentEvent);
_engine.Global.FastSetProperty("event", currentEvent);
}

#endregion
Expand Down Expand Up @@ -333,6 +340,33 @@ public Task<Object> RunCallback(Function function, Object receiver, Object[] arg
return completion.Task;
}

/// <summary>
/// Gets or sets the event the listener running now was called for (window.event), which
/// is undefined outside of listeners.
/// </summary>
public JsValue CurrentEvent
{
get => _currentEvent;
set => _currentEvent = value ?? JsValue.Undefined;
}

// [Replaceable]: script assigning the property replaces it with its value
private PropertyDescriptor CreateCurrentEventProperty() => new GetSetPropertyDescriptor(
new ClrFunction(_engine, "get event", (_, _) => _currentEvent),
new ClrFunction(_engine, "set event", (self, arguments) =>
{
var value = arguments.Length > 0 ? arguments[0] : JsValue.Undefined;

if (self is ObjectInstance target)
{
target.FastSetProperty("event", new PropertyDescriptor(value, true, true, true));
}

return JsValue.Undefined;
}),
false,
true);

/// <summary>
/// Tells that the host is about to run script, e.g. a timer or a listener.
/// </summary>
Expand Down
6 changes: 6 additions & 0 deletions src/AngleSharp.Js/Extensions/DomDelegates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,10 @@ private static DomEventHandler CreateListener(this Function function, EngineInst
{
var objAsJs = obj.ToJsValue(engine);
var evAsJs = ev.ToJsValue(engine);
var previous = engine.CurrentEvent;

engine.EnterScript();
engine.CurrentEvent = evAsJs;

try
{
Expand All @@ -137,6 +139,7 @@ private static DomEventHandler CreateListener(this Function function, EngineInst
}
finally
{
engine.CurrentEvent = previous;
engine.LeaveScript();
}
};
Expand All @@ -148,7 +151,9 @@ private static DomEventHandler CreateListener(this Function function, EngineInst
public static DomEventHandler ToEventHandler(this Function function, EngineInstance engine) => (obj, ev) =>
{
var sender = obj.ToJsValue(engine);
var previous = engine.CurrentEvent;
engine.EnterScript();
engine.CurrentEvent = ev.ToJsValue(engine);

try
{
Expand Down Expand Up @@ -185,6 +190,7 @@ public static DomEventHandler ToEventHandler(this Function function, EngineInsta
}
finally
{
engine.CurrentEvent = previous;
engine.LeaveScript();
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
entry of CHANGELOG.md, which build/Build.cs passes in as -p:Version, so this value only
affects a plain `dotnet build` and no longer needs bumping for a release. -->
<PropertyGroup Label="Versioning">
<Version>1.2.1</Version>
<Version>1.2.2</Version>
</PropertyGroup>

<PropertyGroup Label="Compilation">
Expand Down
Loading