├── .gitignore ├── BlazorPageScript.sln ├── LICENSE ├── README.md ├── samples └── BasicSample │ ├── BasicSample.csproj │ ├── Components │ ├── App.razor │ ├── Layout │ │ ├── MainLayout.razor │ │ └── MainLayout.razor.css │ ├── Pages │ │ ├── Error.razor │ │ ├── Example.razor │ │ ├── Example.razor.js │ │ ├── Home.razor │ │ └── Home.razor.js │ ├── Routes.razor │ └── _Imports.razor │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.Development.json │ ├── appsettings.json │ └── wwwroot │ └── app.css └── src ├── BlazorPageScript.csproj ├── PageScript.razor └── wwwroot └── BlazorPageScript.lib.module.js /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /BlazorPageScript.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorPageScript", "src\BlazorPageScript.csproj", "{05291163-6BC9-415A-BB66-61A47A7BB6BE}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{72817B90-7355-402D-8538-3CB4A8CF45E9}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BasicSample", "samples\BasicSample\BasicSample.csproj", "{A4EEDBD2-96AF-404C-A5AD-3A33968D7EF6}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {05291163-6BC9-415A-BB66-61A47A7BB6BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {05291163-6BC9-415A-BB66-61A47A7BB6BE}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {05291163-6BC9-415A-BB66-61A47A7BB6BE}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {05291163-6BC9-415A-BB66-61A47A7BB6BE}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {A4EEDBD2-96AF-404C-A5AD-3A33968D7EF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {A4EEDBD2-96AF-404C-A5AD-3A33968D7EF6}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {A4EEDBD2-96AF-404C-A5AD-3A33968D7EF6}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {A4EEDBD2-96AF-404C-A5AD-3A33968D7EF6}.Release|Any CPU.Build.0 = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(SolutionProperties) = preSolution 28 | HideSolutionNode = FALSE 29 | EndGlobalSection 30 | GlobalSection(NestedProjects) = preSolution 31 | {A4EEDBD2-96AF-404C-A5AD-3A33968D7EF6} = {72817B90-7355-402D-8538-3CB4A8CF45E9} 32 | EndGlobalSection 33 | GlobalSection(ExtensibilityGlobals) = postSolution 34 | SolutionGuid = {96BE6E22-44D3-4D16-8A69-E99E21AC117C} 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Mackinnon Buck 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **NOTE: This package has been superseded by https://github.com/MackinnonBuck/blazor-js-components** 2 | 3 | # BlazorPageScript 4 | 5 | A Blazor `` component enabling per-page JavaScript navigation callbacks. 6 | 7 | This allows Blazor Web applications to have page-specific JavaScript that works with enhanced navigation enabled or disabled. 8 | 9 | ## Basic usage 10 | 11 | _Example.razor_ 12 | ```razor 13 | @page "/example" 14 | 15 | Example 16 | 17 | 18 | 19 | Welcome to the example page. 20 | ``` 21 | 22 | _Example.razor.js_ 23 | ```js 24 | // Called when the script first gets loaded on the page. 25 | export function onLoad() { 26 | console.log('Load'); 27 | } 28 | 29 | // Called when an enhanced page update occurs, plus once immediately after 30 | // the initial load. 31 | export function onUpdate() { 32 | console.log('Update'); 33 | } 34 | 35 | // Called when an enhanced page update removes the script from the page. 36 | export function onDispose() { 37 | console.log('Dispose'); 38 | } 39 | ``` 40 | 41 | Take a look at the `samples` folder in this repository for more usage examples. 42 | 43 | ## Expected usage patterns 44 | 45 | ### A `` in a `@page` component 46 | 47 | This is expected to be the most common use case. This allows pages to put initialization logic in `onLoad` and cleanup logic in `onDispose`, while reacting to enhanced page updates in `onUpdate`. 48 | 49 | ### A `` in the application's layout 50 | 51 | A `` placed in the app's layout will get its `onLoad` callback invoked once per full page load and the `onUpdate` callback invoked once per enhanced page update. 52 | 53 | ## Other notes 54 | 55 | Duplicating `` components with the same `Src` won't cause duplicate callback invocations. Likewise, if multiple pages render `` components with the same `Src`, then an enhanced navigation between those pages won't invoke the `onDispose` and `onLoad` callbacks. 56 | 57 | If you want to override this behavior, you can deduplicate two `` components by giving them unique querystring values in their `Src` parameters. For example: 58 | 59 | _Home.razor_ 60 | ```razor 61 | 62 | ``` 63 | 64 | _Counter.razor_ 65 | ```razor 66 | 67 | ``` 68 | -------------------------------------------------------------------------------- /samples/BasicSample/BasicSample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Layout/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 |
4 | Home 5 | Example 6 |
7 | 8 | @Body 9 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Layout/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | #blazor-error-ui { 2 | background: lightyellow; 3 | bottom: 0; 4 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 5 | display: none; 6 | left: 0; 7 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 8 | position: fixed; 9 | width: 100%; 10 | z-index: 1000; 11 | } 12 | 13 | #blazor-error-ui .dismiss { 14 | cursor: pointer; 15 | position: absolute; 16 | right: 0.75rem; 17 | top: 0.5rem; 18 | } 19 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Pages/Error.razor: -------------------------------------------------------------------------------- 1 | @page "/Error" 2 | @using System.Diagnostics 3 | 4 | Error 5 | 6 |

Error.

7 |

An error occurred while processing your request.

8 | 9 | @if (ShowRequestId) 10 | { 11 |

12 | Request ID: @RequestId 13 |

14 | } 15 | 16 |

Development Mode

17 |

18 | Swapping to Development environment will display more detailed information about the error that occurred. 19 |

20 |

21 | The Development environment shouldn't be enabled for deployed applications. 22 | It can result in displaying sensitive information from exceptions to end users. 23 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development 24 | and restarting the app. 25 |

26 | 27 | @code{ 28 | [CascadingParameter] 29 | private HttpContext? HttpContext { get; set; } 30 | 31 | private string? RequestId { get; set; } 32 | private bool ShowRequestId => !string.IsNullOrEmpty(RequestId); 33 | 34 | protected override void OnInitialized() => 35 | RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier; 36 | } 37 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Pages/Example.razor: -------------------------------------------------------------------------------- 1 | @page "/example" 2 | @attribute [StreamRendering] 3 | 4 | Example 5 | 6 | 7 | 8 |

Example

9 | 10 |

11 | This page demonstrates how the @("") component can be used to apply transformations 12 | to the page via JavaScript. 13 |

14 | 15 |

16 | The Example.razor.js file changes the background color of this page and replaces the content 17 | of each of the items below. 18 |

19 | 20 | @for (var i = 0; i < _itemCount; i++) 21 | { 22 |
23 |

Initial content

24 |
25 | } 26 | 27 | @code { 28 | private const int TotalItemCount = 5; 29 | 30 | private int _itemCount; 31 | 32 | protected override async Task OnInitializedAsync() 33 | { 34 | for (var i = 0; i < TotalItemCount; i++) 35 | { 36 | await Task.Delay(500); 37 | _itemCount++; 38 | StateHasChanged(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Pages/Example.razor.js: -------------------------------------------------------------------------------- 1 | let initialBackgroundColor; 2 | 3 | // Called when the script first gets loaded on the page. 4 | export function onLoad() { 5 | initialBackgroundColor = document.body.style.backgroundColor; 6 | } 7 | 8 | // Called when an enhanced page update occurs, plus once immediately after 9 | // the initial load. 10 | export function onUpdate() { 11 | document.body.style.backgroundColor = '#FFF6FF'; 12 | 13 | var itemsNoContent = document.getElementsByClassName('item-initial-content'); 14 | for (const item of Array.from(itemsNoContent)) { 15 | item.className = 'item-js-content'; 16 | item.innerHTML = 'Content from JS!'; 17 | } 18 | } 19 | 20 | // Called when an enhanced page update removes the script from the page. 21 | export function onDispose() { 22 | document.body.style.backgroundColor = initialBackgroundColor; 23 | } 24 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Pages/Home.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | Home 4 | 5 | 6 | 7 |

Basic sample

8 | 9 |

10 | This is an app that demonstrates basic usage of the @("") component. 11 |

12 | 13 |

14 | The script for this page just logs each of the available callbacks. 15 |

16 | 17 |

18 | See the example page for a more interesting example. 19 |

20 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Pages/Home.razor.js: -------------------------------------------------------------------------------- 1 | // Called when the script first gets loaded on the page. 2 | export function onLoad() { 3 | console.log('Home page load'); 4 | } 5 | 6 | // Called when an enhanced page update occurs, plus once immediately after 7 | // the initial load. 8 | export function onUpdate() { 9 | console.log('Home page update'); 10 | } 11 | 12 | // Called when an enhanced page update removes the script from the page. 13 | export function onDispose() { 14 | console.log('Home page dispose'); 15 | } 16 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/Routes.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /samples/BasicSample/Components/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using static Microsoft.AspNetCore.Components.Web.RenderMode 7 | @using Microsoft.AspNetCore.Components.Web.Virtualization 8 | @using Microsoft.JSInterop 9 | @using BasicSample 10 | @using BasicSample.Components 11 | @using BlazorPageScript 12 | -------------------------------------------------------------------------------- /samples/BasicSample/Program.cs: -------------------------------------------------------------------------------- 1 | using BasicSample.Components; 2 | 3 | var builder = WebApplication.CreateBuilder(args); 4 | 5 | // Add services to the container. 6 | builder.Services.AddRazorComponents(); 7 | 8 | var app = builder.Build(); 9 | 10 | // Configure the HTTP request pipeline. 11 | if (!app.Environment.IsDevelopment()) 12 | { 13 | app.UseExceptionHandler("/Error", createScopeForErrors: true); 14 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 15 | app.UseHsts(); 16 | } 17 | 18 | app.UseHttpsRedirection(); 19 | 20 | app.UseStaticFiles(); 21 | app.UseAntiforgery(); 22 | 23 | app.MapRazorComponents(); 24 | 25 | app.Run(); 26 | -------------------------------------------------------------------------------- /samples/BasicSample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:4078", 8 | "sslPort": 44361 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "applicationUrl": "http://localhost:5177", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "applicationUrl": "https://localhost:7145;http://localhost:5177", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "IIS Express": { 31 | "commandName": "IISExpress", 32 | "launchBrowser": true, 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /samples/BasicSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /samples/BasicSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /samples/BasicSample/wwwroot/app.css: -------------------------------------------------------------------------------- 1 | body { 2 | transition-property: background-color; 3 | transition-duration: 0.5s; 4 | } 5 | 6 | h1:focus { 7 | outline: none; 8 | } 9 | 10 | .valid.modified:not([type=checkbox]) { 11 | outline: 1px solid #26b050; 12 | } 13 | 14 | .invalid { 15 | outline: 1px solid #e50000; 16 | } 17 | 18 | .validation-message { 19 | color: #e50000; 20 | } 21 | 22 | .blazor-error-boundary { 23 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 24 | padding: 1rem 1rem 1rem 3.7rem; 25 | color: white; 26 | } 27 | 28 | .blazor-error-boundary::after { 29 | content: "An error has occurred." 30 | } 31 | 32 | .darker-border-checkbox.form-check-input { 33 | border-color: #929292; 34 | } 35 | -------------------------------------------------------------------------------- /src/BlazorPageScript.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | MackinnonBuck 8 | 1.0.0 9 | https://github.com/MackinnonBuck/blazor-page-script.git 10 | README.md 11 | true 12 | true 13 | embedded 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | all 28 | runtime; build; native; contentfiles; analyzers; buildtransitive 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/PageScript.razor: -------------------------------------------------------------------------------- 1 | 2 | 3 | @code { 4 | [Parameter] 5 | [EditorRequired] 6 | public string Src { get; set; } = default!; 7 | } 8 | -------------------------------------------------------------------------------- /src/wwwroot/BlazorPageScript.lib.module.js: -------------------------------------------------------------------------------- 1 | const pageScriptInfoBySrc = new Map(); 2 | 3 | function registerPageScriptElement(src) { 4 | if (!src) { 5 | throw new Error('Must provide a non-empty value for the "src" attribute.'); 6 | } 7 | 8 | let pageScriptInfo = pageScriptInfoBySrc.get(src); 9 | 10 | if (pageScriptInfo) { 11 | pageScriptInfo.referenceCount++; 12 | } else { 13 | pageScriptInfo = { referenceCount: 1, module: null }; 14 | pageScriptInfoBySrc.set(src, pageScriptInfo); 15 | initializePageScriptModule(src, pageScriptInfo); 16 | } 17 | } 18 | 19 | function unregisterPageScriptElement(src) { 20 | if (!src) { 21 | return; 22 | } 23 | 24 | const pageScriptInfo = pageScriptInfoBySrc.get(src); 25 | if (!pageScriptInfo) { 26 | return; 27 | } 28 | 29 | pageScriptInfo.referenceCount--; 30 | } 31 | 32 | async function initializePageScriptModule(src, pageScriptInfo) { 33 | // If the path is relative, normalize it by by making it an absolute URL 34 | // with document's the base HREF. 35 | if (src.startsWith("./")) { 36 | src = new URL(src.substr(2), document.baseURI).toString(); 37 | } 38 | 39 | const module = await import(src); 40 | 41 | if (pageScriptInfo.referenceCount <= 0) { 42 | // All page-script elements with the same 'src' were 43 | // unregistered while we were loading the module. 44 | return; 45 | } 46 | 47 | pageScriptInfo.module = module; 48 | module.onLoad?.(); 49 | module.onUpdate?.(); 50 | } 51 | 52 | function onEnhancedLoad() { 53 | // Start by invoking 'onDispose' on any modules that are no longer referenced. 54 | for (const [src, { module, referenceCount }] of pageScriptInfoBySrc) { 55 | if (referenceCount <= 0) { 56 | module?.onDispose?.(); 57 | pageScriptInfoBySrc.delete(src); 58 | } 59 | } 60 | 61 | // Then invoke 'onUpdate' on the remaining modules. 62 | for (const { module } of pageScriptInfoBySrc.values()) { 63 | module?.onUpdate?.(); 64 | } 65 | } 66 | 67 | export function afterWebStarted(blazor) { 68 | customElements.define('page-script', class extends HTMLElement { 69 | static observedAttributes = ['src']; 70 | 71 | // We use attributeChangedCallback instead of connectedCallback 72 | // because a page-script element might get reused between enhanced 73 | // navigations. 74 | attributeChangedCallback(name, oldValue, newValue) { 75 | if (name !== 'src') { 76 | return; 77 | } 78 | 79 | this.src = newValue; 80 | unregisterPageScriptElement(oldValue); 81 | registerPageScriptElement(newValue); 82 | } 83 | 84 | disconnectedCallback() { 85 | unregisterPageScriptElement(this.src); 86 | } 87 | }); 88 | 89 | blazor.addEventListener('enhancedload', onEnhancedLoad); 90 | } 91 | --------------------------------------------------------------------------------