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

Released on Sunday, November 22 2026.

- Fixed `undefined` for an argument of an enumeration (e.g. the `how` of `compareBoundaryPoints`) throwing an error scripts could not catch
- Fixed event handler attributes of forms and selects (e.g. `form.onsubmit`) not being set
- Fixed a frame not finding the functions and variables of a script of another window, e.g. `parent.notify()`
- Fixed `adoptedStyleSheets` not being an array
- Added the constants of the interfaces, e.g. `Node.ELEMENT_NODE`, `Range.START_TO_END` or `NodeFilter.SHOW_ELEMENT`
- Added the callbacks of form-associated custom elements, e.g. `formResetCallback`

# 1.2.2

Released on Sunday, November 15 2026.
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.2",
"version": "1.2.3",
"preview": true,
"description": "The doclet for the AngleSharp.Js documentation.",
"keywords": [
Expand Down
62 changes: 62 additions & 0 deletions src/AngleSharp.Js.Tests/Acid3Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
namespace AngleSharp.Js.Tests
{
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using NUnit.Framework;
using System.Threading.Tasks;

/// <summary>
/// Behavior the Acid3 test (acid3.acidtests.org) relies on.
/// </summary>
[TestFixture]
public class Acid3Tests
{
[Test]
public async Task ConstantsAreOnTheInterfacesAndTheirInstances()
{
var result = await "[Node.ELEMENT_NODE, document.DOCUMENT_FRAGMENT_NODE, document.documentElement.TEXT_NODE, Range.START_TO_END, document.createRange().END_TO_START, Event.CAPTURING_PHASE, NodeFilter.SHOW_ELEMENT].join()".EvalScriptAsync();
Assert.AreEqual("1,11,3,1,3,1,1", result);
}

[Test]
public async Task ConstantsCannotBeChanged()
{
var result = await "(function () { Node.ELEMENT_NODE = 5; document.ELEMENT_NODE = 6; return [Node.ELEMENT_NODE, document.ELEMENT_NODE].join(); })()".EvalScriptAsync();
Assert.AreEqual("1,1", result);
}

[Test]
public async Task UndefinedForAnEnumerationArgumentIsZero()
{
var result = await "(function () { var r = document.createRange(); return r.compareBoundaryPoints(r.NO_SUCH_CONSTANT, r.cloneRange()); })()".EvalScriptAsync();
Assert.AreEqual("0", result);
}

[Test]
public async Task EventHandlerOfAFormIsNotANamedProperty()
{
var result = await "(function () { var f = document.createElement('form'); var n = 0; f.onsubmit = function () { n++; }; f.appendChild(document.createElement('input')); document.documentElement.appendChild(f); f.dispatchEvent(new Event('submit')); return [n, typeof f.onsubmit, f.length, f[0].tagName].join(); })()".EvalScriptAsync();
Assert.AreEqual("1,function,1,INPUT", result);
}

[Test]
public async Task FrameCallsAFunctionOfItsParent()
{
var config = Configuration.Default.WithJs().WithEventLoop();
var document = await BrowsingContext.New(config).OpenAsync(m => m.Content(@"<body><script>
function notify(value) { document.title = value; }
var f = document.createElement('iframe');
document.body.appendChild(f);
var d = f.contentDocument;
d.open();
d.write('<script>parent.notify(typeof parent.notify + \' from frame\')<\/script>');
d.close();
</script></body>"));
await document.WhenStable();
var frame = (IHtmlInlineFrameElement)document.QuerySelector("iframe");
await frame.ContentDocument.WhenStable();

Assert.AreEqual("function from frame", document.Title);
}
}
}
61 changes: 61 additions & 0 deletions src/AngleSharp.Js.Tests/ObservableArrayTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
namespace AngleSharp.Js.Tests
{
using AngleSharp.Attributes;
using AngleSharp.Dom;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

[DomExposed("Document")]
public static class ProbeObservableArrayExtensions
{
private static readonly ConditionalWeakTable<IDocument, List<IElement>> Lists = new ConditionalWeakTable<IDocument, List<IElement>>();

public static List<IElement> Of(IDocument document) => Lists.GetValue(document, _ => new List<IElement>());

[DomName("probeElements")]
[DomAccessor(Accessors.Getter)]
public static IList<IElement> GetProbeElements(this IDocument document) => Of(document);

[DomName("probeElements")]
[DomAccessor(Accessors.Setter)]
public static void SetProbeElements(this IDocument document, IEnumerable<IElement> elements)
{
var list = Of(document);
list.Clear();
list.AddRange(elements);
}
}

/// <summary>
/// A mutable IList of the DOM is a WebIDL ObservableArray (e.g. adoptedStyleSheets): an
/// array for scripts, whose changes go to the list.
/// </summary>
[TestFixture]
public class ObservableArrayTests
{
[TestCase("Array.isArray(document.probeElements)", "True")]
[TestCase("document.probeElements === document.probeElements", "True")]
[TestCase("document.probeElements = document.probeElements.concat([document.body]); document.probeElements[0] === document.body", "True")]
[TestCase("document.probeElements.push(document.body, document.head); document.probeElements.pop(); document.probeElements.length", "1")]
[TestCase("try { document.probeElements.push(1); 'none' } catch (e) { e.name }", "TypeError")]
public async Task MutableListIsAnArray(String script, String expected)
{
var document = await BrowsingContext.New(Configuration.Default.WithJs().With(new ProbeService())).OpenAsync(m => m.Content("<!doctype html><body>"));

Assert.AreEqual(expected, document.ExecuteScript(script)?.ToString());
}

[Test]
public async Task ChangesOfTheArrayGoToTheList()
{
var document = await BrowsingContext.New(Configuration.Default.WithJs().With(new ProbeService())).OpenAsync(m => m.Content("<!doctype html><body>"));

document.ExecuteScript("document.probeElements.push(document.body)");

Assert.AreEqual(new[] { document.Body }, ProbeObservableArrayExtensions.Of(document));
}
}
}
98 changes: 98 additions & 0 deletions src/AngleSharp.Js/Cache/ConstantCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
namespace AngleSharp.Js.Cache
{
using AngleSharp.Attributes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

/// <summary>
/// The WebIDL constants of the interfaces (e.g. Node.ELEMENT_NODE), which the libraries
/// declare as the fields of an enum named like the interface owning them.
/// </summary>
static class ConstantCache
{
private static readonly ConcurrentDictionary<Assembly, IReadOnlyDictionary<String, KeyValuePair<String, Double>[]>> _constants = new();

// Enums whose name doesn't say the interface owning their constants (AngleSharp 1.10 names
// the document for those of a node, which all nodes have).
private static readonly Dictionary<String, String> _owners = new(StringComparer.Ordinal)
{
{ "AngleSharp.Dom.NodeType", "Node" },
{ "AngleSharp.Dom.DocumentPositions", "Node" },
{ "AngleSharp.Dom.DomError", "DOMException" },
};

public static IEnumerable<KeyValuePair<String, Double>> GetConstants(this IEnumerable<Assembly> libs, String name)
{
if (name is null)
{
return [];
}

return libs
.Select(m => _constants.GetOrAdd(m, Collect))
.SelectMany(m => m.TryGetValue(name, out var constants) ? constants : []);
}

private static IReadOnlyDictionary<String, KeyValuePair<String, Double>[]> Collect(Assembly assembly)
{
var result = new Dictionary<String, List<KeyValuePair<String, Double>>>(StringComparer.Ordinal);

foreach (var type in GetTypes(assembly))
{
var info = type.GetTypeInfo();

if (!info.IsEnum || info.GetCustomAttribute<DomLiteralsAttribute>() != null)
{
continue;
}

var owner = _owners.TryGetValue(type.FullName ?? String.Empty, out var known) ? known :
info.GetCustomAttributes<DomNameAttribute>().FirstOrDefault()?.OfficialName;

if (owner is null)
{
continue;
}

foreach (var field in info.DeclaredFields.Where(m => m.IsLiteral))
{
var constant = field.GetCustomAttributes<DomNameAttribute>().FirstOrDefault()?.OfficialName;

if (constant is not null && IsConstantName(constant))
{
if (!result.TryGetValue(owner, out var list))
{
result[owner] = list = [];
}

if (!list.Any(m => m.Key == constant))
{
list.Add(new KeyValuePair<String, Double>(constant, Convert.ToDouble(field.GetRawConstantValue())));
}
}
}
}

return result.ToDictionary(m => m.Key, m => m.Value.ToArray(), StringComparer.Ordinal);
}

// constants are all upper case (the members of a string enumeration are not)
private static Boolean IsConstantName(String name) =>
name.Length > 0 && Char.IsUpper(name[0]) && name.All(c => Char.IsUpper(c) || Char.IsDigit(c) || c == '_');

private static IEnumerable<Type> GetTypes(Assembly assembly)
{
try
{
return assembly.ExportedTypes;
}
catch (Exception)
{
return [];
}
}
}
}
9 changes: 9 additions & 0 deletions src/AngleSharp.Js/Cache/DomShapeCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,15 @@ public DomShape Build(Engine engine)
}
}

// The constants are on the prototype as well, so that a node knows them (node.ELEMENT_NODE).
foreach (var constant in _libs.Assemblies.GetConstants(_name))
{
if (!_members.ContainsKey(constant.Key) && !String.Equals(constant.Key, ConstructorName, StringComparison.Ordinal))
{
builder.Constant(constant.Key, JsNumber.Create(constant.Value), true);
}
}

if (constructor != null)
{
// The attributes an eagerly written constructor had, and still resolved on first
Expand Down
6 changes: 6 additions & 0 deletions src/AngleSharp.Js/Cache/MethodCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ private MethodDescription(MethodBase method)
ReturnType = method.GetCustomAttribute<DomReturnTypeAttribute>()?.ReturnType;
TakesWindow = parameters.Length > 0 && parameters[0].ParameterType == typeof(IWindow);
GivenConversion = (method as MethodInfo)?.ReturnType.GetGivenConversion();
ObservableElementType = ObservableArrays.GetElementType((method as MethodInfo)?.ReturnType);
HasReceiver = TakesWindow || (method.IsStatic && method.IsDefined(typeof(ExtensionAttribute), false));
TakesParamArray = parameters.Length > 0 &&
parameters[parameters.Length - 1].GetCustomAttribute<ParamArrayAttribute>() != null;
Expand All @@ -52,6 +53,11 @@ public static MethodDescription Of(MethodBase method) =>

public Type ReturnType { get; }

/// <summary>
/// Gets the type of the items if the method returns a WebIDL ObservableArray, else null.
/// </summary>
public Type ObservableElementType { get; }

public Boolean TakesWindow { get; }

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/AngleSharp.Js/Dom/CustomElementHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static JsValue Get(this CustomElementRegistry registry, String name) =>
/// </summary>
sealed class CustomElementHost : ICustomElementHost
{
private static readonly String[] CallbackNames = { "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback" };
private static readonly String[] CallbackNames = { "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback", "formAssociatedCallback", "formResetCallback", "formDisabledCallback", "formStateRestoreCallback" };

private readonly JsScriptingService _service;

Expand Down
Loading