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

Released on tbd.

- 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()`
- Added the constants of the interfaces, e.g. `Node.ELEMENT_NODE`, `Range.START_TO_END` or `NodeFilter.SHOW_ELEMENT`

# 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);
}
}
}
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
4 changes: 3 additions & 1 deletion src/AngleSharp.Js/EngineInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,9 @@ private ObjectInstance CreateInstance(Object obj)

private ObjectInstance CreateInstance(Object obj, Type type)
{
var collection = type.GetIndexedCollection();
// A node indexed like a collection (a form, a select) is a node still: only the node's
// proxy holds its event handler attributes (form.onsubmit), and it asks the indexers too.
var collection = obj is INode ? null : type.GetIndexedCollection();

if (collection != null)
{
Expand Down
7 changes: 6 additions & 1 deletion src/AngleSharp.Js/Extensions/JsValueExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,13 @@ public static Object As(this JsValue value, Type targetType, EngineInstance engi
}
}

// a WebIDL integer (e.g. the "how" of compareBoundaryPoints): undefined or NaN is 0
var underlyingType = Enum.GetUnderlyingType(targetType);
var raw = Convert.ChangeType(TypeConverter.ToNumber(value), underlyingType);
var integer = TypeConverter.ToNumber(value);
var raw = underlyingType == typeof(Int32) ? TypeConverter.ToInt32(value) :
underlyingType == typeof(UInt32) ? TypeConverter.ToUint32(value) :
underlyingType == typeof(UInt16) ? TypeConverter.ToUint16(value) :
Convert.ChangeType(ToNumeric(integer, Type.GetTypeCode(underlyingType)), underlyingType);
return Enum.ToObject(targetType, raw);
}
else if (Nullable.GetUnderlyingType(targetType) is Type nullableType)
Expand Down
8 changes: 8 additions & 0 deletions src/AngleSharp.Js/JsScriptingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,14 @@ public Object EvaluateScript(IDocument document, String source, String type, Str

#region Helpers

/// <summary>
/// Gets the engine of the given window, if its document ran scripts already.
/// </summary>
internal static EngineInstance TryGetInstance(IWindow window) =>
window?.Document?.Context?.GetService<JsScriptingService>() is { } service && service._contexts.TryGetValue(window, out var instance)
? instance
: null;

internal EngineInstance GetOrCreateInstance(IDocument document)
{
var objectContext = document.DefaultView;
Expand Down
13 changes: 13 additions & 0 deletions src/AngleSharp.Js/Proxies/DomConstructorInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace AngleSharp.Js
using Jint.Runtime.Descriptors;
using Jint.Runtime.Interop;
using System;
using System.Collections.Generic;
using System.Reflection;

sealed class DomConstructorInstance : Constructor
Expand Down Expand Up @@ -40,6 +41,18 @@ public DomConstructorInstance(EngineInstance engine, ConstructorDefinition defin
SetOwnProperty("prototype", new PropertyDescriptor(_objectPrototype, false, false, false));

AddStaticMembers(definition.Type.GetStaticMembers());
AddConstants(engine.Libs.GetConstants(definition.Name));
}

private void AddConstants(IEnumerable<KeyValuePair<String, Double>> constants)
{
foreach (var constant in constants)
{
if (GetOwnProperty(constant.Key) == PropertyDescriptor.Undefined)
{
SetOwnProperty(constant.Key, new PropertyDescriptor(JsNumber.Create(constant.Value), false, true, false));
}
}
}

private void AddStaticMembers(StaticMember[] members)
Expand Down
13 changes: 9 additions & 4 deletions src/AngleSharp.Js/Proxies/DomNodeInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,16 @@ protected override OwnPropertyProbe ProbeOwnProperty(JsValue property)
/// </remarks>
private PropertyDescriptor GetGlobalProperty(JsValue property)
{
if (_value is IWindow)
if (_value is IWindow window)
{
var global = _instance.Jint.Global;

if (!ReferenceEquals(global, this))
// Another window (of the same origin, the others are wrapped) has its globals in the
// engine of its own document: a frame calling parent.notify() finds the function
// the parent declared.
var global = ReferenceEquals(_instance.Window?.Value, window)
? _instance.Jint.Global
: AngleSharp.Scripting.JsScriptingService.TryGetInstance(window)?.Jint.Global;

if (global != null && !ReferenceEquals(global, this))
{
return global.GetOwnProperty(property);
}
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.2</Version>
<Version>1.2.3</Version>
</PropertyGroup>

<PropertyGroup Label="Compilation">
Expand Down