├── .github └── workflows │ └── main.yml ├── .gitignore ├── Blazor.ServiceWorker.sln ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── samples └── KristofferStrube.Blazor.ServiceWorker.WasmExample │ ├── App.razor │ ├── KristofferStrube.Blazor.ServiceWorker.WasmExample.csproj │ ├── Logger.cs │ ├── Pages │ ├── DownloadFile.razor │ ├── FetchIntercept.razor │ ├── Index.razor │ ├── PostThroughWorker.razor │ ├── Registration.razor │ └── Status.razor │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Shared │ ├── MainLayout.razor │ ├── MainLayout.razor.css │ ├── NavMenu.razor │ └── NavMenu.razor.css │ ├── _Imports.razor │ └── wwwroot │ ├── 404.html │ ├── css │ ├── app.css │ ├── bootstrap │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.css.map │ └── open-iconic │ │ ├── FONT-LICENSE │ │ ├── ICON-LICENSE │ │ ├── README.md │ │ └── font │ │ ├── css │ │ └── open-iconic-bootstrap.min.css │ │ └── fonts │ │ ├── open-iconic.eot │ │ ├── open-iconic.otf │ │ ├── open-iconic.svg │ │ ├── open-iconic.ttf │ │ └── open-iconic.woff │ ├── download │ ├── lighthouse.jpg │ ├── mountain.jpg │ └── snow.jpg │ ├── empty.html │ ├── favicon.png │ ├── icon-192.png │ ├── images │ ├── lighthouse.jpg │ ├── mountain.jpg │ └── snow.jpg │ ├── index.html │ └── service-worker.js └── src └── KristofferStrube.Blazor.ServiceWorker ├── BaseJSWrapper.cs ├── Dictionaries └── NavigationPreloadState.cs ├── EnumDescriptionConverter.cs ├── Enums ├── ServiceWorkerState.cs ├── ServiceWorkerUpdateViaCache.cs └── WorkerType.cs ├── Events ├── ExtendableEvent.cs ├── ExtendableMessageEvent.cs ├── FetchEvent.cs ├── InstallEvent.cs └── PushEvent.cs ├── Extensions ├── IJSObjectReferenceExtensions.cs ├── IJSRuntimeExtensions.cs ├── IServiceCollectionExtensions.cs └── MemoizerExtension.cs ├── INavigatorService.cs ├── Json.cs ├── KristofferStrube.Blazor.ServiceWorker.csproj ├── NavigationPreloadManager.cs ├── NavigatorService.cs ├── Options ├── BodyInit.cs ├── CacheQueryOptions.cs ├── MultiCacheQueryOptions.cs ├── RegistrationOptions.cs ├── Request.cs ├── RequestInfo.cs ├── RequestInit.cs └── ResponseInit.cs ├── ScriptManager.cs ├── ServiceWorker.cs ├── ServiceWorkerContainer.cs ├── ServiceWorkerGloabalScopeProxies ├── BaseJSProxy.cs ├── CacheProxy.cs ├── CacheStorageProxy.cs ├── ClientsProxy.cs ├── HeadersProxy.cs ├── IProxyCreatable.cs ├── JsonProxy.cs ├── PushMessageDataProxy.cs ├── ReadableStreamProxy.cs ├── ResponsePromiseProxy.cs ├── ResponseProxy.cs └── ServiceWorkerGlobalScopeProxy.cs ├── ServiceWorkerRegistration.cs ├── _Imports.razor └── wwwroot ├── KristofferStrube.Blazor.ServiceWorker.Script.js └── KristofferStrube.Blazor.ServiceWorker.js /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: 'Publish application' 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - '**/README.md' 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | # Checkout the code 15 | - uses: actions/checkout@v2 16 | 17 | # Install .NET 7.0 SDK 18 | - name: Setup .NET 7 preview 19 | uses: actions/setup-dotnet@v1 20 | with: 21 | dotnet-version: '7.0.x' 22 | include-prerelease: true 23 | 24 | # Generate the website 25 | - name: Publish 26 | run: dotnet publish samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/KristofferStrube.Blazor.ServiceWorker.WasmExample.csproj --configuration Release --output build 27 | 28 | # Publish the website 29 | - name: GitHub Pages action 30 | if: ${{ github.ref == 'refs/heads/main' }} # Publish only when the push is on main 31 | uses: peaceiris/actions-gh-pages@v3.6.1 32 | with: 33 | github_token: ${{ secrets.PUBLISH_TOKEN }} 34 | publish_branch: gh-pages 35 | publish_dir: build/wwwroot 36 | allow_empty_commit: false 37 | keep_files: false 38 | force_orphan: true 39 | -------------------------------------------------------------------------------- /.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/master/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 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Blazor.ServiceWorker.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}") = "KristofferStrube.Blazor.ServiceWorker", "src\KristofferStrube.Blazor.ServiceWorker\KristofferStrube.Blazor.ServiceWorker.csproj", "{1ECE2A84-8928-44C5-BEDC-750686F1858A}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.Blazor.ServiceWorker.WasmExample", "samples\KristofferStrube.Blazor.ServiceWorker.WasmExample\KristofferStrube.Blazor.ServiceWorker.WasmExample.csproj", "{D6600533-8EF0-4CA5-B133-3C3ACFA9AE8A}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {1ECE2A84-8928-44C5-BEDC-750686F1858A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {1ECE2A84-8928-44C5-BEDC-750686F1858A}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {1ECE2A84-8928-44C5-BEDC-750686F1858A}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {1ECE2A84-8928-44C5-BEDC-750686F1858A}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {D6600533-8EF0-4CA5-B133-3C3ACFA9AE8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {D6600533-8EF0-4CA5-B133-3C3ACFA9AE8A}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {D6600533-8EF0-4CA5-B133-3C3ACFA9AE8A}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {D6600533-8EF0-4CA5-B133-3C3ACFA9AE8A}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {E0E34FF7-593E-45C3-A643-0B9E211789DE} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | Contributing includes many different actions. It is not only writing code. Contributions like discussing solutions in open issues are easily as valuable as contributing code as we can then find the best solution with the perspective of multiple people. 3 | 4 | ## Bugs and feature requests 5 | If you find any bugs in the project or have requests for features, then please [Open a new Issue](https://github.com/KristofferStrube/Blazor.Relewise/issues/new). 6 | 7 | ## Contributing Code and Samples 8 | Before you contribute to the project, you will need to get confirmation from the library author that the contribution is welcome. 9 | This can help align the scope of the contribution so that you and the author agree on the solution and how you ensure the change is maintainable with the existing users in mind. 10 | Once you are ready to start coding try to follow these code guidelines: 11 | - Make a fork of the current `main` branch. 12 | - Follow the existing coding conventions used in the project. This includes tab style, naming conventions, etc. 13 | - If your contribution is a new feature, try to add a demo that demonstrates how this will be used in the sample project. 14 | - Any code or sample you share as a part of the resulting Pull Request should fall under the MIT license agreement. 15 | - You don't need to update the version number of the project as the maintainer will do this when making the next release after the Pull Request has been merged. 16 | - Keep your Pull Request to the point. I.e., if your Pull Request is related to fixing a bug then try not to touch any other files than the ones related to that issue as this will make the chance of the PR being merged without change requests more likely. 17 | 18 | ## Submitting a Pull Request 19 | If you don't know what a pull request is, read this article: https://help.github.com/articles/using-pull-requests. Make sure the repository can be built and that the related sample project still works as intended. It is also a good idea to familiarize yourself with the project workflow and our coding conventions. 20 | 21 | ## Ensuring that your contribution will be accepted 22 | You might also read these two blog posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't "Push" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. These blog posts highlight good open-source collaboration etiquette and help align expectations between you and us. 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Kristoffer Strube 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 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](/LICENSE.md) 2 | [![GitHub issues](https://img.shields.io/github/issues/KristofferStrube/Blazor.ServiceWorker)](https://github.com/KristofferStrube/Blazor.ServiceWorker/issues) 3 | [![GitHub forks](https://img.shields.io/github/forks/KristofferStrube/Blazor.ServiceWorker)](https://github.com/KristofferStrube/Blazor.ServiceWorker/network/members) 4 | [![GitHub stars](https://img.shields.io/github/stars/KristofferStrube/Blazor.ServiceWorker)](https://github.com/KristofferStrube/Blazor.ServiceWorker/stargazers) 5 | 6 | 7 | 8 | # Introduction 9 | A Blazor wrapper for the [Service Workers](https://www.w3.org/TR/service-workers/) API. 10 | 11 | The API makes it possible to interact with and register a Service Worker that can control the fetching of resources for the website before any other contexts exist. This enables developers to make Progressive Web Apps (PWA). This project implements a wrapper around the API for Blazor so that we can easily and safely interact with and create Service Workers. 12 | 13 | **This wrapper is still being developed, so support is very limited.** 14 | 15 | # Demo 16 | The sample project can be demoed at https://kristofferstrube.github.io/Blazor.ServiceWorker/ 17 | 18 | On each page you can find the corresponding code for the example in the top right corner. 19 | 20 | On the [API Coverage Status](https://kristofferstrube.github.io/Blazor.ServiceWorker/Status) page you can get an overview over what parts of the API we support currently. 21 | 22 | # Getting Started 23 | A limitation of statically served Service Workers is that they only have access to the scope that the actual file belong in. 24 | So we need to place the Service Worker interop bootstrapper in the root of our project. You can find that [here](https://github.com/KristofferStrube/Blazor.ServiceWorker/blob/main/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/service-worker.js), but the content is pretty simple: 25 | ```js 26 | importScripts("_content/KristofferStrube.Blazor.ServiceWorker/KristofferStrube.Blazor.ServiceWorker.Script.js") 27 | ``` 28 | 29 | Then once we have copied the script to the root of `wwwroot` in our project we can register a service worker like so: 30 | 31 | ```csharp 32 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 33 | 34 | // other services added and root components configured 35 | 36 | builder.Services.AddNavigatorService(); 37 | 38 | var app = builder.Build(); 39 | 40 | var navigator = app.Services.GetRequiredService(); 41 | var serviceWorker = await navigator.GetServiceWorkerAsync(); 42 | var rootPath = ""; 43 | 44 | await serviceWorker.RegisterAsync("./service-worker.js", rootPath, async (scope) => { 45 | scope.OnActivate = async () => 46 | { 47 | Console.WriteLine("We will do something when activating!"); 48 | }; 49 | }); 50 | ``` 51 | 52 | # Issues 53 | Feel free to open issues on the repository if you find any errors with the package or have wishes for features. 54 | 55 | # Related repositories 56 | This project uses the *Blazor.FileAPI* to return rich Blob objects in certain scenarios. 57 | - https://github.com/KristofferStrube/Blazor.FileAPI 58 | 59 | # Related articles 60 | This repository was build with inspiration and help from the following series of articles: 61 | 62 | - [How to communicate with Service Workers](https://felixgerschau.com/how-to-communicate-with-service-workers/) 63 | - [Wrapping JavaScript libraries in Blazor WebAssembly/WASM](https://blog.elmah.io/wrapping-javascript-libraries-in-blazor-webassembly-wasm/) 64 | - [Call anonymous C# functions from JS in Blazor WASM](https://blog.elmah.io/call-anonymous-c-functions-from-js-in-blazor-wasm/) 65 | - [Using JS Object References in Blazor WASM to wrap JS libraries](https://blog.elmah.io/using-js-object-references-in-blazor-wasm-to-wrap-js-libraries/) 66 | - [Blazor WASM 404 error and fix for GitHub Pages](https://blog.elmah.io/blazor-wasm-404-error-and-fix-for-github-pages/) 67 | - [How to fix Blazor WASM base path problems](https://blog.elmah.io/how-to-fix-blazor-wasm-base-path-problems/) 68 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | Not found 8 | 9 |

Sorry, there's nothing at this address.

