We recommend migrating to the new package, PatrickJahr.ScreenWakeLock, which offers improved features and better compatibility with the latest Blazor versions.
A Blazor wrapper for the Screen Wake Lock API.
The Screen Wake Lock API allows web applications to request a screen wake lock. Under the right conditions, and if allowed, the screen wake lock prevents the system from turning off a device's screen.
You need .NET 7.0 or newer to use this library.
You can install the package via NuGet with the Package Manager in your IDE or alternatively using the command line:
dotnet add package Thinktecture.Blazor.ScreenWakeLock
The package can be used in Blazor WebAssembly projects.
To make the ScreenWakeLockService available on all pages, register it at the IServiceCollection in Program.cs
before the host is built:
builder.Services.AddScreenWakeLockService();
Before using the Screen Wake Lock API, you should first test if the API is supported on the target platform by calling the IsSupportedAsync()
method.
This method returns a boolean to indicate whether the Screen Wake Lock API is supported or not.
var isSupported = await screenWakeLock.IsSupportedAsync();
if (isSupported)
{
// enable screen wake lock feature
}
else
{
// use fallback mechanism or hide/disable feature
}
To request a screen wake lock, you need to call the RequestWakeLockAsync()
method from the IScreenWakeLockService
service.
The browser can refuse the request for various reasons (for example, because the battery charge level is too low),
so it's a good practice to wrap the call in a try…catch
statement.
The exception's message will contain more details in case of failure.
try
{
await _screenWakeLockService.RequestWakeLockAsync();
}
catch(Exception e)
{
// Handle exxception
}
You also need a way to release the screen wake lock, which is achieved by calling the ReleaseWakeLockAsync()
method of the IScreenWakeLockService
service.
await _screenWakeLockService.ReleaseWakeLockAsync();
As soon as the object was released the action WakeLockReleased
will be fired.
protected override async Task OnInitializedAsync()
{
//...
_screenWakeLockService.WakeLockReleased = () =>
{
_wakeLockRequested = false;
};
//...
await base.OnInitializedAsync();
}
Thanks to Kristoffer Strube who provides a Blazor wrapper for the File System Access API. This library is inspired by Kristoffer's implementation and project setup.
BSD-3-Clause.
This is a technical showcase, not an official Thinktecture product.