Skip to content

Commit 05c1b15

Browse files
Fix copy buttons (#3584)
Co-authored-by: James Newton-King <james@newtonking.com>
1 parent 036b05b commit 05c1b15

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/Aspire.Dashboard/Extensions/FluentUIExtensions.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Licensed to the .NET Foundation under one or more agreements.
1+
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
namespace Aspire.Dashboard.Extensions;
@@ -7,12 +7,15 @@ internal static class FluentUIExtensions
77
{
88
public static Dictionary<string, object> GetClipboardCopyAdditionalAttributes(string? text, string? precopy, string? postcopy, params (string Attribute, object Value)[] additionalAttributes)
99
{
10+
// No onclick attribute is added here. The CSP restricts inline scripts, including onclick.
11+
// Instead, a click event listener is added to the document and clicking the button is bubbled up to the event.
12+
// The document click listener looks for a button element and these attributes.
1013
var attributes = new Dictionary<string, object>
1114
{
1215
{ "data-text", text ?? string.Empty },
1316
{ "data-precopy", precopy ?? string.Empty },
1417
{ "data-postcopy", postcopy ?? string.Empty },
15-
{ "onclick", $"buttonCopyTextToClipboard(this)" }
18+
{ "data-copybutton", "true" }
1619
};
1720

1821
foreach (var (attribute, value) in additionalAttributes)

src/Aspire.Dashboard/wwwroot/js/app.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ if (firstUndefinedElement) {
1414
document.body.classList.remove("before-upgrade");
1515
}
1616

17+
// Register a global click event listener to handle copy button clicks.
18+
// Required because an "onclick" attribute is denied by CSP.
19+
document.addEventListener("click", function (e) {
20+
if (e.target.type === "button" && e.target.getAttribute("data-copybutton")) {
21+
buttonCopyTextToClipboard(e.target);
22+
e.stopPropagation();
23+
}
24+
});
25+
1726
let isScrolledToContent = false;
1827
let lastScrollHeight = null;
1928

0 commit comments

Comments
 (0)