10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/KristofferStrube.Blazor.ServiceWorker.WasmExample.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | true 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Logger.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.ServiceWorker.WasmExample 2 | { 3 | public class Logger 4 | { 5 | private string log; 6 | 7 | public void WriteLine(string message) 8 | { 9 | log = DateTime.UtcNow.ToLongTimeString() + ": " + message + "\n" + log; 10 | OnChange?.Invoke(); 11 | } 12 | 13 | public Action? OnChange { get; set; } 14 | 15 | public string Log => log; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Pages/DownloadFile.razor: -------------------------------------------------------------------------------- 1 | @page "/DownloadFile" 2 | @inject HttpClient HttpClient 3 | 4 | ServiceWorker - Download File as stream 5 | 6 |

Download File as stream

7 |

8 | On this page we use that we have setup configuration in Program.cs to intercept any URLs that contains "download/" and intead return the file referenced as a ReadableStream and with a new name. 9 |
10 | We can't intercept outgoing links with the wrapper normally, but if we append the url with #outgoing we can specifically state that it should do it anyway. 11 |

12 | 13 | download/lighthouse.jpg#outgoing 14 |
15 | download/mountain.jpg#outgoing 16 |
17 | download/snow.jpg#outgoing -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Pages/FetchIntercept.razor: -------------------------------------------------------------------------------- 1 | @page "/FetchIntercept" 2 | 3 | ServiceWorker - Fetch Intercept 4 | 5 |

Fetch Intercept

6 | The below images should be mountains, but the Service Worker will replace each with either an image of snow or a lighthouse. 7 |
8 | 9 | 10 |
<img src="images/mountain.jpg?id=@ids[0]" style="max-width:45%; max-height:30vh;" />
11 | <img src="images/mountain.jpg?id=@ids[1]" style="max-width:45%; max-height:30vh;" />
12 | <img src="images/mountain.jpg?id=@ids[2]" style="max-width:45%; max-height:30vh;" />
13 | <img src="images/mountain.jpg?id=@ids[3]" style="max-width:45%; max-height:30vh;" />
14 |
15 | 16 | 17 | 18 | 19 | 20 | @code { 21 | string[] ids = Enumerable.Range(0, 4).Select(_ => Guid.NewGuid().ToString().Substring(0, 4)).ToArray(); 22 | 23 | protected override void OnAfterRender(bool firstRender) 24 | { 25 | ids = Enumerable.Range(0, 4).Select(_ => Guid.NewGuid().ToString().Substring(0, 4)).ToArray(); 26 | } 27 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Pages/Index.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | @inject Logger logger 4 | 5 | ServiceWorker 6 | 7 |

Log of Service Worker events

8 | 9 | 10 | 11 | @code { 12 | protected override void OnInitialized() 13 | { 14 | logger.OnChange = StateHasChanged; 15 | } 16 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Pages/PostThroughWorker.razor: -------------------------------------------------------------------------------- 1 | @page "/PostThroughWorker" 2 | @using KristofferStrube.Blazor.Streams 3 | @inject INavigatorService NavigatorService 4 | @inject IJSRuntime JSRuntime 5 | @inject HttpClient HttpClient 6 | 7 | Post Through Worker 8 | 9 |

Post Through Worker

10 |

On this page we create a ReadableStream from a Stream and then transfer that to the worker thread which then posts it to an API. This makes it so that the expensive work of sending these requests is done in a separate thread.

11 | 12 | 13 | @code { 14 | ServiceWorkerContainer container = default!; 15 | ServiceWorkerRegistration registration = default!; 16 | ServiceWorker? serviceWorker; 17 | 18 | public async Task SendReadableStream() 19 | { 20 | // Get Service Worker 21 | container = await NavigatorService.GetServiceWorkerAsync(); 22 | registration = await container.GetReadyAsync(); 23 | serviceWorker = await registration.GetActiveAsync(); 24 | if (serviceWorker is null) return; 25 | 26 | // Create ReadableStream from a Stream. 27 | var data = await HttpClient.GetStreamAsync("images/snow.jpg"); 28 | using var streamRef = new DotNetStreamReference(stream: data, leaveOpen: false); 29 | var jSStreamReference = await JSRuntime.InvokeAsync("jSStreamReference", streamRef); 30 | var readableStream = await ReadableStreamInProcess.CreateAsync(JSRuntime, jSStreamReference); 31 | 32 | // Create a JSON object with a type and payload 33 | var json = await Json.CreateAsync(JSRuntime); 34 | await json.SetAttributeAsync("type", "test"); 35 | await json.SetAttributeAsync("payload", readableStream.JSReference); 36 | 37 | // Post the JSON object to the service worker and transfer ownership of the ReadableStream as well. 38 | await serviceWorker.PostMessageAsync(json, transfer: new IJSObjectReference[] { readableStream.JSReference }); 39 | } 40 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Pages/Registration.razor: -------------------------------------------------------------------------------- 1 | @page "/Registration" 2 | 3 | @inject INavigatorService NavigatorService 4 | 5 | ServiceWorker - Registration 6 | 7 |

Registration

8 | 9 | 10 | @if (updateAvailable) 11 | { 12 | 13 | } 14 | else 15 | { 16 | 17 | } 18 |
19 | Status: @status
20 | Scope: @scope 21 | 22 | @code { 23 | ServiceWorkerContainer container = default!; 24 | ServiceWorkerRegistration? registration; 25 | bool updateAvailable; 26 | string status = ""; 27 | string scope = ""; 28 | 29 | protected override async Task OnAfterRenderAsync(bool firstRender) 30 | { 31 | if (!firstRender) return; 32 | container = await NavigatorService.GetServiceWorkerAsync(); 33 | registration = await container.GetReadyAsync(); 34 | registration.OnUpdateFound = async () => 35 | { 36 | updateAvailable = true; 37 | await Task.CompletedTask; 38 | }; 39 | await UpdateStatus(); 40 | } 41 | 42 | async Task UpdateStatus() 43 | { 44 | if (registration is null) 45 | { 46 | status = "Not registered"; 47 | StateHasChanged(); 48 | return; 49 | } 50 | 51 | scope = await registration.GetScopeAsync(); 52 | 53 | var installing = await registration.GetInstallingAsync(); 54 | var waiting = await registration.GetWaitingAsync(); 55 | var active = await registration.GetActiveAsync(); 56 | if (installing is not null) 57 | { 58 | var statusAction = async (ServiceWorker sw) => status = $"{await sw.GetStateAsync()} and is installing."; 59 | await statusAction(installing); 60 | installing.OnStateChange = async () => { await statusAction(installing); StateHasChanged(); }; 61 | } 62 | else if (waiting is not null) 63 | { 64 | var statusAction = async (ServiceWorker sw) => status = $"{await sw.GetStateAsync()} and is waiting."; 65 | await statusAction(waiting); 66 | waiting.OnStateChange = async () => { await statusAction(waiting); StateHasChanged(); }; 67 | } 68 | else if (active is not null) 69 | { 70 | var statusAction = async (ServiceWorker sw) => status = $"{await sw.GetStateAsync()} and is active."; 71 | await statusAction(active); 72 | active.OnStateChange = async () => { await statusAction(active); StateHasChanged(); }; 73 | } 74 | StateHasChanged(); 75 | } 76 | 77 | async Task Unregister() 78 | { 79 | if (registration is not null) await registration.UnregisterAsync(); 80 | } 81 | 82 | async Task Update() 83 | { 84 | if (registration is not null) await registration.UpdateAsync(); 85 | } 86 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Pages/Status.razor: -------------------------------------------------------------------------------- 1 | @page "/Status" 2 | 3 | @inject IJSRuntime JSRuntime 4 | 5 | ServiceWorker - Status 6 | 7 |
@((MarkupString)compareText)
8 | 9 | @code { 10 | private string compareText = ""; 11 | 12 | protected override void OnInitialized() 13 | { 14 | var compareLines = new List(); 15 | var lines = webIDL.Replace("<", "<").Split('\n'); 16 | for (int i = 0; i < lines.Count(); i++) 17 | { 18 | var color = supportedRows.Any(interval => i >= interval.start && i <= interval.end) ? "lightgreen" : "pink"; 19 | compareLines.Add($"""{lines[i]}"""); 20 | } 21 | 22 | compareText = string.Join("", compareLines); 23 | StateHasChanged(); 24 | } 25 | 26 | private (int start, int end)[] supportedRows = new (int start, int end)[] { (1, 1), (9, 9), (21, 46), (53, 59), (62, 62), (71, 92), (96, 100), (164, 164), (174, 174), (203, 210), (212, 212), (218, 225), (228, 228), (231, 235) }; 27 | 28 | private const string webIDL = @"[SecureContext, Exposed=(Window,Worker)] 29 | interface ServiceWorker : EventTarget { 30 | readonly attribute USVString scriptURL; 31 | readonly attribute ServiceWorkerState state; 32 | undefined postMessage(any message, sequence transfer); 33 | undefined postMessage(any message, optional StructuredSerializeOptions options = {}); 34 | 35 | // event 36 | attribute EventHandler onstatechange; 37 | }; 38 | ServiceWorker includes AbstractWorker; 39 | 40 | enum ServiceWorkerState { 41 | ""parsed"", 42 | ""installing"", 43 | ""installed"", 44 | ""activating"", 45 | ""activated"", 46 | ""redundant"" 47 | }; 48 | 49 | [SecureContext, Exposed=(Window,Worker)] 50 | interface ServiceWorkerRegistration : EventTarget { 51 | readonly attribute ServiceWorker? installing; 52 | readonly attribute ServiceWorker? waiting; 53 | readonly attribute ServiceWorker? active; 54 | [SameObject] readonly attribute NavigationPreloadManager navigationPreload; 55 | 56 | readonly attribute USVString scope; 57 | readonly attribute ServiceWorkerUpdateViaCache updateViaCache; 58 | 59 | [NewObject] Promise update(); 60 | [NewObject] Promise unregister(); 61 | 62 | // event 63 | attribute EventHandler onupdatefound; 64 | }; 65 | 66 | enum ServiceWorkerUpdateViaCache { 67 | ""imports"", 68 | ""all"", 69 | ""none"" 70 | }; 71 | 72 | partial interface Navigator { 73 | [SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker; 74 | }; 75 | 76 | partial interface WorkerNavigator { 77 | [SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker; 78 | }; 79 | 80 | [SecureContext, Exposed=(Window,Worker)] 81 | interface ServiceWorkerContainer : EventTarget { 82 | readonly attribute ServiceWorker? controller; 83 | readonly attribute Promise ready; 84 | 85 | [NewObject] Promise register(USVString scriptURL, optional RegistrationOptions options = {}); 86 | 87 | [NewObject] Promise<(ServiceWorkerRegistration or undefined)> getRegistration(optional USVString clientURL = """"); 88 | [NewObject] Promise> getRegistrations(); 89 | 90 | undefined startMessages(); 91 | 92 | 93 | // events 94 | attribute EventHandler oncontrollerchange; 95 | attribute EventHandler onmessage; // event.source of message events is ServiceWorker object 96 | attribute EventHandler onmessageerror; 97 | }; 98 | 99 | dictionary RegistrationOptions { 100 | USVString scope; 101 | WorkerType type = ""classic""; 102 | ServiceWorkerUpdateViaCache updateViaCache = ""imports""; 103 | }; 104 | 105 | [SecureContext, Exposed=(Window,Worker)] 106 | interface NavigationPreloadManager { 107 | Promise enable(); 108 | Promise disable(); 109 | Promise setHeaderValue(ByteString value); 110 | Promise getState(); 111 | }; 112 | 113 | dictionary NavigationPreloadState { 114 | boolean enabled = false; 115 | ByteString headerValue; 116 | }; 117 | 118 | [Global=(Worker,ServiceWorker), Exposed=ServiceWorker] 119 | interface ServiceWorkerGlobalScope : WorkerGlobalScope { 120 | [SameObject] readonly attribute Clients clients; 121 | [SameObject] readonly attribute ServiceWorkerRegistration registration; 122 | [SameObject] readonly attribute ServiceWorker serviceWorker; 123 | 124 | [NewObject] Promise skipWaiting(); 125 | 126 | attribute EventHandler oninstall; 127 | attribute EventHandler onactivate; 128 | attribute EventHandler onfetch; 129 | 130 | attribute EventHandler onmessage; 131 | attribute EventHandler onmessageerror; 132 | }; 133 | 134 | [Exposed=ServiceWorker] 135 | interface Client { 136 | readonly attribute USVString url; 137 | readonly attribute FrameType frameType; 138 | readonly attribute DOMString id; 139 | readonly attribute ClientType type; 140 | undefined postMessage(any message, sequence transfer); 141 | undefined postMessage(any message, optional StructuredSerializeOptions options = {}); 142 | }; 143 | 144 | [Exposed=ServiceWorker] 145 | interface WindowClient : Client { 146 | readonly attribute VisibilityState visibilityState; 147 | readonly attribute boolean focused; 148 | [SameObject] readonly attribute FrozenArray ancestorOrigins; 149 | [NewObject] Promise focus(); 150 | [NewObject] Promise navigate(USVString url); 151 | }; 152 | 153 | enum FrameType { 154 | ""auxiliary"", 155 | ""top-level"", 156 | ""nested"", 157 | ""none"" 158 | }; 159 | 160 | [Exposed=ServiceWorker] 161 | interface Clients { 162 | // The objects returned will be new instances every time 163 | [NewObject] Promise<(Client or undefined)> get(DOMString id); 164 | [NewObject] Promise> matchAll(optional ClientQueryOptions options = {}); 165 | [NewObject] Promise openWindow(USVString url); 166 | [NewObject] Promise claim(); 167 | }; 168 | 169 | dictionary ClientQueryOptions { 170 | boolean includeUncontrolled = false; 171 | ClientType type = ""window""; 172 | }; 173 | 174 | enum ClientType { 175 | ""window"", 176 | ""worker"", 177 | ""sharedworker"", 178 | ""all"" 179 | }; 180 | 181 | [Exposed=ServiceWorker] 182 | interface ExtendableEvent : Event { 183 | constructor(DOMString type, optional ExtendableEventInit eventInitDict = {}); 184 | undefined waitUntil(Promise f); 185 | }; 186 | 187 | dictionary ExtendableEventInit : EventInit { 188 | // Defined for the forward compatibility across the derived events 189 | }; 190 | 191 | [Exposed=ServiceWorker] 192 | interface FetchEvent : ExtendableEvent { 193 | constructor(DOMString type, FetchEventInit eventInitDict); 194 | [SameObject] readonly attribute Request request; 195 | readonly attribute Promise preloadResponse; 196 | readonly attribute DOMString clientId; 197 | readonly attribute DOMString resultingClientId; 198 | readonly attribute DOMString replacesClientId; 199 | readonly attribute Promise handled; 200 | 201 | undefined respondWith(Promise r); 202 | }; 203 | 204 | dictionary FetchEventInit : ExtendableEventInit { 205 | required Request request; 206 | Promise preloadResponse; 207 | DOMString clientId = """"; 208 | DOMString resultingClientId = """"; 209 | DOMString replacesClientId = """"; 210 | Promise handled; 211 | }; 212 | 213 | [Exposed=ServiceWorker] 214 | interface ExtendableMessageEvent : ExtendableEvent { 215 | constructor(DOMString type, optional ExtendableMessageEventInit eventInitDict = {}); 216 | readonly attribute any data; 217 | readonly attribute USVString origin; 218 | readonly attribute DOMString lastEventId; 219 | [SameObject] readonly attribute (Client or ServiceWorker or MessagePort)? source; 220 | readonly attribute FrozenArray ports; 221 | }; 222 | 223 | dictionary ExtendableMessageEventInit : ExtendableEventInit { 224 | any data = null; 225 | USVString origin = """"; 226 | DOMString lastEventId = """"; 227 | (Client or ServiceWorker or MessagePort)? source = null; 228 | sequence ports = []; 229 | }; 230 | 231 | partial interface mixin WindowOrWorkerGlobalScope { 232 | [SecureContext, SameObject] readonly attribute CacheStorage caches; 233 | }; 234 | 235 | [SecureContext, Exposed=(Window,Worker)] 236 | interface Cache { 237 | [NewObject] Promise<(Response or undefined)> match(RequestInfo request, optional CacheQueryOptions options = {}); 238 | [NewObject] Promise> matchAll(optional RequestInfo request, optional CacheQueryOptions options = {}); 239 | [NewObject] Promise add(RequestInfo request); 240 | [NewObject] Promise addAll(sequence requests); 241 | [NewObject] Promise put(RequestInfo request, Response response); 242 | [NewObject] Promise delete(RequestInfo request, optional CacheQueryOptions options = {}); 243 | [NewObject] Promise> keys(optional RequestInfo request, optional CacheQueryOptions options = {}); 244 | }; 245 | 246 | dictionary CacheQueryOptions { 247 | boolean ignoreSearch = false; 248 | boolean ignoreMethod = false; 249 | boolean ignoreVary = false; 250 | }; 251 | 252 | [SecureContext, Exposed=(Window,Worker)] 253 | interface CacheStorage { 254 | [NewObject] Promise<(Response or undefined)> match(RequestInfo request, optional MultiCacheQueryOptions options = {}); 255 | [NewObject] Promise has(DOMString cacheName); 256 | [NewObject] Promise open(DOMString cacheName); 257 | [NewObject] Promise delete(DOMString cacheName); 258 | [NewObject] Promise> keys(); 259 | }; 260 | 261 | dictionary MultiCacheQueryOptions : CacheQueryOptions { 262 | DOMString cacheName; 263 | };"; 264 | 265 | } 266 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.Web; 2 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 3 | using KristofferStrube.Blazor.ServiceWorker; 4 | using KristofferStrube.Blazor.ServiceWorker.WasmExample; 5 | using Microsoft.JSInterop; 6 | using KristofferStrube.Blazor.Streams; 7 | 8 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 9 | builder.RootComponents.Add("#app"); 10 | builder.RootComponents.Add("head::after"); 11 | 12 | builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 13 | builder.Services.AddNavigatorService(); 14 | 15 | // This is a very simple logger. 16 | builder.Services.AddSingleton(); 17 | 18 | var app = builder.Build(); 19 | 20 | var navigator = app.Services.GetRequiredService(); 21 | var logger = app.Services.GetRequiredService(); 22 | var environment = app.Services.GetRequiredService(); 23 | 24 | var rootPath = environment.IsProduction() ? "/Blazor.ServiceWorker" : ""; 25 | 26 | var serviceWorker = await navigator.GetServiceWorkerAsync(); 27 | var registration = await serviceWorker.RegisterAsync("./service-worker.js", rootPath, new Guid("58ada1ca-f125-4665-adc6-d9f76463265c"), async (scope) => 28 | { 29 | scope.OnInstall = async (installEvent) => 30 | { 31 | logger.WriteLine("Started Install!"); 32 | await scope.SkipWaitingAsync(); 33 | logger.WriteLine("Finished Install!"); 34 | }; 35 | scope.OnActivate = async () => 36 | { 37 | logger.WriteLine("Started Activation!"); 38 | await scope.SkipWaitingAsync(); 39 | logger.WriteLine("Finished Activation!"); 40 | }; 41 | scope.OnFetch = async (fetchEvent) => 42 | { 43 | logger.WriteLine("Started Fetch!"); 44 | CacheStorageProxy caches = await scope.GetCachesAsync(); 45 | Request request = await fetchEvent.GetRequestAsync(); 46 | string url = await request.GetURLAsync(); 47 | logger.WriteLine($"We fetched: {url}"); 48 | await fetchEvent.RespondWithAsync(async () => 49 | { 50 | ResponseProxy? response = await caches.MatchAsync(request); 51 | if (response is not null) 52 | { 53 | return response; 54 | } 55 | 56 | if (url.Contains("download/")) 57 | { 58 | response = await scope.FetchAsync(request); 59 | ReadableStreamProxy body = await response.GetBodyAsync(); 60 | return await scope.ConstructResponse(body, new ResponseInit() 61 | { 62 | Headers = new() 63 | { 64 | { "Content-Disposition", $"attachment; filename=\"image_{Random.Shared.Next(9999):D4}.jpg\"" }, 65 | { "Content-Type", "image/png" } 66 | } 67 | }); 68 | } 69 | 70 | if (url.Contains("mountain.jpg")) 71 | { 72 | string replacement = Random.Shared.Next(2) is 1 ? "snow" : "lighthouse"; 73 | return await scope.FetchAsync(url.Replace("mountain", replacement)); 74 | } 75 | 76 | return await scope.FetchAsync(request); 77 | }); 78 | }; 79 | scope.OnPush = async (pushEvent) => 80 | { 81 | logger.WriteLine("We pushed!"); 82 | var messageData = await pushEvent.GetDataAsync(); 83 | var array = await messageData.ArrayBufferAsync(); 84 | var blob = await messageData.BlobAsync(); 85 | var json = await messageData.JsonProxyAsync(); 86 | var text = await messageData.TextAsync(); 87 | logger.WriteLine($"arrayBuffer length: {array.Length}"); 88 | logger.WriteLine($"blob size: {await blob.GetSizeAsync()}"); 89 | logger.WriteLine($"json object as string: {await json.AsStringAsync()}"); 90 | logger.WriteLine($"text: {text}"); 91 | }; 92 | scope.OnMessage = async (messageEvent) => 93 | { 94 | logger.WriteLine("We got a message!"); 95 | var json = await messageEvent.GetDataAsync(); 96 | var type = await json.GetAttributeAsStringAsync("type"); 97 | logger.WriteLine($"The message had type '{type}'!"); 98 | if (type is "test") 99 | { 100 | ReadableStreamProxy payload = await json.GetAttributeProxyAsync("payload"); 101 | await scope.FetchAsync("https://kristoffer-strube.dk/API/receive", 102 | new RequestInit 103 | { 104 | Method = "POST", 105 | Body = payload, 106 | Credentials = "omit", 107 | Duplex = "half" 108 | }); 109 | logger.WriteLine($"The message payload was sent to an API on the Worker Thread using fetch!"); 110 | } 111 | }; 112 | logger.WriteLine("We Initialized!"); 113 | await Task.CompletedTask; 114 | }); 115 | 116 | await app.RunAsync(); -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:3060", 7 | "sslPort": 44365 8 | } 9 | }, 10 | "profiles": { 11 | "http": { 12 | "commandName": "Project", 13 | "dotnetRunMessages": true, 14 | "launchBrowser": true, 15 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 16 | "applicationUrl": "http://localhost:5021", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 26 | "applicationUrl": "https://localhost:7029;http://localhost:5021", 27 | "environmentVariables": { 28 | "ASPNETCORE_ENVIRONMENT": "Development" 29 | } 30 | }, 31 | "IIS Express": { 32 | "commandName": "IISExpress", 33 | "launchBrowser": true, 34 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 35 | "environmentVariables": { 36 | "ASPNETCORE_ENVIRONMENT": "Development" 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Shared/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | @inject NavigationManager NavigationManager 3 | 4 |
5 | 8 | 9 |
10 |
11 | 12 | 13 | 14 |
15 | 16 |
17 | @Body 18 |
19 |
20 |
21 | 22 | 23 | @code { 24 | private string relativeUri => NavigationManager.ToBaseRelativePath(NavigationManager.Uri); 25 | 26 | protected string page => (string.IsNullOrEmpty(relativeUri) ? "Index" : relativeUri) + ".razor"; 27 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Shared/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | .page { 2 | position: relative; 3 | display: flex; 4 | flex-direction: column; 5 | } 6 | 7 | main { 8 | flex: 1; 9 | } 10 | 11 | .sidebar { 12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); 13 | } 14 | 15 | .top-row { 16 | background-color: #f7f7f7; 17 | border-bottom: 1px solid #d6d5d5; 18 | justify-content: flex-end; 19 | height: 3.5rem; 20 | display: flex; 21 | align-items: center; 22 | } 23 | 24 | .top-row ::deep a, .top-row ::deep .btn-link { 25 | white-space: nowrap; 26 | margin-left: 1.5rem; 27 | text-decoration: none; 28 | } 29 | 30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { 31 | text-decoration: underline; 32 | } 33 | 34 | .top-row ::deep a:first-child { 35 | overflow: hidden; 36 | text-overflow: ellipsis; 37 | } 38 | 39 | @media (max-width: 640.98px) { 40 | .top-row:not(.auth) { 41 | display: none; 42 | } 43 | 44 | .top-row.auth { 45 | justify-content: space-between; 46 | } 47 | 48 | .top-row ::deep a, .top-row ::deep .btn-link { 49 | margin-left: 0; 50 | } 51 | } 52 | 53 | @media (min-width: 641px) { 54 | .page { 55 | flex-direction: row; 56 | } 57 | 58 | .sidebar { 59 | width: 250px; 60 | height: 100vh; 61 | position: sticky; 62 | top: 0; 63 | } 64 | 65 | .top-row { 66 | position: sticky; 67 | top: 0; 68 | z-index: 1; 69 | } 70 | 71 | .top-row.auth ::deep a:first-child { 72 | flex: 1; 73 | text-align: right; 74 | width: 0; 75 | } 76 | 77 | .top-row, article { 78 | padding-left: 2rem !important; 79 | padding-right: 1.5rem !important; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Shared/NavMenu.razor: -------------------------------------------------------------------------------- 1 |  9 | 10 | 44 | 45 | @code { 46 | private bool collapseNavMenu = true; 47 | 48 | private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; 49 | 50 | private void ToggleNavMenu() 51 | { 52 | collapseNavMenu = !collapseNavMenu; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/Shared/NavMenu.razor.css: -------------------------------------------------------------------------------- 1 | .navbar-toggler { 2 | background-color: rgba(255, 255, 255, 0.1); 3 | } 4 | 5 | .top-row { 6 | height: 3.5rem; 7 | background-color: rgba(0,0,0,0.4); 8 | } 9 | 10 | .navbar-brand { 11 | font-size: 1.1rem; 12 | } 13 | 14 | .oi { 15 | width: 2rem; 16 | font-size: 1.1rem; 17 | vertical-align: text-top; 18 | top: -2px; 19 | } 20 | 21 | .nav-item { 22 | font-size: 0.9rem; 23 | padding-bottom: 0.5rem; 24 | } 25 | 26 | .nav-item:first-of-type { 27 | padding-top: 1rem; 28 | } 29 | 30 | .nav-item:last-of-type { 31 | padding-bottom: 1rem; 32 | } 33 | 34 | .nav-item ::deep a { 35 | color: #d7d7d7; 36 | border-radius: 4px; 37 | height: 3rem; 38 | display: flex; 39 | align-items: center; 40 | line-height: 3rem; 41 | } 42 | 43 | .nav-item ::deep a.active { 44 | background-color: rgba(255,255,255,0.25); 45 | color: white; 46 | } 47 | 48 | .nav-item ::deep a:hover { 49 | background-color: rgba(255,255,255,0.1); 50 | color: white; 51 | } 52 | 53 | @media (min-width: 641px) { 54 | .navbar-toggler { 55 | display: none; 56 | } 57 | 58 | .collapse { 59 | /* Never collapse the sidebar for wide screens */ 60 | display: block; 61 | } 62 | 63 | .nav-scrollable { 64 | /* Allow sidebar to scroll for tall menus */ 65 | height: calc(100vh - 3.5rem); 66 | overflow-y: auto; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/_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 Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 8 | @using Microsoft.JSInterop 9 | @using KristofferStrube.Blazor.ServiceWorker 10 | @using KristofferStrube.Blazor.ServiceWorker.WasmExample 11 | @using KristofferStrube.Blazor.ServiceWorker.WasmExample.Shared 12 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/404.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Blazor ServiceWorker 6 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | @import url('open-iconic/font/css/open-iconic-bootstrap.min.css'); 2 | 3 | html, body { 4 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 5 | } 6 | 7 | h1:focus { 8 | outline: none; 9 | } 10 | 11 | a, .btn-link { 12 | color: #0071c1; 13 | } 14 | 15 | .btn-primary { 16 | color: #fff; 17 | background-color: #1b6ec2; 18 | border-color: #1861ac; 19 | } 20 | 21 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 22 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 23 | } 24 | 25 | .content { 26 | padding-top: 1.1rem; 27 | } 28 | 29 | .valid.modified:not([type=checkbox]) { 30 | outline: 1px solid #26b050; 31 | } 32 | 33 | .invalid { 34 | outline: 1px solid red; 35 | } 36 | 37 | .validation-message { 38 | color: red; 39 | } 40 | 41 | #blazor-error-ui { 42 | background: lightyellow; 43 | bottom: 0; 44 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 45 | display: none; 46 | left: 0; 47 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 48 | position: fixed; 49 | width: 100%; 50 | z-index: 1000; 51 | } 52 | 53 | #blazor-error-ui .dismiss { 54 | cursor: pointer; 55 | position: absolute; 56 | right: 0.75rem; 57 | top: 0.5rem; 58 | } 59 | 60 | .blazor-error-boundary { 61 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 62 | padding: 1rem 1rem 1rem 3.7rem; 63 | color: white; 64 | } 65 | 66 | .blazor-error-boundary::after { 67 | content: "An error has occurred." 68 | } 69 | 70 | .loading-progress { 71 | position: relative; 72 | display: block; 73 | width: 8rem; 74 | height: 8rem; 75 | margin: 20vh auto 1rem auto; 76 | } 77 | 78 | .loading-progress circle { 79 | fill: none; 80 | stroke: #e0e0e0; 81 | stroke-width: 0.6rem; 82 | transform-origin: 50% 50%; 83 | transform: rotate(-90deg); 84 | } 85 | 86 | .loading-progress circle:last-child { 87 | stroke: #1b6ec2; 88 | stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%; 89 | transition: stroke-dasharray 0.05s ease-in-out; 90 | } 91 | 92 | .loading-progress-text { 93 | position: absolute; 94 | text-align: center; 95 | font-weight: bold; 96 | inset: calc(20vh + 3.25rem) 0 auto 0.2rem; 97 | } 98 | 99 | .loading-progress-text:after { 100 | content: var(--blazor-load-percentage-text, "Loading"); 101 | } 102 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/FONT-LICENSE: -------------------------------------------------------------------------------- 1 | SIL OPEN FONT LICENSE Version 1.1 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | PREAMBLE 6 | The goals of the Open Font License (OFL) are to stimulate worldwide 7 | development of collaborative font projects, to support the font creation 8 | efforts of academic and linguistic communities, and to provide a free and 9 | open framework in which fonts may be shared and improved in partnership 10 | with others. 11 | 12 | The OFL allows the licensed fonts to be used, studied, modified and 13 | redistributed freely as long as they are not sold by themselves. The 14 | fonts, including any derivative works, can be bundled, embedded, 15 | redistributed and/or sold with any software provided that any reserved 16 | names are not used by derivative works. The fonts and derivatives, 17 | however, cannot be released under any other type of license. The 18 | requirement for fonts to remain under this license does not apply 19 | to any document created using the fonts or their derivatives. 20 | 21 | DEFINITIONS 22 | "Font Software" refers to the set of files released by the Copyright 23 | Holder(s) under this license and clearly marked as such. This may 24 | include source files, build scripts and documentation. 25 | 26 | "Reserved Font Name" refers to any names specified as such after the 27 | copyright statement(s). 28 | 29 | "Original Version" refers to the collection of Font Software components as 30 | distributed by the Copyright Holder(s). 31 | 32 | "Modified Version" refers to any derivative made by adding to, deleting, 33 | or substituting -- in part or in whole -- any of the components of the 34 | Original Version, by changing formats or by porting the Font Software to a 35 | new environment. 36 | 37 | "Author" refers to any designer, engineer, programmer, technical 38 | writer or other person who contributed to the Font Software. 39 | 40 | PERMISSION & CONDITIONS 41 | Permission is hereby granted, free of charge, to any person obtaining 42 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 43 | redistribute, and sell modified and unmodified copies of the Font 44 | Software, subject to the following conditions: 45 | 46 | 1) Neither the Font Software nor any of its individual components, 47 | in Original or Modified Versions, may be sold by itself. 48 | 49 | 2) Original or Modified Versions of the Font Software may be bundled, 50 | redistributed and/or sold with any software, provided that each copy 51 | contains the above copyright notice and this license. These can be 52 | included either as stand-alone text files, human-readable headers or 53 | in the appropriate machine-readable metadata fields within text or 54 | binary files as long as those fields can be easily viewed by the user. 55 | 56 | 3) No Modified Version of the Font Software may use the Reserved Font 57 | Name(s) unless explicit written permission is granted by the corresponding 58 | Copyright Holder. This restriction only applies to the primary font name as 59 | presented to the users. 60 | 61 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 62 | Software shall not be used to promote, endorse or advertise any 63 | Modified Version, except to acknowledge the contribution(s) of the 64 | Copyright Holder(s) and the Author(s) or with their explicit written 65 | permission. 66 | 67 | 5) The Font Software, modified or unmodified, in part or in whole, 68 | must be distributed entirely under this license, and must not be 69 | distributed under any other license. The requirement for fonts to 70 | remain under this license does not apply to any document created 71 | using the Font Software. 72 | 73 | TERMINATION 74 | This license becomes null and void if any of the above conditions are 75 | not met. 76 | 77 | DISCLAIMER 78 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 79 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 80 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 81 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 82 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 83 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 84 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 85 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 86 | OTHER DEALINGS IN THE FONT SOFTWARE. 87 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/ICON-LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Waybury 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 13 | all 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 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/README.md: -------------------------------------------------------------------------------- 1 | [Open Iconic v1.1.1](https://github.com/iconic/open-iconic) 2 | =========== 3 | 4 | ### Open Iconic is the open source sibling of [Iconic](https://github.com/iconic/open-iconic). It is a hyper-legible collection of 223 icons with a tiny footprint—ready to use with Bootstrap and Foundation. [View the collection](https://github.com/iconic/open-iconic) 5 | 6 | 7 | 8 | ## What's in Open Iconic? 9 | 10 | * 223 icons designed to be legible down to 8 pixels 11 | * Super-light SVG files - 61.8 for the entire set 12 | * SVG sprite—the modern replacement for icon fonts 13 | * Webfont (EOT, OTF, SVG, TTF, WOFF), PNG and WebP formats 14 | * Webfont stylesheets (including versions for Bootstrap and Foundation) in CSS, LESS, SCSS and Stylus formats 15 | * PNG and WebP raster images in 8px, 16px, 24px, 32px, 48px and 64px. 16 | 17 | 18 | ## Getting Started 19 | 20 | #### For code samples and everything else you need to get started with Open Iconic, check out our [Icons](https://github.com/iconic/open-iconic) and [Reference](https://github.com/iconic/open-iconic) sections. 21 | 22 | ### General Usage 23 | 24 | #### Using Open Iconic's SVGs 25 | 26 | We like SVGs and we think they're the way to display icons on the web. Since Open Iconic are just basic SVGs, we suggest you display them like you would any other image (don't forget the `alt` attribute). 27 | 28 | ``` 29 | icon name 30 | ``` 31 | 32 | #### Using Open Iconic's SVG Sprite 33 | 34 | Open Iconic also comes in a SVG sprite which allows you to display all the icons in the set with a single request. It's like an icon font, without being a hack. 35 | 36 | Adding an icon from an SVG sprite is a little different than what you're used to, but it's still a piece of cake. *Tip: To make your icons easily style able, we suggest adding a general class to the* `` *tag and a unique class name for each different icon in the* `` *tag.* 37 | 38 | ``` 39 | 40 | 41 | 42 | ``` 43 | 44 | Sizing icons only needs basic CSS. All the icons are in a square format, so just set the `` tag with equal width and height dimensions. 45 | 46 | ``` 47 | .icon { 48 | width: 16px; 49 | height: 16px; 50 | } 51 | ``` 52 | 53 | Coloring icons is even easier. All you need to do is set the `fill` rule on the `` tag. 54 | 55 | ``` 56 | .icon-account-login { 57 | fill: #f00; 58 | } 59 | ``` 60 | 61 | To learn more about SVG Sprites, read [Chris Coyier's guide](http://css-tricks.com/svg-sprites-use-better-icon-fonts/). 62 | 63 | #### Using Open Iconic's Icon Font... 64 | 65 | 66 | ##### …with Bootstrap 67 | 68 | You can find our Bootstrap stylesheets in `font/css/open-iconic-bootstrap.{css, less, scss, styl}` 69 | 70 | 71 | ``` 72 | 73 | ``` 74 | 75 | 76 | ``` 77 | 78 | ``` 79 | 80 | ##### …with Foundation 81 | 82 | You can find our Foundation stylesheets in `font/css/open-iconic-foundation.{css, less, scss, styl}` 83 | 84 | ``` 85 | 86 | ``` 87 | 88 | 89 | ``` 90 | 91 | ``` 92 | 93 | ##### …on its own 94 | 95 | You can find our default stylesheets in `font/css/open-iconic.{css, less, scss, styl}` 96 | 97 | ``` 98 | 99 | ``` 100 | 101 | ``` 102 | 103 | ``` 104 | 105 | 106 | ## License 107 | 108 | ### Icons 109 | 110 | All code (including SVG markup) is under the [MIT License](http://opensource.org/licenses/MIT). 111 | 112 | ### Fonts 113 | 114 | All fonts are under the [SIL Licensed](http://scripts.sil.org/cms/scripts/page.php?item_id=OFL_web). 115 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/css/open-iconic-bootstrap.min.css: -------------------------------------------------------------------------------- 1 | @font-face{font-family:Icons;src:url(../fonts/open-iconic.eot);src:url(../fonts/open-iconic.eot?#iconic-sm) format('embedded-opentype'),url(../fonts/open-iconic.woff) format('woff'),url(../fonts/open-iconic.ttf) format('truetype'),url(../fonts/open-iconic.otf) format('opentype'),url(../fonts/open-iconic.svg#iconic-sm) format('svg');font-weight:400;font-style:normal}.oi{position:relative;top:1px;display:inline-block;speak:none;font-family:Icons;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.oi:empty:before{width:1em;text-align:center;box-sizing:content-box}.oi.oi-align-center:before{text-align:center}.oi.oi-align-left:before{text-align:left}.oi.oi-align-right:before{text-align:right}.oi.oi-flip-horizontal:before{-webkit-transform:scale(-1,1);-ms-transform:scale(-1,1);transform:scale(-1,1)}.oi.oi-flip-vertical:before{-webkit-transform:scale(1,-1);-ms-transform:scale(-1,1);transform:scale(1,-1)}.oi.oi-flip-horizontal-vertical:before{-webkit-transform:scale(-1,-1);-ms-transform:scale(-1,1);transform:scale(-1,-1)}.oi-account-login:before{content:'\e000'}.oi-account-logout:before{content:'\e001'}.oi-action-redo:before{content:'\e002'}.oi-action-undo:before{content:'\e003'}.oi-align-center:before{content:'\e004'}.oi-align-left:before{content:'\e005'}.oi-align-right:before{content:'\e006'}.oi-aperture:before{content:'\e007'}.oi-arrow-bottom:before{content:'\e008'}.oi-arrow-circle-bottom:before{content:'\e009'}.oi-arrow-circle-left:before{content:'\e00a'}.oi-arrow-circle-right:before{content:'\e00b'}.oi-arrow-circle-top:before{content:'\e00c'}.oi-arrow-left:before{content:'\e00d'}.oi-arrow-right:before{content:'\e00e'}.oi-arrow-thick-bottom:before{content:'\e00f'}.oi-arrow-thick-left:before{content:'\e010'}.oi-arrow-thick-right:before{content:'\e011'}.oi-arrow-thick-top:before{content:'\e012'}.oi-arrow-top:before{content:'\e013'}.oi-audio-spectrum:before{content:'\e014'}.oi-audio:before{content:'\e015'}.oi-badge:before{content:'\e016'}.oi-ban:before{content:'\e017'}.oi-bar-chart:before{content:'\e018'}.oi-basket:before{content:'\e019'}.oi-battery-empty:before{content:'\e01a'}.oi-battery-full:before{content:'\e01b'}.oi-beaker:before{content:'\e01c'}.oi-bell:before{content:'\e01d'}.oi-bluetooth:before{content:'\e01e'}.oi-bold:before{content:'\e01f'}.oi-bolt:before{content:'\e020'}.oi-book:before{content:'\e021'}.oi-bookmark:before{content:'\e022'}.oi-box:before{content:'\e023'}.oi-briefcase:before{content:'\e024'}.oi-british-pound:before{content:'\e025'}.oi-browser:before{content:'\e026'}.oi-brush:before{content:'\e027'}.oi-bug:before{content:'\e028'}.oi-bullhorn:before{content:'\e029'}.oi-calculator:before{content:'\e02a'}.oi-calendar:before{content:'\e02b'}.oi-camera-slr:before{content:'\e02c'}.oi-caret-bottom:before{content:'\e02d'}.oi-caret-left:before{content:'\e02e'}.oi-caret-right:before{content:'\e02f'}.oi-caret-top:before{content:'\e030'}.oi-cart:before{content:'\e031'}.oi-chat:before{content:'\e032'}.oi-check:before{content:'\e033'}.oi-chevron-bottom:before{content:'\e034'}.oi-chevron-left:before{content:'\e035'}.oi-chevron-right:before{content:'\e036'}.oi-chevron-top:before{content:'\e037'}.oi-circle-check:before{content:'\e038'}.oi-circle-x:before{content:'\e039'}.oi-clipboard:before{content:'\e03a'}.oi-clock:before{content:'\e03b'}.oi-cloud-download:before{content:'\e03c'}.oi-cloud-upload:before{content:'\e03d'}.oi-cloud:before{content:'\e03e'}.oi-cloudy:before{content:'\e03f'}.oi-code:before{content:'\e040'}.oi-cog:before{content:'\e041'}.oi-collapse-down:before{content:'\e042'}.oi-collapse-left:before{content:'\e043'}.oi-collapse-right:before{content:'\e044'}.oi-collapse-up:before{content:'\e045'}.oi-command:before{content:'\e046'}.oi-comment-square:before{content:'\e047'}.oi-compass:before{content:'\e048'}.oi-contrast:before{content:'\e049'}.oi-copywriting:before{content:'\e04a'}.oi-credit-card:before{content:'\e04b'}.oi-crop:before{content:'\e04c'}.oi-dashboard:before{content:'\e04d'}.oi-data-transfer-download:before{content:'\e04e'}.oi-data-transfer-upload:before{content:'\e04f'}.oi-delete:before{content:'\e050'}.oi-dial:before{content:'\e051'}.oi-document:before{content:'\e052'}.oi-dollar:before{content:'\e053'}.oi-double-quote-sans-left:before{content:'\e054'}.oi-double-quote-sans-right:before{content:'\e055'}.oi-double-quote-serif-left:before{content:'\e056'}.oi-double-quote-serif-right:before{content:'\e057'}.oi-droplet:before{content:'\e058'}.oi-eject:before{content:'\e059'}.oi-elevator:before{content:'\e05a'}.oi-ellipses:before{content:'\e05b'}.oi-envelope-closed:before{content:'\e05c'}.oi-envelope-open:before{content:'\e05d'}.oi-euro:before{content:'\e05e'}.oi-excerpt:before{content:'\e05f'}.oi-expand-down:before{content:'\e060'}.oi-expand-left:before{content:'\e061'}.oi-expand-right:before{content:'\e062'}.oi-expand-up:before{content:'\e063'}.oi-external-link:before{content:'\e064'}.oi-eye:before{content:'\e065'}.oi-eyedropper:before{content:'\e066'}.oi-file:before{content:'\e067'}.oi-fire:before{content:'\e068'}.oi-flag:before{content:'\e069'}.oi-flash:before{content:'\e06a'}.oi-folder:before{content:'\e06b'}.oi-fork:before{content:'\e06c'}.oi-fullscreen-enter:before{content:'\e06d'}.oi-fullscreen-exit:before{content:'\e06e'}.oi-globe:before{content:'\e06f'}.oi-graph:before{content:'\e070'}.oi-grid-four-up:before{content:'\e071'}.oi-grid-three-up:before{content:'\e072'}.oi-grid-two-up:before{content:'\e073'}.oi-hard-drive:before{content:'\e074'}.oi-header:before{content:'\e075'}.oi-headphones:before{content:'\e076'}.oi-heart:before{content:'\e077'}.oi-home:before{content:'\e078'}.oi-image:before{content:'\e079'}.oi-inbox:before{content:'\e07a'}.oi-infinity:before{content:'\e07b'}.oi-info:before{content:'\e07c'}.oi-italic:before{content:'\e07d'}.oi-justify-center:before{content:'\e07e'}.oi-justify-left:before{content:'\e07f'}.oi-justify-right:before{content:'\e080'}.oi-key:before{content:'\e081'}.oi-laptop:before{content:'\e082'}.oi-layers:before{content:'\e083'}.oi-lightbulb:before{content:'\e084'}.oi-link-broken:before{content:'\e085'}.oi-link-intact:before{content:'\e086'}.oi-list-rich:before{content:'\e087'}.oi-list:before{content:'\e088'}.oi-location:before{content:'\e089'}.oi-lock-locked:before{content:'\e08a'}.oi-lock-unlocked:before{content:'\e08b'}.oi-loop-circular:before{content:'\e08c'}.oi-loop-square:before{content:'\e08d'}.oi-loop:before{content:'\e08e'}.oi-magnifying-glass:before{content:'\e08f'}.oi-map-marker:before{content:'\e090'}.oi-map:before{content:'\e091'}.oi-media-pause:before{content:'\e092'}.oi-media-play:before{content:'\e093'}.oi-media-record:before{content:'\e094'}.oi-media-skip-backward:before{content:'\e095'}.oi-media-skip-forward:before{content:'\e096'}.oi-media-step-backward:before{content:'\e097'}.oi-media-step-forward:before{content:'\e098'}.oi-media-stop:before{content:'\e099'}.oi-medical-cross:before{content:'\e09a'}.oi-menu:before{content:'\e09b'}.oi-microphone:before{content:'\e09c'}.oi-minus:before{content:'\e09d'}.oi-monitor:before{content:'\e09e'}.oi-moon:before{content:'\e09f'}.oi-move:before{content:'\e0a0'}.oi-musical-note:before{content:'\e0a1'}.oi-paperclip:before{content:'\e0a2'}.oi-pencil:before{content:'\e0a3'}.oi-people:before{content:'\e0a4'}.oi-person:before{content:'\e0a5'}.oi-phone:before{content:'\e0a6'}.oi-pie-chart:before{content:'\e0a7'}.oi-pin:before{content:'\e0a8'}.oi-play-circle:before{content:'\e0a9'}.oi-plus:before{content:'\e0aa'}.oi-power-standby:before{content:'\e0ab'}.oi-print:before{content:'\e0ac'}.oi-project:before{content:'\e0ad'}.oi-pulse:before{content:'\e0ae'}.oi-puzzle-piece:before{content:'\e0af'}.oi-question-mark:before{content:'\e0b0'}.oi-rain:before{content:'\e0b1'}.oi-random:before{content:'\e0b2'}.oi-reload:before{content:'\e0b3'}.oi-resize-both:before{content:'\e0b4'}.oi-resize-height:before{content:'\e0b5'}.oi-resize-width:before{content:'\e0b6'}.oi-rss-alt:before{content:'\e0b7'}.oi-rss:before{content:'\e0b8'}.oi-script:before{content:'\e0b9'}.oi-share-boxed:before{content:'\e0ba'}.oi-share:before{content:'\e0bb'}.oi-shield:before{content:'\e0bc'}.oi-signal:before{content:'\e0bd'}.oi-signpost:before{content:'\e0be'}.oi-sort-ascending:before{content:'\e0bf'}.oi-sort-descending:before{content:'\e0c0'}.oi-spreadsheet:before{content:'\e0c1'}.oi-star:before{content:'\e0c2'}.oi-sun:before{content:'\e0c3'}.oi-tablet:before{content:'\e0c4'}.oi-tag:before{content:'\e0c5'}.oi-tags:before{content:'\e0c6'}.oi-target:before{content:'\e0c7'}.oi-task:before{content:'\e0c8'}.oi-terminal:before{content:'\e0c9'}.oi-text:before{content:'\e0ca'}.oi-thumb-down:before{content:'\e0cb'}.oi-thumb-up:before{content:'\e0cc'}.oi-timer:before{content:'\e0cd'}.oi-transfer:before{content:'\e0ce'}.oi-trash:before{content:'\e0cf'}.oi-underline:before{content:'\e0d0'}.oi-vertical-align-bottom:before{content:'\e0d1'}.oi-vertical-align-center:before{content:'\e0d2'}.oi-vertical-align-top:before{content:'\e0d3'}.oi-video:before{content:'\e0d4'}.oi-volume-high:before{content:'\e0d5'}.oi-volume-low:before{content:'\e0d6'}.oi-volume-off:before{content:'\e0d7'}.oi-warning:before{content:'\e0d8'}.oi-wifi:before{content:'\e0d9'}.oi-wrench:before{content:'\e0da'}.oi-x:before{content:'\e0db'}.oi-yen:before{content:'\e0dc'}.oi-zoom-in:before{content:'\e0dd'}.oi-zoom-out:before{content:'\e0de'} -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.eot -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.otf -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | Created by FontForge 20120731 at Tue Jul 1 20:39:22 2014 9 | By P.J. Onori 10 | Created by P.J. Onori with FontForge 2.0 (http://fontforge.sf.net) 11 | 12 | 13 | 14 | 27 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 45 | 47 | 49 | 51 | 53 | 55 | 57 | 59 | 61 | 63 | 65 | 67 | 69 | 71 | 74 | 76 | 79 | 81 | 84 | 86 | 88 | 91 | 93 | 95 | 98 | 100 | 102 | 104 | 106 | 109 | 112 | 115 | 117 | 121 | 123 | 125 | 127 | 130 | 132 | 134 | 136 | 138 | 141 | 143 | 145 | 147 | 149 | 151 | 153 | 155 | 157 | 159 | 162 | 165 | 167 | 169 | 172 | 174 | 177 | 179 | 181 | 183 | 185 | 189 | 191 | 194 | 196 | 198 | 200 | 202 | 205 | 207 | 209 | 211 | 213 | 215 | 218 | 220 | 222 | 224 | 226 | 228 | 230 | 232 | 234 | 236 | 238 | 241 | 243 | 245 | 247 | 249 | 251 | 253 | 256 | 259 | 261 | 263 | 265 | 267 | 269 | 272 | 274 | 276 | 280 | 282 | 285 | 287 | 289 | 292 | 295 | 298 | 300 | 302 | 304 | 306 | 309 | 312 | 314 | 316 | 318 | 320 | 322 | 324 | 326 | 330 | 334 | 338 | 340 | 343 | 345 | 347 | 349 | 351 | 353 | 355 | 358 | 360 | 363 | 365 | 367 | 369 | 371 | 373 | 375 | 377 | 379 | 381 | 383 | 386 | 388 | 390 | 392 | 394 | 396 | 399 | 401 | 404 | 406 | 408 | 410 | 412 | 414 | 416 | 419 | 421 | 423 | 425 | 428 | 431 | 435 | 438 | 440 | 442 | 444 | 446 | 448 | 451 | 453 | 455 | 457 | 460 | 462 | 464 | 466 | 468 | 471 | 473 | 477 | 479 | 481 | 483 | 486 | 488 | 490 | 492 | 494 | 496 | 499 | 501 | 504 | 506 | 509 | 512 | 515 | 517 | 520 | 522 | 524 | 526 | 529 | 532 | 534 | 536 | 539 | 542 | 543 | 544 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.woff -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/download/lighthouse.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/download/lighthouse.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/download/mountain.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/download/mountain.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/download/snow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/download/snow.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/empty.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Blazor ServiceWorker 6 | 7 | 8 |

Oh no, we don't have internet. 🤦‍

9 | 10 | 11 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/favicon.png -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/icon-192.png -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/images/lighthouse.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/images/lighthouse.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/images/mountain.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/images/mountain.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/images/snow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.ServiceWorker/f1bc59b0aac9e5b4af8f8af43ba667c53b0dccb6/samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/images/snow.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Blazor.ServiceWorker 8 | 9 | 10 | 32 | 43 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 |
54 | 55 | 56 | 57 | 58 |
59 |
60 | 61 |
62 | An unhandled error has occurred. 63 | Reload 64 | 🗙 65 |
66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.ServiceWorker.WasmExample/wwwroot/service-worker.js: -------------------------------------------------------------------------------- 1 | importScripts("_content/KristofferStrube.Blazor.ServiceWorker/KristofferStrube.Blazor.ServiceWorker.Script.js") -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/BaseJSWrapper.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.ServiceWorker; 6 | 7 | public abstract class BaseJSWrapper : IJSWrapper, IAsyncDisposable 8 | { 9 | protected readonly Lazy> helperTask; 10 | 11 | public IJSRuntime JSRuntime { get; } 12 | public IJSObjectReference JSReference { get; } 13 | 14 | /// 15 | /// Constructs a wrapper instance for an equivalent JS instance. 16 | /// 17 | /// An instance. 18 | /// A JS reference to an existing JS instance that should be wrapped. 19 | public BaseJSWrapper(IJSRuntime jSRuntime, IJSObjectReference jSReference) 20 | { 21 | helperTask = new(jSRuntime.GetHelperAsync); 22 | JSRuntime = jSRuntime; 23 | JSReference = jSReference; 24 | } 25 | 26 | public async ValueTask DisposeAsync() 27 | { 28 | if (helperTask.IsValueCreated) 29 | { 30 | IJSObjectReference module = await helperTask.Value; 31 | await module.DisposeAsync(); 32 | } 33 | GC.SuppressFinalize(this); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Dictionaries/NavigationPreloadState.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class NavigationPreloadState 6 | { 7 | [JsonPropertyName("enabled")] 8 | public bool Enabled { get; set; } 9 | 10 | [JsonPropertyName("headerValue")] 11 | public byte[] HeaderValue { get; set; } = Array.Empty(); 12 | } 13 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/EnumDescriptionConverter.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace KristofferStrube.Blazor.ServiceWorker; 7 | 8 | #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. 9 | #pragma warning disable CS8603 // Possible null reference return. 10 | #pragma warning disable CS8604 // Possible null reference argument. 11 | #pragma warning disable CS8602 // Dereference of a possibly null reference. 12 | public class EnumDescriptionConverter : JsonConverter where T : IComparable, IFormattable, IConvertible 13 | { 14 | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 15 | { 16 | string jsonValue = reader.GetString(); 17 | 18 | foreach (FieldInfo? fi in typeToConvert.GetFields()) 19 | { 20 | DescriptionAttribute description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false); 21 | 22 | if (description != null) 23 | { 24 | if (description.Description == jsonValue) 25 | { 26 | return (T)fi.GetValue(null); 27 | } 28 | } 29 | } 30 | throw new JsonException($"string {jsonValue} was not found as a description in the enum {typeToConvert}"); 31 | } 32 | 33 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) 34 | { 35 | FieldInfo fi = value.GetType().GetField(value.ToString()); 36 | 37 | DescriptionAttribute description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false); 38 | 39 | writer.WriteStringValue(description.Description); 40 | } 41 | } 42 | #pragma warning restore CS8602 // Dereference of a possibly null reference. 43 | #pragma warning restore CS8604 // Possible null reference argument. 44 | #pragma warning restore CS8603 // Possible null reference return. 45 | #pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Enums/ServiceWorkerState.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | [JsonConverter(typeof(EnumDescriptionConverter))] 7 | public enum ServiceWorkerState 8 | { 9 | [Description("parsed")] 10 | Parsed, 11 | [Description("installing")] 12 | Installing, 13 | [Description("installed")] 14 | Installed, 15 | [Description("activating")] 16 | Activating, 17 | [Description("activated")] 18 | Activated, 19 | [Description("redundant")] 20 | Redundant, 21 | } 22 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Enums/ServiceWorkerUpdateViaCache.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | [JsonConverter(typeof(EnumDescriptionConverter))] 7 | public enum ServiceWorkerUpdateViaCache 8 | { 9 | [Description("imports")] 10 | Imports, 11 | [Description("all")] 12 | All, 13 | [Description("none")] 14 | None, 15 | } 16 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Enums/WorkerType.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | [JsonConverter(typeof(EnumDescriptionConverter))] 7 | public enum WorkerType 8 | { 9 | [Description("classic")] 10 | Classic, 11 | [Description("module")] 12 | Module, 13 | } 14 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Events/ExtendableEvent.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class ExtendableEvent : BaseJSProxy 6 | { 7 | public ExtendableEvent(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | public async Task WaitUntil(Func f) 11 | { 12 | await f(); 13 | await ResolveProxy(Id); 14 | } 15 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Events/ExtendableMessageEvent.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class ExtendableMessageEvent : ExtendableEvent 6 | { 7 | public ExtendableMessageEvent(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task GetDataAsync() 12 | { 13 | await container.StartMessagesAsync(); 14 | Guid objectId = await GetProxyAttributeAsProxy("data"); 15 | return new JsonProxy(jSRuntime, objectId, container); 16 | } 17 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Events/FetchEvent.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class FetchEvent : BaseJSProxy 6 | { 7 | public FetchEvent(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task GetRequestAsync() 12 | { 13 | await container.StartMessagesAsync(); 14 | Guid objectId = await GetProxyAttributeAsProxy("request"); 15 | return new Request(jSRuntime, objectId, container); 16 | } 17 | 18 | public async Task RespondWithAsync(Func> r) 19 | { 20 | ResponseProxy response = await r(); 21 | await ResolveProxy(Id, response.Id.ToString()); 22 | } 23 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Events/InstallEvent.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class InstallEvent : ExtendableEvent 6 | { 7 | public InstallEvent(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Events/PushEvent.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class PushEvent : BaseJSProxy 6 | { 7 | public PushEvent(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task GetDataAsync() 12 | { 13 | await container.StartMessagesAsync(); 14 | Guid objectId = await GetProxyAttributeAsProxy("data"); 15 | return new PushMessageDataProxy(jSRuntime, objectId, container); 16 | } 17 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Extensions/IJSObjectReferenceExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | 3 | public static class IJSObjectReferenceExtensions 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Extensions/IJSRuntimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker.Extensions; 4 | 5 | public static class IJSRuntimeExtensions 6 | { 7 | public static async Task GetHelperAsync(this IJSRuntime jSRuntime) 8 | { 9 | return await jSRuntime.InvokeAsync( 10 | "import", "./_content/KristofferStrube.Blazor.ServiceWorker/KristofferStrube.Blazor.ServiceWorker.js"); 11 | } 12 | 13 | public static async Task GetInProcessHelperAsync(this IJSRuntime jSRuntime) 14 | { 15 | return await jSRuntime.InvokeAsync( 16 | "import", "./_content/KristofferStrube.Blazor.ServiceWorker/KristofferStrube.Blazor.ServiceWorker.js"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Extensions/IServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public static class IServiceCollectionExtensions 6 | { 7 | public static IServiceCollection AddNavigatorService(this IServiceCollection serviceCollection) 8 | { 9 | return serviceCollection.AddScoped(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Extensions/MemoizerExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker.Extensions; 5 | 6 | /// Adopted from this StackOverflow answer. 7 | public static class MemoizerExtension 8 | { 9 | public static ConditionalWeakTable> _weakCache = new(); 10 | 11 | public static Task MemoizedTask( 12 | this object context, 13 | Func> f, 14 | [CallerMemberName] string? cacheKey = null) 15 | { 16 | ArgumentNullException.ThrowIfNull(context); 17 | ArgumentNullException.ThrowIfNull(cacheKey); 18 | 19 | ConcurrentDictionary methodCaches = _weakCache.GetOrCreateValue(context); 20 | 21 | ConcurrentDictionary> methodCache = (ConcurrentDictionary>)methodCaches 22 | .GetOrAdd(cacheKey, _ => new ConcurrentDictionary>()); 23 | return methodCache.GetOrAdd(cacheKey, _ => f()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/INavigatorService.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.ServiceWorker 2 | { 3 | public interface INavigatorService 4 | { 5 | Task GetServiceWorkerAsync(); 6 | } 7 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Json.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.ServiceWorker; 6 | 7 | public class Json : BaseJSWrapper, IJSCreatable 8 | { 9 | public static async Task CreateAsync(IJSRuntime jSRuntime) 10 | { 11 | var helper = await jSRuntime.GetHelperAsync(); 12 | var jSInstance = await helper.InvokeAsync("constructJsonObject"); 13 | return new(jSRuntime, jSInstance); 14 | } 15 | 16 | public static Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 17 | { 18 | return Task.FromResult(new Json(jSRuntime, jSReference)); 19 | } 20 | 21 | public Json(IJSRuntime jSRuntime, IJSObjectReference jSReference) : base(jSRuntime, jSReference) 22 | { 23 | } 24 | 25 | public async Task AsStringAsync() 26 | { 27 | return await JSReference.InvokeAsync("valueOf"); 28 | } 29 | 30 | public async Task GetAttributeAsync(string attribute) 31 | { 32 | var helper = await helperTask.Value; 33 | var jSInstance = await helper.InvokeAsync("getAttribute", JSReference, attribute); 34 | return new Json(JSRuntime, jSInstance); 35 | } 36 | 37 | public async Task GetAttributeAsStringAsync(string attribute) 38 | { 39 | var helper = await helperTask.Value; 40 | return await helper.InvokeAsync("getAttribute", JSReference, attribute); 41 | } 42 | 43 | public async Task SetAttributeAsync(string attribute, IJSObjectReference value) 44 | { 45 | var helper = await helperTask.Value; 46 | await helper.InvokeVoidAsync("setAttribute", JSReference, attribute, value); 47 | } 48 | 49 | public async Task SetAttributeAsync(string attribute, IJSWrapper value) 50 | { 51 | var helper = await helperTask.Value; 52 | await helper.InvokeVoidAsync("setAttribute", JSReference, attribute, value.JSReference); 53 | } 54 | 55 | public async Task SetAttributeAsync(string attribute, string value) 56 | { 57 | var helper = await helperTask.Value; 58 | await helper.InvokeVoidAsync("setAttribute", JSReference, attribute, value); 59 | } 60 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/KristofferStrube.Blazor.ServiceWorker.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/NavigationPreloadManager.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class NavigationPreloadManager : BaseJSWrapper 6 | { 7 | public NavigationPreloadManager(IJSRuntime jSRuntime, IJSObjectReference jSReference) : base(jSRuntime, jSReference) 8 | { 9 | } 10 | 11 | public async Task EnableAsync() 12 | { 13 | await JSReference.InvokeVoidAsync("enable"); 14 | } 15 | 16 | public async Task DisableAsync() 17 | { 18 | await JSReference.InvokeVoidAsync("disable"); 19 | } 20 | 21 | /// 22 | /// Sets the preload header value. The initial value is 'true'. 23 | /// 24 | /// It is important that the value is a ByteString. This can be interpreted as UTF-8 string. 25 | /// Check out the C# 11 language feature called UTF-8 String Literals. 26 | public async Task SetHeaderValueAsync(byte[] value) 27 | { 28 | await JSReference.InvokeVoidAsync("setHeaderValue", value); 29 | } 30 | 31 | public async Task GetStateAsync() 32 | { 33 | return await JSReference.InvokeAsync("getState"); 34 | } 35 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/NavigatorService.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class NavigatorService : INavigatorService 7 | { 8 | protected readonly Lazy> helperTask; 9 | protected readonly IJSRuntime jSRuntime; 10 | 11 | public NavigatorService(IJSRuntime jSRuntime) 12 | { 13 | helperTask = new(() => jSRuntime.GetHelperAsync()); 14 | this.jSRuntime = jSRuntime; 15 | } 16 | 17 | public async Task GetServiceWorkerAsync() 18 | { 19 | return await this.MemoizedTask(async () => 20 | { 21 | IJSObjectReference helper = await helperTask.Value; 22 | IJSObjectReference jSNavigator = await helper.InvokeAsync("getNavigator"); 23 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttribute", jSNavigator, "serviceWorker"); 24 | return new ServiceWorkerContainer(jSRuntime, jSInstance); 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/BodyInit.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.Streams; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class BodyInit 6 | { 7 | public readonly object value; 8 | 9 | public BodyInit(ReadableStreamProxy value) 10 | { 11 | this.value = value; 12 | } 13 | 14 | public static implicit operator BodyInit(ReadableStreamProxy value) 15 | { 16 | return new(value); 17 | } 18 | 19 | public static implicit operator string(BodyInit bi) 20 | { 21 | return bi.value switch 22 | { 23 | ReadableStreamProxy value => value.Id.ToString(), 24 | _ => throw new InvalidCastException("Constructed with wrong type.") 25 | }; 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/CacheQueryOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class CacheQueryOptions 6 | { 7 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 8 | [JsonPropertyName("ignoreSearch")] 9 | public bool IgnoreSearch { get; set; } 10 | 11 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 12 | [JsonPropertyName("ignoreMethod")] 13 | public bool IgnoreMethod { get; set; } 14 | 15 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 16 | [JsonPropertyName("ignoreVary")] 17 | public bool IgnoreVary { get; set; } 18 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/MultiCacheQueryOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class MultiCacheQueryOptions : CacheQueryOptions 6 | { 7 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 8 | [JsonPropertyName("cacheName")] 9 | public string? CacheName { get; set; } 10 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/RegistrationOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class RegistrationOptions 6 | { 7 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 8 | [JsonPropertyName("scope")] 9 | public string? Scope { get; set; } 10 | 11 | [JsonPropertyName("type")] 12 | public WorkerType Type { get; set; } = WorkerType.Classic; 13 | 14 | [JsonPropertyName("updateViaCache")] 15 | public ServiceWorkerUpdateViaCache UpdateViaCache { get; set; } = ServiceWorkerUpdateViaCache.Imports; 16 | } 17 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/Request.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class Request : BaseJSProxy 6 | { 7 | public Request(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task GetURLAsync() 12 | { 13 | return await GetProxyAttribute("url"); 14 | } 15 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/RequestInfo.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.ServiceWorker; 2 | 3 | public class RequestInfo 4 | { 5 | public readonly object value; 6 | 7 | public RequestInfo(Request value) 8 | { 9 | this.value = value; 10 | } 11 | public RequestInfo(string value) 12 | { 13 | this.value = value; 14 | } 15 | 16 | public static implicit operator RequestInfo(Request value) 17 | { 18 | return new(value); 19 | } 20 | 21 | public static implicit operator RequestInfo(string value) 22 | { 23 | return new(value); 24 | } 25 | 26 | public static implicit operator string(RequestInfo ri) 27 | { 28 | return ri.value switch 29 | { 30 | Request request => request.Id.ToString(), 31 | string request => request, 32 | _ => throw new InvalidCastException("Constructed with wrong type.") 33 | }; 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/RequestInit.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.ServiceWorker; 2 | 3 | public class RequestInit 4 | { 5 | public string Method { get; set; } = "GET"; 6 | public BodyInit Body { get; set; } 7 | public string Credentials { get; set; } 8 | public bool KeepAlive { get; set; } = false; 9 | public string Duplex { get; set; } 10 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/Options/ResponseInit.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class ResponseInit 6 | { 7 | [JsonPropertyName("status")] 8 | public short Status { get; set; } = 200; 9 | 10 | [JsonPropertyName("headers")] 11 | public Dictionary Headers { get; set; } = new(); 12 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ScriptManager.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public static class ScriptManager 6 | { 7 | private static readonly Dictionary scripts = new(); 8 | 9 | public static async Task AddScriptAsync(Guid id, IJSRuntime jSRuntime, ServiceWorkerContainer container, Func script) 10 | { 11 | ServiceWorkerGlobalScopeProxy scope = new(jSRuntime, id, container); 12 | await script(scope); 13 | scripts.Add(id, new(jSRuntime, container, scope, script)); 14 | } 15 | 16 | [JSInvokable] 17 | public static async Task InvokeOnInstallAsync(string stringId, string eventId) 18 | { 19 | if (Guid.TryParse(stringId, out Guid id) && 20 | scripts.TryGetValue(id, out ExecutionContext? context) && 21 | context.Scope.OnInstall is not null) 22 | { 23 | await context.Scope.OnInstall.Invoke(new InstallEvent(context.JSRuntime, Guid.Parse(eventId), context.Container)); 24 | } 25 | } 26 | 27 | [JSInvokable] 28 | public static async Task InvokeOnActivateAsync(string stringId, string _) 29 | { 30 | if (Guid.TryParse(stringId, out Guid id) 31 | && scripts.TryGetValue(id, out ExecutionContext? context) 32 | && context.Scope.OnActivate is not null) 33 | { 34 | await context.Scope.OnActivate.Invoke(); 35 | } 36 | } 37 | 38 | [JSInvokable] 39 | public static async Task InvokeOnFetchAsync(string stringId, string eventId) 40 | { 41 | if (Guid.TryParse(stringId, out Guid id) && 42 | scripts.TryGetValue(id, out ExecutionContext? context) && 43 | context.Scope.OnFetch is not null) 44 | { 45 | await context.Scope.OnFetch.Invoke(new FetchEvent(context.JSRuntime, Guid.Parse(eventId), context.Container)); 46 | } 47 | } 48 | 49 | [JSInvokable] 50 | public static async Task InvokeOnPushAsync(string stringId, string eventId) 51 | { 52 | if (Guid.TryParse(stringId, out Guid id) && 53 | scripts.TryGetValue(id, out ExecutionContext? context) && 54 | context.Scope.OnPush is not null) 55 | { 56 | await context.Scope.OnPush.Invoke(new PushEvent(context.JSRuntime, Guid.Parse(eventId), context.Container)); 57 | } 58 | } 59 | 60 | [JSInvokable] 61 | public static async Task InvokeOnMessageAsync(string stringId, string eventId) 62 | { 63 | if (Guid.TryParse(stringId, out Guid id) && 64 | scripts.TryGetValue(id, out ExecutionContext? context) && 65 | context.Scope.OnMessage is not null) 66 | { 67 | await context.Scope.OnMessage.Invoke(new ExtendableMessageEvent(context.JSRuntime, Guid.Parse(eventId), context.Container)); 68 | } 69 | } 70 | } 71 | 72 | public class ExecutionContext 73 | { 74 | public IJSRuntime JSRuntime; 75 | public ServiceWorkerContainer Container; 76 | public ServiceWorkerGlobalScopeProxy Scope; 77 | public Func Script; 78 | 79 | public ExecutionContext(IJSRuntime jSRuntime, ServiceWorkerContainer container, ServiceWorkerGlobalScopeProxy scope, Func script) 80 | { 81 | JSRuntime = jSRuntime; 82 | Container = container; 83 | Scope = scope; 84 | Script = script; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorker.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.ServiceWorker; 6 | 7 | public class ServiceWorker : BaseJSWrapper 8 | { 9 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 10 | { 11 | IJSObjectReference helper = await jSRuntime.GetHelperAsync(); 12 | ServiceWorker serviceWorker = new(jSRuntime, jSReference); 13 | await helper.InvokeVoidAsync("registerEventHandlerAsync", DotNetObjectReference.Create(serviceWorker), jSReference, "statechange", "InvokeOnStateChange"); 14 | return serviceWorker; 15 | } 16 | 17 | public ServiceWorker(IJSRuntime jSRuntime, IJSObjectReference jSReference) : base(jSRuntime, jSReference) 18 | { 19 | } 20 | 21 | public async Task GetScriptURLAsync() 22 | { 23 | IJSObjectReference helper = await helperTask.Value; 24 | return await helper.InvokeAsync("getAttribute", JSReference, "scriptURL"); 25 | } 26 | 27 | public async Task GetStateAsync() 28 | { 29 | IJSObjectReference helper = await helperTask.Value; 30 | return await helper.InvokeAsync("getAttribute", JSReference, "state"); 31 | } 32 | 33 | public async Task PostMessageAsync(Json json, IJSWrapper[]? transfer = null) 34 | { 35 | if (transfer is null) 36 | { 37 | await JSReference.InvokeVoidAsync("postMessage", json.JSReference); 38 | } 39 | else 40 | { 41 | await JSReference.InvokeVoidAsync("postMessage", json.JSReference, transfer.Select(t => t.JSReference).ToArray()); 42 | } 43 | } 44 | 45 | public async Task PostMessageAsync(Json json, IJSObjectReference[] transfer) 46 | { 47 | await JSReference.InvokeVoidAsync("postMessage", json.JSReference, transfer); 48 | } 49 | 50 | public Func? OnStateChange { get; set; } 51 | 52 | public async Task InvokeOnStateChange() 53 | { 54 | if (OnStateChange is null) 55 | { 56 | return; 57 | } 58 | 59 | await OnStateChange(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerContainer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | using Microsoft.JSInterop.Infrastructure; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class ServiceWorkerContainer : BaseJSWrapper 7 | { 8 | public ServiceWorkerContainer(IJSRuntime jSRuntime, IJSObjectReference jSReference) : base(jSRuntime, jSReference) 9 | { 10 | } 11 | 12 | public async Task GetControllerAsync() 13 | { 14 | IJSObjectReference helper = await helperTask.Value; 15 | if (await helper.InvokeAsync("isAttributeNullOrUndefined", JSReference, "controller")) 16 | { 17 | return null; 18 | } 19 | 20 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttribute", JSReference, "controller"); 21 | return new ServiceWorker(JSRuntime, jSInstance); 22 | } 23 | 24 | public async Task GetReadyAsync() 25 | { 26 | IJSObjectReference helper = await helperTask.Value; 27 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttributeAsync", JSReference, "ready"); 28 | return new ServiceWorkerRegistration(JSRuntime, jSInstance); 29 | } 30 | 31 | public async Task RegisterAsync(string scriptURL, RegistrationOptions? options = null) 32 | { 33 | IJSObjectReference jSInstance = await JSReference.InvokeAsync("register", scriptURL, options); 34 | return new ServiceWorkerRegistration(JSRuntime, jSInstance); 35 | } 36 | 37 | public async Task RegisterAsync(string scriptBootstrapperURL, string rootPath, Guid id, Func script) 38 | { 39 | await ScriptManager.AddScriptAsync(id, JSRuntime, this, async (scope) => 40 | { 41 | await script(scope); 42 | await scope.InitialBlazorHandshake(); 43 | }); 44 | IJSObjectReference helper = await helperTask.Value; 45 | await helper.InvokeVoidAsync("registerMessageListener", JSReference); 46 | IJSObjectReference jSInstance = await JSReference.InvokeAsync("register", $"{scriptBootstrapperURL}?id={id}&root={rootPath}", new RegistrationOptions() { Type = WorkerType.Classic, UpdateViaCache = ServiceWorkerUpdateViaCache.Imports }); 47 | var registration = new ServiceWorkerRegistration(JSRuntime, jSInstance); 48 | return registration; 49 | } 50 | 51 | public async Task GetRegistrationAsync(string clientURL = "") 52 | { 53 | IJSObjectReference jSInstance = await JSReference.InvokeAsync("getRegistration", clientURL); 54 | return new ServiceWorkerRegistration(JSRuntime, jSInstance); 55 | } 56 | 57 | public async Task StartMessagesAsync() 58 | { 59 | await JSReference.InvokeVoidAsync("startMessages"); 60 | } 61 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/BaseJSProxy.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using Microsoft.JSInterop; 3 | using System; 4 | 5 | namespace KristofferStrube.Blazor.ServiceWorker; 6 | 7 | public abstract class BaseJSProxy 8 | { 9 | protected readonly IJSRuntime jSRuntime; 10 | protected readonly Lazy> helperTask; 11 | protected readonly ServiceWorkerContainer container; 12 | 13 | public BaseJSProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) 14 | { 15 | this.jSRuntime = jSRuntime; 16 | helperTask = new(jSRuntime.GetHelperAsync); 17 | this.container = container; 18 | Id = id; 19 | } 20 | 21 | public Guid Id { get; set; } 22 | 23 | public async Task GetProxyAttributeAsProxy(string attribute) 24 | { 25 | IJSObjectReference helper = await helperTask.Value; 26 | return Guid.Parse(await helper.InvokeAsync("getProxyAttributeAsProxy", container.JSReference, Guid.NewGuid(), Id, attribute)); 27 | } 28 | 29 | public async Task GetProxyAsyncAttributeAsProxy(string attribute) 30 | { 31 | IJSObjectReference helper = await helperTask.Value; 32 | return Guid.Parse(await helper.InvokeAsync("getProxyAsyncAttributeAsProxy", container.JSReference, Guid.NewGuid(), Id, attribute)); 33 | } 34 | 35 | public async Task GetProxyAttribute(string attribute) 36 | { 37 | IJSObjectReference helper = await helperTask.Value; 38 | return await helper.InvokeAsync("getProxyAttribute", container.JSReference, Guid.NewGuid(), Id, attribute); 39 | } 40 | 41 | public async Task CallProxyMethodAsProxy(string method, params object[]? args) 42 | { 43 | args ??= Array.Empty(); 44 | IJSObjectReference helper = await helperTask.Value; 45 | return Guid.Parse(await helper.InvokeAsync("callProxyMethodAsProxy", container.JSReference, Guid.NewGuid(), Id, method, args)); 46 | } 47 | 48 | public async Task CallProxyAsyncMethodAsProxy(string method, params object[]? args) 49 | { 50 | args ??= Array.Empty(); 51 | IJSObjectReference helper = await helperTask.Value; 52 | return Guid.Parse(await helper.InvokeAsync("callProxyAsyncMethodAsProxy", container.JSReference, Guid.NewGuid(), Id, method, args)); 53 | } 54 | 55 | public async Task CallProxyAsyncMethodAsNullableProxy(string method, params object[]? args) 56 | { 57 | args ??= Array.Empty(); 58 | IJSObjectReference helper = await helperTask.Value; 59 | string proxyObjectId = await helper.InvokeAsync("callProxyAsyncMethodAsProxy", container.JSReference, Guid.NewGuid(), Id, method, args); 60 | bool isUndefined = await helper.InvokeAsync("isUndefined", proxyObjectId); 61 | if (isUndefined) 62 | { 63 | return null; 64 | } 65 | return Guid.Parse(proxyObjectId); 66 | } 67 | 68 | public async Task CallProxyMethod(string method, params object[]? args) 69 | { 70 | args ??= Array.Empty(); 71 | IJSObjectReference helper = await helperTask.Value; 72 | return await helper.InvokeAsync("callProxyMethod", container.JSReference, Guid.NewGuid(), Id, method, args); 73 | } 74 | 75 | public async Task CallProxyConstructorAsProxy(string name, params object[]? args) 76 | { 77 | args ??= Array.Empty(); 78 | IJSObjectReference helper = await helperTask.Value; 79 | return Guid.Parse(await helper.InvokeAsync("callProxyConstructorAsProxy", container.JSReference, Guid.NewGuid(), Id, name, args)); 80 | } 81 | 82 | public async Task ResolveProxy(Guid objectId, params object[]? args) 83 | { 84 | IJSObjectReference helper = await helperTask.Value; 85 | await helper.InvokeVoidAsync("resolveProxy", container.JSReference, objectId, args); 86 | } 87 | 88 | internal async Task InitialBlazorHandshake() 89 | { 90 | IJSObjectReference helper = await helperTask.Value; 91 | await helper.InvokeVoidAsync("initialBlazorHandshake", container.JSReference); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/CacheProxy.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class CacheProxy : BaseJSProxy 6 | { 7 | public CacheProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task AddAsync(RequestInfo request) 12 | { 13 | await container.StartMessagesAsync(); 14 | await CallProxyAsyncMethodAsNullableProxy("add", new string[] { request }); 15 | } 16 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/CacheStorageProxy.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class CacheStorageProxy : BaseJSProxy 6 | { 7 | public CacheStorageProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task MatchAsync(RequestInfo request, MultiCacheQueryOptions? options = null) 12 | { 13 | await container.StartMessagesAsync(); 14 | Guid? objectId = await CallProxyAsyncMethodAsNullableProxy("match", new object[] { (string)request, options }); 15 | if (objectId is Guid id) 16 | { 17 | return new ResponseProxy(jSRuntime, id, container); 18 | } 19 | return null; 20 | } 21 | 22 | public async Task OpenAsync(string cacheName) 23 | { 24 | await container.StartMessagesAsync(); 25 | Guid objectId = await CallProxyAsyncMethodAsProxy("open", new object[] { cacheName }); 26 | return new CacheProxy(jSRuntime, objectId, container); 27 | } 28 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/ClientsProxy.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class ClientsProxy : BaseJSProxy 6 | { 7 | public ClientsProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task ClaimAsync() 12 | { 13 | await CallProxyAsyncMethodAsNullableProxy("claim"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/HeadersProxy.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class HeadersProxy : BaseJSProxy 6 | { 7 | public HeadersProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task AppendAsync(string name, string value) 12 | { 13 | await CallProxyMethod("append", name, value); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/IProxyCreatable.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker.ServiceWorkerGloabalScopeProxies; 4 | 5 | public interface IProxyCreatable where TProxy : IProxyCreatable 6 | { 7 | public static abstract TProxy Create(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container); 8 | } 9 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/JsonProxy.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.ServiceWorkerGloabalScopeProxies; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class JsonProxy : BaseJSProxy 7 | { 8 | public JsonProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 9 | { 10 | } 11 | 12 | public async Task AsStringAsync() 13 | { 14 | return await CallProxyMethod("valueOf"); 15 | } 16 | 17 | public async Task GetAttributeProxyAsync(string attribute) 18 | { 19 | Guid objectId = await GetProxyAttributeAsProxy(attribute); 20 | return new JsonProxy(jSRuntime, objectId, container); 21 | } 22 | 23 | public async Task GetAttributeProxyAsync(string attribute) where T : IProxyCreatable 24 | { 25 | Guid objectId = await GetProxyAttributeAsProxy(attribute); 26 | return T.Create(jSRuntime, objectId, container); 27 | } 28 | 29 | public async Task GetAttributeAsStringAsync(string attribute) 30 | { 31 | return await GetProxyAttribute(attribute); 32 | } 33 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/PushMessageDataProxy.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileAPI; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class PushMessageDataProxy : BaseJSProxy 7 | { 8 | public PushMessageDataProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 9 | { 10 | } 11 | 12 | public async Task ArrayBufferAsync() 13 | { 14 | IJSObjectReference helper = await helperTask.Value; 15 | IJSObjectReference jSInstance = await CallProxyMethod("arrayBuffer"); 16 | return await helper.InvokeAsync("arrayBuffer", jSInstance); 17 | } 18 | 19 | public async Task BlobAsync() 20 | { 21 | IJSObjectReference jSInstance = await CallProxyMethod("blob"); 22 | return Blob.Create(jSRuntime, jSInstance); 23 | } 24 | 25 | public async Task JsonProxyAsync() 26 | { 27 | Guid objectId = await CallProxyMethodAsProxy("json"); 28 | return new JsonProxy(jSRuntime, objectId, container); 29 | } 30 | 31 | public async Task TextAsync() 32 | { 33 | return await CallProxyMethod("text"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/ReadableStreamProxy.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.ServiceWorkerGloabalScopeProxies; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class ReadableStreamProxy : BaseJSProxy, IProxyCreatable 7 | { 8 | public ReadableStreamProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 9 | { 10 | } 11 | 12 | public static ReadableStreamProxy Create(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) 13 | { 14 | return new ReadableStreamProxy(jSRuntime, id, container); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/ResponsePromiseProxy.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class ResponsePromiseProxy 6 | { 7 | private readonly Func> r; 8 | 9 | public ResponsePromiseProxy(Func> r) 10 | { 11 | this.r = r; 12 | ObjRef = DotNetObjectReference.Create(this); 13 | } 14 | 15 | public DotNetObjectReference ObjRef { get; set; } 16 | 17 | [JSInvokable] 18 | public async Task Invoke() 19 | { 20 | return (await r()).Id; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/ResponseProxy.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.ServiceWorker; 4 | 5 | public class ResponseProxy : BaseJSProxy 6 | { 7 | public ResponseProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 8 | { 9 | } 10 | 11 | public async Task GetStatusAsync() 12 | { 13 | return await GetProxyAttribute("status"); 14 | } 15 | 16 | public async Task GetURLAsync() 17 | { 18 | return await GetProxyAttribute("url"); 19 | } 20 | 21 | public async Task GetHeadersAsync() 22 | { 23 | var id = await GetProxyAttributeAsProxy("headers"); 24 | return new HeadersProxy(jSRuntime, id, container); 25 | } 26 | 27 | public async Task GetBodyAsync() 28 | { 29 | var id = await GetProxyAttributeAsProxy("body"); 30 | return new ReadableStreamProxy(jSRuntime, id, container); 31 | } 32 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerGloabalScopeProxies/ServiceWorkerGlobalScopeProxy.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class ServiceWorkerGlobalScopeProxy : BaseJSProxy 7 | { 8 | public ServiceWorkerGlobalScopeProxy(IJSRuntime jSRuntime, Guid id, ServiceWorkerContainer container) : base(jSRuntime, id, container) 9 | { 10 | } 11 | 12 | public Func? OnInstall { get; set; } 13 | 14 | public Func? OnActivate { get; set; } 15 | 16 | public Func? OnFetch { get; set; } 17 | 18 | public Func? OnPush { get; set; } 19 | 20 | public Func? OnMessage { get; set; } 21 | 22 | public async Task GetClientsAsync() 23 | { 24 | return await this.MemoizedTask(async () => 25 | { 26 | Guid objectId = await GetProxyAttributeAsProxy("clients"); 27 | return new ClientsProxy(jSRuntime, objectId, container); 28 | }); 29 | } 30 | 31 | public async Task SkipWaitingAsync() 32 | { 33 | await CallProxyAsyncMethodAsNullableProxy("skipWaiting"); 34 | } 35 | 36 | public async Task GetCachesAsync() 37 | { 38 | return await this.MemoizedTask(async () => 39 | { 40 | Guid objectId = await GetProxyAttributeAsProxy("caches"); 41 | return new CacheStorageProxy(jSRuntime, objectId, container); 42 | }); 43 | } 44 | 45 | public async Task FetchAsync(RequestInfo input, RequestInit? init = null) 46 | { 47 | if (init is not null) 48 | { 49 | Guid objectId = await CallProxyAsyncMethodAsProxy( 50 | "fetch", 51 | new object[] { 52 | (string)input, 53 | new { 54 | method = init.Method, 55 | body = (string)init.Body, 56 | credentials = init.Credentials, 57 | keepalive = init.KeepAlive, 58 | duplex = init.Duplex 59 | } 60 | }); 61 | return new ResponseProxy(jSRuntime, objectId, container); 62 | } 63 | else 64 | { 65 | Guid objectId = await CallProxyAsyncMethodAsProxy("fetch", new object[] { (string)input}); 66 | return new ResponseProxy(jSRuntime, objectId, container); 67 | } 68 | } 69 | 70 | public async Task ConstructResponse(string body, ResponseInit? init = null) 71 | { 72 | Guid objectId = await CallProxyConstructorAsProxy("Response", body, init); 73 | return new ResponseProxy(jSRuntime, objectId, container); 74 | } 75 | 76 | public async Task ConstructResponse(ReadableStreamProxy body, ResponseInit? init = null) 77 | { 78 | Guid objectId = await CallProxyConstructorAsProxy("Response", body.Id, init); 79 | return new ResponseProxy(jSRuntime, objectId, container); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/ServiceWorkerRegistration.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.ServiceWorker.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.ServiceWorker; 5 | 6 | public class ServiceWorkerRegistration : BaseJSWrapper 7 | { 8 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 9 | { 10 | IJSObjectReference helper = await jSRuntime.GetHelperAsync(); 11 | ServiceWorkerRegistration serviceWorkerRegistration = new(jSRuntime, jSReference); 12 | await helper.InvokeVoidAsync("registerEventHandlerAsync", DotNetObjectReference.Create(serviceWorkerRegistration), jSReference, "updatefound", "InvokeOnUpdateFound"); 13 | return serviceWorkerRegistration; 14 | } 15 | 16 | public ServiceWorkerRegistration(IJSRuntime jSRuntime, IJSObjectReference jSReference) : base(jSRuntime, jSReference) 17 | { 18 | } 19 | 20 | public async Task GetInstallingAsync() 21 | { 22 | IJSObjectReference helper = await helperTask.Value; 23 | if (await helper.InvokeAsync("isAttributeNullOrUndefined", JSReference, "installing")) 24 | { 25 | return null; 26 | } 27 | 28 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttribute", JSReference, "installing"); 29 | return new ServiceWorker(JSRuntime, jSInstance); 30 | } 31 | 32 | public async Task GetWaitingAsync() 33 | { 34 | IJSObjectReference helper = await helperTask.Value; 35 | if (await helper.InvokeAsync("isAttributeNullOrUndefined", JSReference, "waiting")) 36 | { 37 | return null; 38 | } 39 | 40 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttribute", JSReference, "waiting"); 41 | return new ServiceWorker(JSRuntime, jSInstance); 42 | } 43 | 44 | public async Task GetActiveAsync() 45 | { 46 | IJSObjectReference helper = await helperTask.Value; 47 | if (await helper.InvokeAsync("isAttributeNullOrUndefined", JSReference, "active")) 48 | { 49 | return null; 50 | } 51 | 52 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttribute", JSReference, "active"); 53 | return new ServiceWorker(JSRuntime, jSInstance); 54 | } 55 | 56 | public async Task GetNavigationPreloadAsync() 57 | { 58 | return await this.MemoizedTask(async () => 59 | { 60 | IJSObjectReference helper = await helperTask.Value; 61 | IJSObjectReference jSInstance = await helper.InvokeAsync("getAttribute", JSReference, "navigationPreload"); 62 | return new NavigationPreloadManager(JSRuntime, jSInstance); 63 | }); 64 | } 65 | 66 | public async Task GetScopeAsync() 67 | { 68 | IJSObjectReference helper = await helperTask.Value; 69 | return await helper.InvokeAsync("getAttribute", JSReference, "scope"); 70 | } 71 | 72 | public async Task GetUpdateViaCacheAsync() 73 | { 74 | IJSObjectReference helper = await helperTask.Value; 75 | return await helper.InvokeAsync("getAttribute", JSReference, "updateViaCache"); 76 | } 77 | 78 | public async Task UpdateAsync() 79 | { 80 | await JSReference.InvokeVoidAsync("update"); 81 | } 82 | 83 | public async Task UnregisterAsync() 84 | { 85 | return await JSReference.InvokeAsync("unregister"); 86 | } 87 | 88 | public Func? OnUpdateFound { get; set; } 89 | 90 | [JSInvokable] 91 | public async Task InvokeOnUpdateFound() 92 | { 93 | if (OnUpdateFound is null) 94 | { 95 | return; 96 | } 97 | 98 | await OnUpdateFound(); 99 | } 100 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Components.Web 2 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/wwwroot/KristofferStrube.Blazor.ServiceWorker.Script.js: -------------------------------------------------------------------------------- 1 | const params = new Proxy(new URLSearchParams(self.location.search), { 2 | get: (searchParams, prop) => searchParams.get(prop), 3 | }); 4 | let id = params.id; 5 | let root = self.location.origin + params.root + "/"; 6 | let receivedInitialBlazorHandshakes = []; 7 | 8 | const proxyHandler = { 9 | construct(target, args) { 10 | return new target(...args); 11 | }, 12 | }; 13 | 14 | let proxyDict = {}; 15 | proxyDict[id] = self; 16 | 17 | let resolvers = {}; 18 | 19 | self.oninstall = (event) => { 20 | invokePost("Install", generateGUID(), event); 21 | } 22 | self.onactivate = (event) => { 23 | invokePost("Activate", generateGUID(), event); 24 | } 25 | self.onfetch = (event) => { 26 | if (receivedInitialBlazorHandshakes.includes(event.clientId) || event.request.url.endsWith("#outgoing")) { 27 | event.respondWith(handleFetch(event)); 28 | } 29 | } 30 | 31 | async function handleFetch(event) { 32 | var id = generateGUID(); 33 | var promise = new Promise((resolve, _) => { 34 | resolvers[id] = resolve; 35 | }); 36 | invokePost("Fetch", id, event); 37 | return await promise; 38 | } 39 | 40 | self.onpush = (event) => { 41 | invokePost("Push", generateGUID(), event); 42 | } 43 | 44 | self.onmessage = (event) => { 45 | var message = event.data; 46 | if (message.type == "InitialBlazorHandshake") { 47 | receivedInitialBlazorHandshakes.push(event.source.id); 48 | } 49 | else if (message.type == "GetProxyAttributeAsProxy") { 50 | var obj = proxyDict[message.objectId][message.attribute]; 51 | var objectId = generateGUID(); 52 | proxyDict[objectId] = obj; 53 | resolvePost(message.type, message.id, objectId); 54 | } 55 | else if (message.type == "GetProxyAsyncAttributeAsProxy") { 56 | proxyDict[message.objectId][message.attribute].then(obj => { 57 | var objectId = generateGUID(); 58 | proxyDict[objectId] = obj; 59 | resolvePost(message.type, message.id, objectId); 60 | }); 61 | } 62 | else if (message.type == "GetProxyAttribute") { 63 | var obj = proxyDict[message.objectId][message.attribute]; 64 | resolvePost(message.type, message.id, obj); 65 | } 66 | else if (message.type.startsWith("Call")) { 67 | if (proxyDict[message.objectId] == undefined && resolvers[message.id] == undefined) { 68 | return; 69 | } 70 | for (let i = 0; i < message.args.length; i++) { 71 | resolveEncodesIds(message.args, i); 72 | } 73 | if (message.type == "CallProxyMethodAsProxy") { 74 | var obj = proxyDict[message.objectId][message.method].apply(proxyDict[message.objectId], message.args); 75 | var objectId = generateGUID(); 76 | proxyDict[objectId] = obj; 77 | resolvePost(message.type, message.id, objectId); 78 | } 79 | else if (message.type == "CallProxyAsyncMethodAsProxy") { 80 | proxyDict[message.objectId][message.method].apply(proxyDict[message.objectId], message.args).then(obj => { 81 | 82 | var objectId = generateGUID(); 83 | if (obj == undefined) { 84 | objectId = undefined; 85 | } 86 | else { 87 | proxyDict[objectId] = obj; 88 | } 89 | resolvePost(message.type, message.id, objectId); 90 | }); 91 | } 92 | else if (message.type == "CallProxyMethod") { 93 | var obj = proxyDict[message.objectId][message.method].apply(proxyDict[message.objectId], message.args); 94 | resolvePost(message.type, message.id, obj); 95 | } 96 | else if (message.type == "CallProxyConstructorAsProxy") { 97 | var newProxy = new Proxy(proxyDict[message.objectId][message.name], proxyHandler); 98 | var obj = new newProxy(...message.args) 99 | var objectId = generateGUID(); 100 | proxyDict[objectId] = obj; 101 | resolvePost(message.type, message.id, objectId); 102 | } 103 | else if (message.type == "CallResolve") { 104 | resolvers[message.id].apply(this, message.args); 105 | } 106 | } 107 | else { 108 | invokePost("Message", generateGUID(), event); 109 | } 110 | }; 111 | 112 | function resolveEncodesIds(obj, key) { 113 | if (obj[key] != null) { 114 | if (obj[key].length == 36 && obj[key].charAt(8) == '-') { 115 | obj[key] = proxyDict[obj[key]]; 116 | } 117 | else if (obj[key] instanceof Object) { 118 | for (const [nestedKey, value] of Object.entries(obj[key])) { 119 | resolveEncodesIds(obj[key], nestedKey) 120 | } 121 | } 122 | } 123 | } 124 | 125 | skipWaiting(); 126 | 127 | function invokePost(type, eventId, event) { 128 | clients.matchAll({ type: "window", includeUncontrolled: true }).then(([windowClient]) => { 129 | if (windowClient != undefined) { 130 | proxyDict[eventId] = event; 131 | var message = { type: type, id: id, eventId: eventId }; 132 | windowClient.postMessage(message); 133 | } 134 | }); 135 | } 136 | 137 | function resolvePost(type, id, object) { 138 | clients.matchAll({ type: "window", includeUncontrolled: true }).then(([windowClient]) => { 139 | if (windowClient != undefined) { 140 | var message = { type: `Resolve${type}`, id: id, object: object }; 141 | windowClient.postMessage(message); 142 | } 143 | }); 144 | } 145 | 146 | // https://stackoverflow.com/a/8809472/9905146 147 | function generateGUID() { // Public Domain/MIT 148 | var d = new Date().getTime();//Timestamp 149 | var d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now() * 1000)) || 0;//Time in microseconds since page-load or 0 if unsupported 150 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { 151 | var r = Math.random() * 16;//random number between 0 and 16 152 | if (d > 0) {//Use timestamp until depleted 153 | r = (d + r) % 16 | 0; 154 | d = Math.floor(d / 16); 155 | } else {//Use microseconds since page-load if supported 156 | r = (d2 + r) % 16 | 0; 157 | d2 = Math.floor(d2 / 16); 158 | } 159 | return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); 160 | }); 161 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.ServiceWorker/wwwroot/KristofferStrube.Blazor.ServiceWorker.js: -------------------------------------------------------------------------------- 1 | export function isAttributeNullOrUndefined(object, attribute) { 2 | return object[attribute] == null || object[attribute] == undefined; 3 | } 4 | 5 | export function getAttribute(object, attribute) { return object[attribute]; } 6 | 7 | export function setAttribute(object, attribute, value) { object[attribute] = value; } 8 | 9 | export async function getAttributeAsync(object, attribute) { 10 | return await object[attribute]; 11 | } 12 | 13 | export function arrayBuffer(buffer) { 14 | var bytes = new Uint8Array(buffer); 15 | return bytes; 16 | } 17 | 18 | export function isUndefined(object) { 19 | return object == undefined; 20 | } 21 | 22 | export function registerEventHandlerAsync(objRef, jSInstance, eventName, invokeMethod) { 23 | jSInstance.addEventListener(eventName, (e) => objRef.invokeMethodAsync(invokeMethod, DotNet.createJSObjectReference(e))); 24 | } 25 | 26 | export function getNavigator() { return navigator; } 27 | 28 | export function constructJsonObject() { return {}; } 29 | 30 | var resolvers = {} 31 | 32 | export function registerMessageListener(container) { 33 | container.addEventListener("message", async (e) => { 34 | var message = e.data 35 | if (message.type.startsWith("Resolve")) { 36 | resolvers[message.id].call(this, message.object); 37 | delete resolvers[message.id]; 38 | } 39 | else { 40 | DotNet.invokeMethodAsync("KristofferStrube.Blazor.ServiceWorker", `InvokeOn${message.type}Async`, message.id, message.eventId); 41 | } 42 | }) 43 | } 44 | 45 | export async function getProxyAttributeAsProxy(container, id, objectId, attribute) { 46 | var promise = new Promise(async (resolve, _) => { 47 | resolvers[id] = resolve; 48 | var message = { type: "GetProxyAttributeAsProxy", id: id, objectId: objectId, attribute: attribute }; 49 | var serviceWorker = (await container.ready).active; 50 | if (serviceWorker != null) { 51 | serviceWorker.postMessage(message); 52 | } 53 | }) 54 | return await promise; 55 | } 56 | 57 | export async function getProxyAsyncAttributeAsProxy(container, id, objectId, attribute) { 58 | var promise = new Promise(async (resolve, _) => { 59 | resolvers[id] = resolve; 60 | var message = { type: "GetProxyAsyncAttributeAsProxy", id: id, objectId: objectId, attribute: attribute }; 61 | var serviceWorker = (await container.ready).active; 62 | if (serviceWorker != null) { 63 | serviceWorker.postMessage(message); 64 | } 65 | }) 66 | return await promise; 67 | } 68 | 69 | export async function getProxyAttribute(container, id, objectId, attribute) { 70 | var promise = new Promise(async (resolve, _) => { 71 | resolvers[id] = resolve; 72 | var message = { type: "GetProxyAttribute", id: id, objectId: objectId, attribute: attribute }; 73 | var serviceWorker = (await container.ready).active; 74 | if (serviceWorker != null) { 75 | serviceWorker.postMessage(message); 76 | } 77 | }) 78 | return await promise; 79 | } 80 | 81 | export async function callProxyMethodAsProxy(container, id, objectId, method, args = []) { 82 | var promise = new Promise(async (resolve, _) => { 83 | resolvers[id] = resolve; 84 | var message = { type: "CallProxyMethodAsProxy", id: id, objectId: objectId, method: method, args: args }; 85 | var serviceWorker = (await container.ready).active; 86 | if (serviceWorker != null) { 87 | serviceWorker.postMessage(message); 88 | } 89 | }) 90 | return await promise; 91 | } 92 | 93 | export async function callProxyAsyncMethodAsProxy(container, id, objectId, method, args = []) { 94 | var promise = new Promise(async (resolve, _) => { 95 | resolvers[id] = resolve; 96 | var message = { type: "CallProxyAsyncMethodAsProxy", id: id, objectId: objectId, method: method, args: args }; 97 | var serviceWorker = (await container.ready).active; 98 | if (serviceWorker != null) { 99 | serviceWorker.postMessage(message); 100 | } 101 | }) 102 | return await promise; 103 | } 104 | 105 | export async function callProxyMethod(container, id, objectId, method, args = []) { 106 | var promise = new Promise(async (resolve, _) => { 107 | resolvers[id] = resolve; 108 | var message = { type: "CallProxyMethod", id: id, objectId: objectId, method: method, args: args }; 109 | var serviceWorker = (await container.ready).active; 110 | if (serviceWorker != null) { 111 | serviceWorker.postMessage(message); 112 | } 113 | }) 114 | return await promise; 115 | } 116 | 117 | export async function callProxyConstructorAsProxy(container, id, objectId, name, args = []) { 118 | var promise = new Promise(async (resolve, _) => { 119 | resolvers[id] = resolve; 120 | var message = { type: "CallProxyConstructorAsProxy", id: id, objectId: objectId, name: name, args: args }; 121 | var serviceWorker = (await container.ready).active; 122 | if (serviceWorker != null) { 123 | serviceWorker.postMessage(message); 124 | } 125 | }) 126 | return await promise; 127 | } 128 | 129 | export async function resolveProxy(container, id, args) { 130 | var message = { type: "CallResolve", id: id, args: args }; 131 | var controller = container.controller; 132 | if (controller != null) { 133 | controller.postMessage(message); 134 | } 135 | } 136 | 137 | export async function initialBlazorHandshake(container) { 138 | var message = { type: "InitialBlazorHandshake" }; 139 | var controller = container.controller; 140 | if (controller != null) { 141 | controller.postMessage(message); 142 | } 143 | } --------------------------------------------------------------------------------