Remove inline JS event handler from NavMenu component in Blazor Web App template #63828
+12
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #XXXXX
This PR removes the inline JavaScript event handler from the NavMenu component in the Blazor Web App project template and replaces it with a proper ES6 module approach to improve Content Security Policy (CSP) compliance.
Problem
The current NavMenu component contains an inline
onclick
attribute:This inline event handler requires CSP configurations to include
'unsafe-hashes'
with a specific SHA-256 hash, which goes against web security best practices. The HTML specification discourages this approach as it can lead to security vulnerabilities.Solution
NavMenu.razor.js
: Added an ES6 module that properly attaches a click event listener to the navigation scrollable areaNavMenu.razor
:<script type="module" src="@Assets["Components/Layout/NavMenu.razor.js"]"></script>
<div id="nav-scrollable" class="nav-scrollable">
The JavaScript module code:
Benefits
'unsafe-hashes'
in CSP configurationsReconnectModal.razor.js
andPasskeySubmit.razor.js
Testing
Verified that the navigation toggle functionality works correctly in both desktop and mobile responsive views. The hamburger menu opens and closes the navigation as expected, maintaining full backward compatibility.
Desktop view showing full navigation: Mobile view with hamburger menu:

Mobile view with navigation expanded:

Impact
This change will help developers implement proper Content Security Policies without needing to accommodate inline event handlers, improving the overall security posture of Blazor Web applications created from the template.
Original prompt
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.