diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 10651afd..7d85a75e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,7 +55,7 @@ jobs: 10.0.x - name: Build - run: ./build.sh -AngleSharpVersion 1.8.0 + run: ./build.sh -AngleSharpVersion 1.10.0 windows: runs-on: windows-latest @@ -85,9 +85,9 @@ jobs: NUGET_API_KEY: ${{ steps.nuget_login.outputs.NUGET_API_KEY }} run: | if ($env:GITHUB_REF -eq "refs/heads/main") { - .\build.ps1 -Target Publish -AngleSharpVersion 1.8.0 + .\build.ps1 -Target Publish -AngleSharpVersion 1.10.0 } elseif ($env:GITHUB_REF -eq "refs/heads/devel") { - .\build.ps1 -Target PrePublish -AngleSharpVersion 1.8.0 + .\build.ps1 -Target PrePublish -AngleSharpVersion 1.10.0 } else { - .\build.ps1 -AngleSharpVersion 1.8.0 + .\build.ps1 -AngleSharpVersion 1.10.0 } diff --git a/AGENTS.md b/AGENTS.md index 907e0729..d586d395 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,6 +113,24 @@ values. `EngineExtensions.BuildArgs` maps JS arguments onto a CLR signature and DOM-specific cases: an implicit leading `IWindow` parameter, optional parameters, `params` arrays, and `[DomInitDict]` option objects expanded into positional arguments. +What a type's members become, as libraries rely on it: + +- Instance members marked with `[DomName]` go on the prototype. Several methods or + `[DomConstructor]`s of the same name within one type are overloads, picked per call by + `OverloadResolution`; a method further up the type tree is hidden instead. +- Static members go on the constructor object (`DomConstructorInstance`, cached per type by + `CreatorCache.GetStaticMembers`). Only `[DomExposed]` *extension methods* are added to the type + they extend, so a class can be exposed to the window without spilling members onto it. +- A class overriding `ToString` gets a `toString` on its prototype, as such classes are exactly the + WebIDL stringifiers. A new override on a DOM type is hence visible to scripts. +- Into the CLR: `Object` receives bytes for a BufferSource and the raw Jint value for other objects. + Sequences are arrays and the generic interfaces arrays implement, filled from any JS iterable. A + class with `implicit operator`s from several types is a WebIDL union, picked like overloads; going + back out, its `implicit operator` to another type gives what a script receives for it. +- Out of the CLR: `[DomLiterals]` enums are strings (other enums are numbers, and exposed as an object + of constants), `Byte[]` is a new `ArrayBuffer`, `ArraySegment` a new `Uint8Array`, other arrays are JS arrays, every numeric type is a + number, `IDictionary` is a plain object, and a `Task` is a promise. + ## Performance **Performance is a primary concern in this repository, not an afterthought.** Jint is an diff --git a/CHANGELOG.md b/CHANGELOG.md index a6b02875..bb42ac81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,73 @@ +# 1.2.0 + +Released on Friday, November 6 2026. + +- Fixed `window.origin` being `null` for a frame without an address of its own instead of the origin of its creator +- Fixed text given to `append`, `prepend` and the like failing instead of becoming a text node +- Fixed a class deriving from a type of the DOM not having its instances on its prototype chain +- Fixed an object with `handleEvent` not being accepted as an event listener, or one with `acceptNode` as a filter of a `TreeWalker` or `NodeIterator` +- Fixed a function not being accepted as a callback whose result is waited for, e.g. of `navigator.locks.request`: it runs on the event loop and is followed to its promise +- Fixed promise jobs not running after a timer, a listener or any other callback of the host: they waited for something else to run them, so `await` could hang +- Fixed a `DOMException` with a name having no code (e.g. `NotAllowedError`) being named `Error` for script +- Fixed a date from the DOM not being a `Date` for script, and bytes not surviving a structured clone +- Fixed a function not being accepted as a callback with a result, e.g. as a filter of a `TreeWalker` +- Fixed a worker that failed to start throwing from `postMessage` instead of firing an `error` event +- Fixed collections from attributes, e.g. `document.links` or `element.children`, not being iterable +- Fixed `classList` not being iterable and having no `forEach`, `entries`, `keys` and `values` +- Fixed a member of an options dictionary without a default becoming `undefined` in text +- Fixed members of the DOM being read-only and copied onto every prototype, so polyfills could neither replace them nor reach derived types (e.g. patching `Element.prototype.querySelector`): each is now on the prototype of the interface declaring it, as WebIDL says (writable, enumerable and configurable) +- Fixed interface objects of the window being read-only and enumerable: `window.Node = ...` now also changes `Node`, as WebIDL says +- Fixed bound functions and callable proxies not being accepted as callbacks (e.g. `setTimeout(f.bind(x))`, `addEventListener('click', f.bind(x))`, `requestAnimationFrame(f.bind(x))`, `onclick`), failing with `Could not find corresponding cast target` +- Fixed `removeEventListener` not removing listeners, as a function was turned into another listener each time +- Fixed errors of event listeners not reaching the `error` listeners of the window; an error thrown by such a listener goes to the browsing context +- Fixed the address of a script getting lost, so errors and stack traces named ``: they tell the resolved address of the script, or of the document for one written into it +- Fixed scripts written into a document telling lines and columns of their own in errors and stack traces instead of the ones in the document +- Fixed errors of scripts and of callbacks (e.g. timers, animation frames) not reaching the `error` listeners of the window; what they don't handle by `preventDefault` goes to the browsing context +- Fixed `onerror` of the window getting the event instead of the message, source, line, column and error, and returning `true` not handling the error +- Fixed `error` of an `ErrorEvent` being a .NET exception instead of what script threw +- Fixed an `onclick` and the like throwing taking down the process and skipping the other listeners, as it was not reported like a listener +- Fixed a `TypeError` or the like thrown for script by a member of the DOM becoming a plain `Error` +- Fixed modules being read from the local disk; every module is loaded through the configured requesters (#153) @michaelthyregod +- Fixed modules imported by a relative address being requested from the wrong address (e.g. `./a.js` of `/dir/page.html` from `/dir/page.html/a.js`, and the imports of a module of another origin from the own origin); they are resolved against what imports them (#153) @michaelthyregod +- Fixed modules being known by the path of their address, so errors didn't tell the whole address, and imports of an imported module were looked for from the wrong place +- Fixed a module written into a document telling lines and columns of its own, and importing from somewhere other than the base address of the document +- Fixed an error of a module being reported twice +- Fixed an event handler (e.g. `onclick`) returning `false` not cancelling the event +- Fixed an event handler attribute being added on top of the previous one when it changed, staying when it was removed, and throwing a syntax error at whoever set the attribute instead of reporting it +- Fixed only the first of several methods or constructors of the same name being callable (e.g. `new URLSearchParams('a=1')`, `register(url, options)`); the one fitting the arguments is called +- Fixed static members not being reachable (e.g. `DOMRect.fromRect`); they are on the constructor and may take the window as first parameter +- Fixed members of classes marked with `DomExposed` ending up on what they are exposed to (e.g. the members of a constructor on `window`); only extension methods do +- Fixed arrays and other iterables not converting to sequences (arrays and the interfaces they implement) +- Fixed `ArrayBuffer`, typed arrays, and `DataView` not converting to `Byte[]`, `ArraySegment`, and `Object` (e.g. a request body being sent as `[object Uint8Array]`) +- Fixed numbers not converting from and to `Int64`, `UInt64`, `Int16`, `Byte`, `SByte`, `Single` (only from), and `Decimal`, as well as nullable forms of all value types +- Fixed values of `DomLiterals` enums being numbers instead of strings (e.g. `shadowRoot.mode`), and such enums being exposed as objects +- Fixed `Byte[]` being given as an array of numbers instead of an `ArrayBuffer` +- Fixed errors thrown by constructors losing their message +- Fixed WebIDL stringifiers (`URL`, `URLSearchParams`, `Location`, `Range`, `DOMTokenList`, `DOMMatrix`) answering `String(x)` with `[object X]`; a type overriding `ToString` has a `toString` +- Fixed sandboxed browsing contexts without `allow-scripts` running scripts and event handler attributes +- Fixed `postMessage` ignoring `targetOrigin`, giving it as the origin of the event, turning objects into strings, and not having a `source`; messages are copied by the structured clone algorithm, and the options form is supported +- Added `clearResourceTimings` and `setResourceTimingBufferSize` to `performance` +- Added `{ type: 'module' }` and `onerror` to `Worker`, with imports being loaded by the worker +- Added `MessageChannel` with queued message delivery, structured cloning, and transferable ports for windows and workers +- Added `IScriptValueCloner`, so that values of script can be kept, e.g. by IndexedDB +- Added `structuredClone`, `origin`, `isSecureContext` and `length` to the window +- Added `DOMException`, which is what the DOM now throws for scripts: an `Error` with the `name` and `code` of the standard, also available as a constructor and with its constants +- Added `TextEncoder` and `TextDecoder` +- Added the iterator of a type giving `entries` (WebIDL `iterable`), so that e.g. `for (const [k, v] of new URLSearchParams(s))` works +- Added overloads brought by extensions for the methods of the DOM, as `addEventListener` with options has them +- Added `crypto` with `getRandomValues` and `randomUUID`, but without `subtle` +- Added `requestIdleCallback` and `cancelIdleCallback` +- Fixed `DOMParser` replacing the document of the page with what it parsed, and running its scripts +- Added `PerformanceObserver`, for the marks and measures of `performance` +- Added custom elements, run for the registry of AngleSharp: classes deriving from `HTMLElement` or another element, with their callbacks running when the call of a script returns (requires AngleSharp 1.10) +- Fixed classes deriving from a DOM type taking every object of that type for an instance of them +- Added what a promise rejects with being a `DOMException` or what was thrown, if the task behind it failed with one +- Added `import.meta.url` to modules; without it, e.g., webpack stopped with `Automatic publicPath is not supported in this browser` +- Added `ArraySegment` being given as a `Uint8Array` +- Added classes with implicit conversions standing for a WebIDL union, e.g. of a string and a sequence of strings, which fixes such conversions failing; an implicit conversion from such a class is what a script receives for it +- Added the same-origin policy: script gets `null` for a node of another origin, and for its window a `CrossOriginWindow` with only `window`, `self`, `frames`, `parent`, `top`, `closed`, `length`, `location` (only to be set, and only for frames inside the own document), `postMessage`, `focus`, `blur` and `close` +- Added `performance.mark`, `measure`, `getEntries`, `getEntriesByName`, `getEntriesByType`, `clearMarks`, `clearMeasures`, along with `PerformanceEntry`, `PerformanceMark` and `PerformanceMeasure` + # 1.1.4 Released on Sunday, November 1 2026. diff --git a/README.md b/README.md index e08377ab..0d4f5d14 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ The library comes with a service that exposes `WithJs` to `IConfiguration`. This - Support of modern JavaScript (ES2015 through ES2025) through Jint - Connection to the DOM - ES modules and import maps (`")); + } + + private static IHtmlElement Button(IDocument document) => (IHtmlElement)document.GetElementById("b"); + + private static async Task WaitForTitle(IDocument document, String title) + { + for (var i = 0; i < 200 && document.Title != title; i++) + { + await Task.Delay(10).ConfigureAwait(false); + } + + Assert.AreEqual(title, document.Title); + } + + [Test] + public async Task TimerRunsBoundFunctionWithItsThisAndArguments() + { + var document = await OpenAsync(@" + function done(a, b) { document.title = this.name + a + b; } + setTimeout(done.bind({ name: 'bound' }, 1, 2), 0);"); + + await WaitForTitle(document, "bound12"); + } + + [Test] + public async Task EventListenerRunsBoundFunction() + { + var document = await OpenAsync(@" + function clicked(ev) { document.title = this.name + ev.type; } + document.getElementById('b').addEventListener('click', clicked.bind({ name: 'bound-' }));"); + + Button(document).DoClick(); + + await WaitForTitle(document, "bound-click"); + } + + [Test] + public async Task EventListenerRunsBoundFunctionOfBoundFunction() + { + var document = await OpenAsync(@" + function clicked() { document.title = this.name; } + document.getElementById('b').addEventListener('click', clicked.bind({ name: 'first' }).bind({ name: 'second' }));"); + + Button(document).DoClick(); + + await WaitForTitle(document, "first"); + } + + [Test] + public async Task EventListenerRunsCallableProxy() + { + var document = await OpenAsync(@" + var proxy = new Proxy(function () { document.title = 'proxied'; }, {}); + document.getElementById('b').addEventListener('click', proxy);"); + + Button(document).DoClick(); + + await WaitForTitle(document, "proxied"); + } + + [Test] + public async Task EventHandlerPropertyRunsAndHandsBackBoundFunction() + { + var document = await OpenAsync(@" + var button = document.getElementById('b'); + var handler = function () { document.title = this.name; }.bind({ name: 'handled' }); + button.onclick = handler; + document.body.setAttribute('data-same', String(button.onclick === handler));"); + + Button(document).DoClick(); + + await WaitForTitle(document, "handled"); + Assert.AreEqual("true", document.Body.GetAttribute("data-same")); + } + + [Test] + public async Task EventHandlerPropertyIgnoresWhatIsNotCallable() + { + var document = await OpenAsync(@" + var button = document.getElementById('b'); + button.onclick = { name: 'no function' }; + document.body.setAttribute('data-value', String(button.onclick));"); + + Assert.AreEqual("null", document.Body.GetAttribute("data-value")); + } + + private static async Task Dispatched(String setup) + { + var document = await OpenAsync($@" + var button = document.getElementById('b'); + {setup} + var ev = new Event('click', {{ cancelable: true }}); + button.dispatchEvent(ev); + document.title = String(ev.defaultPrevented);"); + return document.Title; + } + + [Test] + public async Task EventHandlerPropertyReturningFalseCancelsTheEvent() + { + Assert.AreEqual("true", await Dispatched("button.onclick = function () { return false; };")); + } + + [Test] + public async Task EventHandlerAttributeReturningFalseCancelsTheEvent() + { + Assert.AreEqual("true", await Dispatched("button.setAttribute('onclick', 'return false');")); + } + + [TestCase("return true;")] + [TestCase("return 0;")] + [TestCase("")] + public async Task EventHandlerPropertyReturningAnythingElseDoesNotCancelTheEvent(String body) + { + Assert.AreEqual("false", await Dispatched($"button.onclick = function () {{ {body} }};")); + } + + [Test] + public async Task EventListenerReturningFalseDoesNotCancelTheEvent() + { + Assert.AreEqual("false", await Dispatched("button.addEventListener('click', function () { return false; });")); + } + + [Test] + public async Task BoundEventHandlerReturningFalseCancelsTheEvent() + { + Assert.AreEqual("true", await Dispatched("button.onclick = function () { return false; }.bind(null);")); + } + + [Test] + public async Task ChangingAnEventHandlerAttributeReplacesTheHandler() + { + var document = await OpenAsync(@" + var calls = []; + var button = document.getElementById('b'); + button.setAttribute('onclick', 'calls.push(1)'); + button.setAttribute('onclick', 'calls.push(2)'); + button.dispatchEvent(new Event('click')); + document.title = calls.join();"); + + Assert.AreEqual("2", document.Title); + } + + [Test] + public async Task RemovingAnEventHandlerAttributeRemovesTheHandler() + { + var document = await OpenAsync(@" + var calls = 0; + var button = document.getElementById('b'); + button.setAttribute('onclick', 'calls++'); + button.removeAttribute('onclick'); + button.dispatchEvent(new Event('click')); + document.title = String(calls);"); + + Assert.AreEqual("0", document.Title); + } + + [Test] + public async Task EventHandlerAttributeWithASyntaxErrorIsReported() + { + var document = await OpenAsync(@" + window.onerror = function (message) { document.title = 'reported'; }; + var button = document.getElementById('b'); + button.setAttribute('onclick', 'function ('); + document.body.setAttribute('data-after', 'yes'); + button.dispatchEvent(new Event('click'));"); + + Assert.AreEqual("reported", document.Title); + Assert.AreEqual("yes", document.Body.GetAttribute("data-after")); + } + + [Test] + public async Task IdleCallbackGetsItsDeadline() + { + var document = await OpenAsync(@" + var called = false; + requestIdleCallback(function (deadline) { + document.title = [deadline.didTimeout, deadline.timeRemaining() > 0, deadline.timeRemaining() <= 50].join(); + }, { timeout: 100 });"); + + await WaitForTitle(document, "false,true,true"); + } + + [Test] + public async Task CancelledIdleCallbackIsNotCalled() + { + var document = await OpenAsync(@" + var handle = requestIdleCallback(function () { document.title = 'wrong'; }); + cancelIdleCallback(handle); + setTimeout(function () { document.title = 'fine'; }, 30);"); + + await WaitForTitle(document, "fine"); + } + + [Test] + public async Task DomParserLeavesThePageAlone() + { + var config = Configuration.Default.WithJs().WithEventLoop(); + var context = BrowsingContext.New(config); + var document = await context.OpenAsync(m => m.Content(@"

page

")); + + Assert.AreSame(document, context.Active); + Assert.AreEqual("other,false,page", document.Title); + Assert.IsNotNull(document.GetElementById("mine")); + } + + [Test] + public async Task DomParserDoesNotRunWhatItParses() + { + var document = await OpenAsync(@" + new DOMParser().parseFromString('", + [frameAddress] = frameHtml, + }; + var config = Configuration.Default + .With(new SiteRequester(pages)) + .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }) + .WithJs() + .WithEventLoop(); + var page = await BrowsingContext.New(config).OpenAsync(PageAddress); + var frame = (IHtmlInlineFrameElement)page.GetElementById("f"); + await Until(() => frame.ContentDocument?.ReadyState == DocumentReadyState.Complete); + return (page, frame.ContentDocument); + } + + private static async Task Until(Func condition) + { + for (var i = 0; i < 200 && !condition(); i++) + { + await Task.Delay(20); + } + + Assert.IsTrue(condition(), "The condition never held."); + } + + private static String Eval(IDocument document, String script) => Convert.ToString(document.ExecuteScript(script), System.Globalization.CultureInfo.InvariantCulture); + + [Test] + public async Task ContentDocumentOfAnotherOriginIsNull() + { + var (page, _) = await LoadAsync(CrossAddress, "secret"); + Assert.AreEqual("true", Eval(page, "String(document.getElementById('f').contentDocument === null)")); + } + + [Test] + public async Task ContentDocumentOfTheSameOriginIsAvailable() + { + var (page, _) = await LoadAsync(SameAddress, "mine"); + Assert.AreEqual("mine", Eval(page, "document.getElementById('f').contentDocument.title")); + Assert.AreEqual("mine", Eval(page, "document.getElementById('f').contentWindow.document.title")); + } + + [TestCase("document")] + [TestCase("localStorage")] + [TestCase("name")] + [TestCase("navigator")] + [TestCase("fetch")] + [TestCase("setTimeout")] + [TestCase("getComputedStyle")] + [TestCase("eval")] + [TestCase("secret")] + public async Task WindowOfAnotherOriginHasNoSuchMember(String member) + { + var (page, _) = await LoadAsync(CrossAddress, ""); + Assert.AreEqual("undefined", Eval(page, $"typeof document.getElementById('f').contentWindow.{member}")); + } + + [TestCase("postMessage", "function")] + [TestCase("closed", "boolean")] + [TestCase("length", "number")] + [TestCase("location", "object")] + [TestCase("parent", "object")] + [TestCase("top", "object")] + public async Task WindowOfAnotherOriginHasWhatIsAllowed(String member, String type) + { + var (page, _) = await LoadAsync(CrossAddress, ""); + Assert.AreEqual(type, Eval(page, $"typeof document.getElementById('f').contentWindow.{member}")); + } + + [Test] + public async Task WindowOfAnotherOriginStaysTheSameObject() + { + var (page, _) = await LoadAsync(CrossAddress, ""); + Assert.AreEqual("true", Eval(page, "String(document.getElementById('f').contentWindow === document.getElementById('f').contentWindow)")); + } + + [Test] + public async Task LocationOfAnotherOriginCannotBeRead() + { + var (page, _) = await LoadAsync(CrossAddress, ""); + Assert.AreEqual("thrown", Eval(page, "(function () { try { return document.getElementById('f').contentWindow.location.href; } catch (e) { return 'thrown'; } })()")); + } + + [Test] + public async Task FrameCannotReachThePageOfAnotherOrigin() + { + var (_, frame) = await LoadAsync(CrossAddress, ""); + + Assert.AreEqual("undefined", Eval(frame, "typeof parent.document")); + Assert.AreEqual("undefined", Eval(frame, "typeof top.document")); + Assert.AreEqual("undefined", Eval(frame, "typeof parent.parent.document")); + Assert.AreEqual("true", Eval(frame, "String(parent === top)")); + } + + [Test] + public async Task FrameCanReachThePageOfTheSameOrigin() + { + var (_, frame) = await LoadAsync(SameAddress, ""); + Assert.AreEqual("object", Eval(frame, "typeof parent.document")); + } + + [Test] + public async Task FrameCannotNavigateThePageOfAnotherOrigin() + { + var (page, frame) = await LoadAsync(CrossAddress, ""); + + Assert.AreEqual("thrown", Eval(frame, "(function () { try { top.location.href = 'https://evil.test/'; return 'set'; } catch (e) { return 'thrown'; } })()")); + Assert.AreEqual(PageAddress, page.Url); + } + + [Test] + public async Task PageCanNavigateItsFrameOfAnotherOrigin() + { + var (page, frame) = await LoadAsync(CrossAddress, ""); + Assert.AreEqual("set", Eval(page, "(function () { try { document.getElementById('f').contentWindow.location.href = 'https://c.test/'; return 'set'; } catch (e) { return 'thrown'; } })()")); + } + + private const String EchoingFrame = ""; + + [Test] + public async Task MessageReachesAFrameOfAnotherOriginWithWhoSentIt() + { + var (page, frame) = await LoadAsync(CrossAddress, EchoingFrame, "window.addEventListener('message', function (e) { window.reply = e.data; window.replyOrigin = e.origin; });"); + + Eval(page, "document.getElementById('f').contentWindow.postMessage({ a: 1, b: [2, 'x'], c: { d: true } }, 'https://b.test')"); + + await Until(() => Eval(frame, "window.seen") != "undefined" && Eval(page, "window.reply") == "back" && Eval(page, "window.replyOrigin") != "undefined"); + Assert.AreEqual("{\"a\":1,\"b\":[2,\"x\"],\"c\":{\"d\":true}}", Eval(frame, "window.seen")); + Assert.AreEqual("https://a.test", Eval(frame, "window.seenOrigin")); + Assert.AreEqual("https://b.test", Eval(page, "window.replyOrigin")); + } + + [TestCase("https://c.test")] + [TestCase("https://a.test")] + [TestCase("/")] + public async Task MessageForAnotherOriginIsNotDelivered(String targetOrigin) + { + var (page, frame) = await LoadAsync(CrossAddress, EchoingFrame); + + Eval(page, $"document.getElementById('f').contentWindow.postMessage('x', '{targetOrigin}')"); + await Task.Delay(100); + + Assert.AreEqual("undefined", Eval(frame, "typeof window.seen")); + } + + [Test] + public async Task MessageWithOptionsHasItsTargetOrigin() + { + var (page, frame) = await LoadAsync(CrossAddress, EchoingFrame); + + Eval(page, "document.getElementById('f').contentWindow.postMessage('x', { targetOrigin: 'https://b.test' })"); + + await Until(() => Eval(frame, "typeof window.seen") == "string"); + } + + [TestCase("function () {}")] + [TestCase("document")] + [TestCase("{ a: document.body }")] + public async Task WhatCannotBeClonedIsNotPosted(String message) + { + var (page, frame) = await LoadAsync(CrossAddress, EchoingFrame); + + Assert.AreEqual("thrown", Eval(page, $"(function () {{ try {{ document.getElementById('f').contentWindow.postMessage({message}, '*'); return 'posted'; }} catch (e) {{ return 'thrown'; }} }})()")); + } + + [Test] + public async Task CyclicObjectIsNotPosted() + { + var (page, _) = await LoadAsync(CrossAddress, EchoingFrame); + + Assert.AreEqual("thrown", Eval(page, "(function () { var a = {}; a.self = a; try { document.getElementById('f').contentWindow.postMessage(a, '*'); return 'posted'; } catch (e) { return 'thrown'; } })()")); + } + + [Test] + public async Task MessageIsACopy() + { + var (page, frame) = await LoadAsync(SameAddress, ""); + + Eval(page, "window.sent = { a: 1 }; document.getElementById('f').contentWindow.postMessage(window.sent, '*')"); + await Until(() => Eval(frame, "typeof window.got") == "object"); + + Assert.AreEqual("1", Eval(page, "window.sent.a")); + } + + [Test] + public async Task SandboxWithoutScriptsRunsNothing() + { + var config = Configuration.Default.WithJs().WithEventLoop(); + var top = BrowsingContext.New(config); + var context = top.CreateChild("sandboxed", Sandboxes.Scripts); + var document = await context.OpenAsync(m => m.Content("")); + + document.Body.DoClick(); + + await Task.Delay(50); + Assert.AreNotEqual("ran", document.Title); + Assert.AreNotEqual("clicked", document.Title); + } + + [Test] + public async Task SandboxWithoutSameOriginIsOfNoOrigin() + { + var config = Configuration.Default.WithJs().WithEventLoop(); + var top = await BrowsingContext.New(config).OpenAsync(m => m.Content("").Address(PageAddress)); + var context = top.Context.CreateChild("sandboxed", Sandboxes.Origin); + var document = await context.OpenAsync(m => m.Content("").Address(PageAddress)); + + Assert.AreEqual("undefined", Eval(document, "typeof parent.document")); + } + } +} diff --git a/src/AngleSharp.Js.Tests/CustomElementsTests.cs b/src/AngleSharp.Js.Tests/CustomElementsTests.cs new file mode 100644 index 00000000..c91f4cf7 --- /dev/null +++ b/src/AngleSharp.Js.Tests/CustomElementsTests.cs @@ -0,0 +1,438 @@ +namespace AngleSharp.Js.Tests +{ + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Threading.Tasks; + + /// + /// Custom elements as scripts see them: classes deriving from the elements of the DOM. + /// + [TestFixture] + public class CustomElementsTests + { + private static Task OpenAsync(String html) + { + var config = Configuration.Default.WithJs().WithEventLoop(); + return BrowsingContext.New(config).OpenAsync(m => m.Address("https://example.com/").Content($"{html}")); + } + + private static async Task Eval(String script, String body = "") + { + var document = await OpenAsync($"{body}"); + return document.Title; + } + + [Test] + public async Task RegistryIsOnTheWindow() + { + Assert.AreEqual("object,true,function", await Eval("return [typeof customElements, window.customElements === customElements, typeof customElements.define].join();")); + } + + [Test] + public async Task ClassIsDefinedAndFound() + { + Assert.AreEqual("true,my-el,true", await Eval(@" + class MyEl extends HTMLElement {} + customElements.define('my-el', MyEl); + return [customElements.get('my-el') === MyEl, customElements.getName(MyEl), customElements.get('other-el') === undefined].join();")); + } + + [Test] + public async Task CreatedElementIsAnInstanceOfItsClass() + { + Assert.AreEqual("true,true,true,MY-EL,hello", await Eval(@" + class MyEl extends HTMLElement { + constructor() { super(); this.greeting = 'hello'; } + greet() { return this.greeting; } + } + customElements.define('my-el', MyEl); + var el = document.createElement('my-el'); + return [el instanceof MyEl, el instanceof HTMLElement, el instanceof Element, el.tagName, el.greet()].join();")); + } + + [Test] + public async Task ElementCreatedWithNewIsTheElementOfTheDefinition() + { + Assert.AreEqual("MY-EL,true,x", await Eval(@" + class MyEl extends HTMLElement {} + customElements.define('my-el', MyEl); + var el = new MyEl(); + el.setAttribute('a', 'x'); + document.body.appendChild(el); + return [el.tagName, el instanceof MyEl, document.querySelector('my-el').getAttribute('a')].join();")); + } + + [Test] + public async Task WrapperStaysTheSameObject() + { + Assert.AreEqual("true", await Eval(@" + class MyEl extends HTMLElement {} + customElements.define('my-el', MyEl); + var el = new MyEl(); + document.body.appendChild(el); + return document.querySelector('my-el') === el;")); + } + + [Test] + public async Task ExistingElementsAreUpgradedWhenDefined() + { + Assert.AreEqual("false,true,upgraded", await Eval(@" + var el = document.getElementById('a'); + var before = el instanceof HTMLUnknownElement && el.state === 'upgraded'; + class MyEl extends HTMLElement { constructor() { super(); this.state = 'upgraded'; } } + customElements.define('my-el', MyEl); + return [before, el instanceof MyEl, el.state].join();", "")); + } + + [Test] + public async Task ParsedElementsAfterTheDefinitionAreUpgraded() + { + var document = await OpenAsync(@""); + + Assert.AreEqual("constructed a,connected a true", document.Title); + } + + [Test] + public async Task CallbacksAreCalledWithTheElementAsThis() + { + Assert.AreEqual("connected:true,attr:color::red,disconnected:true", await Eval(@" + var log = []; + class MyEl extends HTMLElement { + static get observedAttributes() { return ['color']; } + connectedCallback() { log.push('connected:' + (this instanceof MyEl)); } + disconnectedCallback() { log.push('disconnected:' + (this instanceof MyEl)); } + attributeChangedCallback(name, oldValue, newValue) { log.push('attr:' + name + ':' + (oldValue === null ? '' : oldValue) + ':' + newValue); } + } + customElements.define('my-el', MyEl); + var el = document.createElement('my-el'); + document.body.appendChild(el); + el.setAttribute('color', 'red'); + el.setAttribute('other', 'x'); + el.remove(); + return log.join();")); + } + + [Test] + public async Task ObservedAttributesMayBeAStaticField() + { + Assert.AreEqual("a", await Eval(@" + var log = []; + class MyEl extends HTMLElement { + static observedAttributes = ['a']; + attributeChangedCallback(name) { log.push(name); } + } + customElements.define('my-el', MyEl); + var el = document.createElement('my-el'); + el.setAttribute('b', '1'); + el.setAttribute('a', '1'); + return log.join();")); + } + + [Test] + public async Task ClassCanExtendACustomElementClass() + { + Assert.AreEqual("base,true,true", await Eval(@" + class Base extends HTMLElement { who() { return 'base'; } } + class Derived extends Base {} + customElements.define('my-derived', Derived); + var el = new Derived(); + return [el.who(), el instanceof Base, el instanceof Derived].join();")); + } + + [Test] + public async Task ClassCanExtendABuiltInElement() + { + Assert.AreEqual("BUTTON,true,true,my-button", await Eval(@" + class MyButton extends HTMLButtonElement {} + customElements.define('my-button', MyButton, { extends: 'button' }); + var el = new MyButton(); + return [el.tagName, el instanceof MyButton, el instanceof HTMLButtonElement, el.outerHTML.indexOf('is=""my-button""') > 0 ? 'my-button' : el.outerHTML].join();")); + } + + [Test] + public async Task ElementCanHaveAShadowRoot() + { + Assert.AreEqual("inner", await Eval(@" + class MyEl extends HTMLElement { + constructor() { super(); this.attachShadow({ mode: 'open' }).innerHTML = 'inner'; } + } + customElements.define('my-el', MyEl); + return new MyEl().shadowRoot.querySelector('span').textContent;")); + } + + [Test] + public async Task ClassNotDefinedCannotBeCreated() + { + Assert.AreEqual("TypeError", await Eval(@" + class MyEl extends HTMLElement {} + try { new MyEl(); return 'no error'; } catch (e) { return e.name; }")); + } + + [Test] + public async Task HtmlElementItselfCannotBeCreated() + { + Assert.AreEqual("TypeError", await Eval("try { new HTMLElement(); return 'no error'; } catch (e) { return e.name; }")); + } + + [TestCase("customElements.define('nohyphen', class extends HTMLElement {})", "SyntaxError")] + [TestCase("customElements.define('my-el', class extends HTMLElement {}); customElements.define('my-el', class extends HTMLElement {})", "NotSupportedError")] + [TestCase("customElements.define('my-el', function () {}.bind(null))", "TypeError")] + [TestCase("customElements.define('my-el', 42)", "TypeError")] + [TestCase("customElements.define('my-el', class extends HTMLElement { get connectedCallback() { return 1; } })", "TypeError")] + public async Task WhatCannotBeDefinedIsRefused(String statement, String expected) + { + Assert.AreEqual(expected, await Eval($"try {{ {statement}; return 'no error'; }} catch (e) {{ return e.name; }}")); + } + + [Test] + public async Task WhenDefinedGivesTheClass() + { + var document = await OpenAsync(@""); + + for (var i = 0; i < 200 && document.Title.Length == 0; i++) + { + await Task.Delay(10); + } + + Assert.AreEqual("true", document.Title); + } + + [Test] + public async Task ConstructorThrowingIsReportedAndLeavesTheElement() + { + var context = BrowsingContext.New(Configuration.Default.WithJs().WithEventLoop()); + var errors = context.CollectErrors(); + var document = await context.OpenAsync(m => m.Content(@"")); + + Assert.AreEqual("null", document.Title); + Assert.AreEqual(1, errors.Count); + StringAssert.Contains("broken", errors[0].Message); + } + + [Test] + public async Task CallbackThrowingIsReported() + { + var context = BrowsingContext.New(Configuration.Default.WithJs().WithEventLoop()); + var errors = context.CollectErrors(); + var document = await context.OpenAsync(m => m.Content(@"")); + + Assert.AreEqual("went on", document.Title); + Assert.AreEqual(1, errors.Count); + } + + [Test] + public async Task ConstructorNotCallingSuperIsReported() + { + var context = BrowsingContext.New(Configuration.Default.WithJs().WithEventLoop()); + var errors = context.CollectErrors(); + await context.OpenAsync(m => m.Content(@"")); + + Assert.AreEqual(1, errors.Count); + } + + [Test] + public async Task ConstructorMayCreateOtherCustomElements() + { + Assert.AreEqual("MY-INNER,true", await Eval(@" + class Inner extends HTMLElement {} + class Outer extends HTMLElement { constructor() { super(); this.inner = new Inner(); } } + customElements.define('my-inner', Inner); + customElements.define('my-outer', Outer); + var outer = new Outer(); + return [outer.inner.tagName, outer.inner instanceof Inner].join();")); + } + + [Test] + public async Task ReflectConstructWorksAsForOldClasses() + { + Assert.AreEqual("true", await Eval(@" + function MyEl() { return Reflect.construct(HTMLElement, [], MyEl); } + MyEl.prototype = Object.create(HTMLElement.prototype); + MyEl.prototype.constructor = MyEl; + customElements.define('my-el', MyEl); + return document.createElement('my-el') instanceof MyEl;")); + } + + [Test] + public async Task DefinedPseudoClassFollowsTheDefinition() + { + Assert.AreEqual("0,1", await Eval(@" + var before = document.querySelectorAll('my-el:defined').length; + customElements.define('my-el', class extends HTMLElement {}); + return [before, document.querySelectorAll('my-el:defined').length].join();", "")); + } + + [Test] + public async Task CallbacksSeeWhatTheCallOfTheScriptDidCompletely() + { + Assert.AreEqual("a:my-b,b:", await Eval(@" + var log = []; + class Item extends HTMLElement { + connectedCallback() { log.push(this.id + ':' + (this.nextElementSibling ? this.nextElementSibling.localName : '')); } + } + customElements.define('my-a', class extends Item {}); + customElements.define('my-b', class extends Item {}); + var parent = document.createElement('div'); + document.body.appendChild(parent); + parent.innerHTML = ''; + return log.join();")); + } + + [Test] + public async Task CallbacksAreDoneWhenTheCallOfTheScriptReturns() + { + Assert.AreEqual("setting,changed,set", await Eval(@" + var log = []; + class MyEl extends HTMLElement { + static observedAttributes = ['a']; + attributeChangedCallback() { log.push('changed'); } + } + customElements.define('my-el', MyEl); + var el = new MyEl(); + log.push('setting'); + el.setAttribute('a', '1'); + log.push('set'); + return log.join();")); + } + + [Test] + public async Task AppendTellsAfterAllOfItIsIn() + { + Assert.AreEqual("2,2", await Eval(@" + var log = []; + class MyEl extends HTMLElement { connectedCallback() { log.push(this.parentNode.childElementCount); } } + customElements.define('my-el', MyEl); + var parent = document.createElement('div'); + document.body.appendChild(parent); + parent.append(new MyEl(), new MyEl()); + return log.join();")); + } + + [Test] + public async Task CallbackChangingTheTreeWorksInTheMiddleOfAnotherCall() + { + Assert.AreEqual("1", await Eval(@" + class MyEl extends HTMLElement { + connectedCallback() { + var inner = document.createElement('span'); + this.appendChild(inner); + inner.remove(); + this.appendChild(document.createElement('b')); + } + } + customElements.define('my-el', MyEl); + var el = new MyEl(); + document.body.appendChild(el); + return el.childElementCount;")); + } + + [Test] + public async Task CreateElementTakesWhatItIs() + { + Assert.AreEqual("true,true,true", await Eval(@" + class MyButton extends HTMLButtonElement {} + customElements.define('my-button', MyButton, { extends: 'button' }); + var el = document.createElement('button', { is: 'my-button' }); + var plain = document.createElement('button'); + return [el instanceof MyButton, el.getAttribute('is') === null, !(plain instanceof MyButton)].join();")); + } + + [Test] + public async Task CreateElementKeepsWorkingWithoutOptions() + { + Assert.AreEqual("DIV,DIV", await Eval(@" + return [document.createElement('div').tagName, document.createElement('div', {}).tagName].join();")); + } + + [Test] + public async Task ClonedElementIsAnInstanceOfItsClass() + { + Assert.AreEqual("true,false,constructed", await Eval(@" + class MyEl extends HTMLElement { constructor() { super(); this.state = 'constructed'; } } + customElements.define('my-el', MyEl); + var el = new MyEl(); + var clone = el.cloneNode(); + return [clone instanceof MyEl, clone === el, clone.state].join();")); + } + + [Test] + public async Task AdoptedCallbackGetsTheDocuments() + { + Assert.AreEqual("true,true", await Eval(@" + var log = []; + class MyEl extends HTMLElement { adoptedCallback(oldDocument, newDocument) { log.push(oldDocument === document, newDocument === other); } } + customElements.define('my-el', MyEl); + var other = document.implementation.createHTMLDocument('other'); + var el = new MyEl(); + other.body.appendChild(el); + return log.join();")); + } + + [Test] + public async Task ThrowingMemberStillRunsTheReactionsOfItsCall() + { + Assert.AreEqual("connected,caught", await Eval(@" + var log = []; + class MyEl extends HTMLElement { connectedCallback() { log.push('connected'); } } + customElements.define('my-el', MyEl); + var el = new MyEl(); + document.body.appendChild(el); + try { document.body.appendChild(document.documentElement); } catch (e) { log.push('caught'); } + return log.join();")); + } + + [Test] + public async Task OtherElementsAreNoInstancesOfAClass() + { + Assert.AreEqual("true,false,false,true,true", await Eval(@" + class Base extends HTMLElement {} + class Derived extends Base {} + class Other extends HTMLElement {} + customElements.define('my-derived', Derived); + customElements.define('my-other', Other); + var el = new Derived(); + var div = document.createElement('div'); + return [el instanceof Base, el instanceof Other, div instanceof Base, div instanceof HTMLElement, el instanceof HTMLElement].join();")); + } + + [Test] + public async Task NodesCanBeReplacedWith() + { + Assert.AreEqual("B", await Eval(@" + var parent = document.createElement('div'); + var a = parent.appendChild(document.createElement('a')); + a.replaceWith(document.createElement('b')); + return parent.firstChild.tagName;")); + } + + [Test] + public async Task DomExceptionsOfTheRegistryAreRealOnes() + { + Assert.AreEqual("true", await Eval("try { customElements.define('x', class extends HTMLElement {}); } catch (e) { return e instanceof DOMException; }")); + } + } +} diff --git a/src/AngleSharp.Js.Tests/DeferredConstructorTests.cs b/src/AngleSharp.Js.Tests/DeferredConstructorTests.cs index 4cb91550..6ee5c9cd 100644 --- a/src/AngleSharp.Js.Tests/DeferredConstructorTests.cs +++ b/src/AngleSharp.Js.Tests/DeferredConstructorTests.cs @@ -39,24 +39,24 @@ public async Task UnreadConstructorIsStillOwnPropertyOfWindow() } [Test] - public async Task UnreadConstructorIsStillEnumerable() + public async Task UnreadConstructorIsStillListed() { - var result = await "String(Object.keys(window).indexOf('HTMLTableColElement') !== -1)".EvalScriptAsync(); + var result = await "String(Object.getOwnPropertyNames(window).indexOf('HTMLTableColElement') !== -1)".EvalScriptAsync(); Assert.AreEqual("true", result); } [Test] - public async Task UnreadConstructorIsStillFoundByForIn() + public async Task UnreadConstructorIsNotEnumerable() { var result = await "String((function () { for (var k in window) { if (k === 'HTMLTableColElement') { return true; } } return false; })())".EvalScriptAsync(); - Assert.AreEqual("true", result); + Assert.AreEqual("false", result); } [Test] public async Task ConstructorKeepsItsAttributes() { var result = await "(function () { var d = Object.getOwnPropertyDescriptor(window, 'HTMLDivElement'); return d.writable + ',' + d.enumerable + ',' + d.configurable; })()".EvalScriptAsync(); - Assert.AreEqual("false,true,false", result); + Assert.AreEqual("true,false,true", result); } [Test] @@ -111,16 +111,16 @@ public async Task InstanceReportsTheSameConstructorTheWindowPublishes() } [Test] - public async Task ConstructorIsNotWritable() + public async Task ConstructorIsWritable() { - var result = await "String((function () { var before = HTMLDivElement; window.HTMLDivElement = 5; return window.HTMLDivElement === before; })())".EvalScriptAsync(); + var result = await "String((function () { window.HTMLDivElement = 5; return window.HTMLDivElement === 5 && HTMLDivElement === 5; })())".EvalScriptAsync(); Assert.AreEqual("true", result); } [Test] - public async Task ConstructorIsNotConfigurable() + public async Task ConstructorIsConfigurable() { - var result = await "String((delete window.HTMLDivElement) === false && typeof HTMLDivElement === 'function')".EvalScriptAsync(); + var result = await "String((delete window.HTMLDivElement) === true && typeof HTMLDivElement === 'undefined')".EvalScriptAsync(); Assert.AreEqual("true", result); } diff --git a/src/AngleSharp.Js.Tests/DocumentOpenTests.cs b/src/AngleSharp.Js.Tests/DocumentOpenTests.cs new file mode 100644 index 00000000..7945d812 --- /dev/null +++ b/src/AngleSharp.Js.Tests/DocumentOpenTests.cs @@ -0,0 +1,116 @@ +namespace AngleSharp.Js.Tests +{ + using AngleSharp.Browser; + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using NUnit.Framework; + using System; + using System.Threading.Tasks; + + /// + /// A handler is called on the event loop, which document.open must not wait for. + /// + [TestFixture] + public class DocumentOpenTests + { + private static async Task LoadAsync(String html) + { + var config = Configuration.Default.WithJs().WithEventLoop(); + return await BrowsingContext.New(config).OpenAsync(m => m.Content(html)); + } + + private static async Task ClickAsync(IDocument document, String id) + { + var done = new TaskCompletionSource(); + var loop = ((AngleSharp.Dom.Document)document).Loop; + loop.Enqueue(() => ((IHtmlElement)document.GetElementById(id)).DoClick()); + // after what the click may have queued itself + loop.Enqueue(() => loop.Enqueue(() => done.TrySetResult(true))); + var finished = await Task.WhenAny(done.Task, Task.Delay(10000)); + Assert.AreSame(done.Task, finished, "The event loop is stuck."); + } + + [Test] + public async Task HandlerOpensWritesAndClosesTheDocument() + { + var document = await LoadAsync(@"

"); + + await ClickAsync(document, "b"); + + Assert.IsNull(document.GetElementById("old")); + Assert.AreEqual("x", document.GetElementById("new").TextContent); + Assert.AreEqual(DocumentReadyState.Complete, document.ReadyState); + } + + [Test] + public async Task EmptyFrameCanBeWrittenToFromAScript() + { + var document = await LoadAsync(@""); + await document.WhenStable(); + var frame = (IHtmlInlineFrameElement)document.QuerySelector("iframe"); + + await frame.ContentDocument.WhenStable(); + + Assert.AreEqual("trueabout:blankcompletehttp://localhosthttp://localhost", document.Title); + Assert.AreEqual("written", frame.ContentDocument.GetElementById("x").TextContent); + Assert.AreEqual("true", frame.ContentDocument.Body.GetAttribute("ran")); + } + + [Test] + public async Task EmptyFrameFiresLoadWhenInserted() + { + var document = await LoadAsync(@""); + await document.WhenStable(); + var done = new TaskCompletionSource(); + var loop = ((AngleSharp.Dom.Document)document).Loop; + loop.Enqueue(() => done.TrySetResult(true)); + await done.Task; + + Assert.AreEqual("loadedtrue", document.Title); + } + + [TestCase("https://page.test/", "https://page.test")] + public async Task OriginOfFramesWithoutAnAddressIsTheOneOfTheirCreator(String address, String origin) + { + var config = Configuration.Default.WithJs().WithEventLoop(); + var document = await BrowsingContext.New(config).OpenAsync(m => m.Address(address).Content(@"")); + await document.WhenStable(); + + for (var i = 0; i < 300 && (((IHtmlInlineFrameElement)document.GetElementById("s")).ContentDocument is null || ((IHtmlInlineFrameElement)document.GetElementById("b")).ContentDocument is null); i++) + { + await Task.Delay(10); + } + + Assert.AreEqual(origin, document.ExecuteScript("window.origin")); + Assert.AreEqual(origin, document.ExecuteScript("document.getElementById('e').contentWindow.origin")); + Assert.AreEqual(origin, document.ExecuteScript("document.getElementById('s').contentWindow.origin")); + Assert.AreEqual("null", ((IHtmlInlineFrameElement)document.GetElementById("b")).ContentDocument.ExecuteScript("window.origin")); + } + + [Test] + public async Task WriteWithoutCloseIsParsedWhenTheHandlerIsDone() + { + var document = await LoadAsync(@"