Skip to content

Commit b23daa2

Browse files
authored
Merge pull request #116 from lahma/fix/window-console-identity
Return the same console object for a window
2 parents 6b79f63 + 0e50cc0 commit b23daa2

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

src/AngleSharp.Js.Tests/DomTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,5 +68,19 @@ public async Task NumericIndexerOfTokenListYieldsTheToken()
6868
var result = await "new DOMParser().parseFromString(`<div class='a b'></div>`, 'text/html').body.firstChild.classList[1]".EvalScriptAsync();
6969
Assert.AreEqual("b", result);
7070
}
71+
72+
[Test]
73+
public async Task ConsoleIsTheSameObjectOnEveryAccess()
74+
{
75+
var result = await "window.console === window.console".EvalScriptAsync();
76+
Assert.AreEqual("True", result);
77+
}
78+
79+
[Test]
80+
public async Task ConsoleKeepsPropertiesAssignedToIt()
81+
{
82+
var result = await "(function () { window.console.marker = 'kept'; return window.console.marker; })()".EvalScriptAsync();
83+
Assert.AreEqual("kept", result);
84+
}
7185
}
7286
}

src/AngleSharp.Js/Dom/WindowExtensions.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,17 @@ namespace AngleSharp.Js.Dom
77
using AngleSharp.Html.Dom;
88
using AngleSharp.Js.Attributes;
99
using System;
10+
using System.Runtime.CompilerServices;
1011

1112
/// <summary>
1213
/// Defines a set of extensions for the window object.
1314
/// </summary>
1415
[DomExposed("Window")]
1516
public static class WindowExtensions
1617
{
18+
private static readonly ConditionalWeakTable<IWindow, Console> Consoles =
19+
new ConditionalWeakTable<IWindow, Console>();
20+
1721
/// <summary>
1822
/// Posts a message.
1923
/// </summary>
@@ -34,15 +38,17 @@ public static void PostMessage(this IWindow window, String message, String targe
3438
public static IWindow Top(this IWindow window) => window.Document.Context?.Creator?.DefaultView;
3539

3640
/// <summary>
37-
/// Gets the console instance.
41+
/// Gets the console instance. The same instance is returned for the same
42+
/// window, so that `window.console === window.console` holds and anything
43+
/// script puts on the console is still there on the next access.
3844
/// </summary>
3945
/// <param name="window"></param>
4046
/// <returns></returns>
4147
[DomName("console")]
4248
[DomAccessor(Accessors.Getter)]
4349
public static Console Console(this IWindow window)
4450
{
45-
return new Console(window);
51+
return Consoles.GetValue(window, w => new Console(w));
4652
}
4753

4854
/// <summary>

0 commit comments

Comments
 (0)