This repository provides an F# WebSharper binding for the Web Locks API, allowing WebSharper applications to coordinate access to resources across multiple scripts.
The repository consists of two main projects:
-
Binding Project:
- Contains the F# WebSharper binding for the Web Locks API.
-
Sample Project:
- Demonstrates how to use the Web Locks API with WebSharper syntax.
- Includes a GitHub Pages demo: View Demo.
To use this package in your WebSharper project, add the NuGet package:
dotnet add package WebSharper.WebLocks
- .NET SDK installed on your machine.
-
Clone the repository:
git clone https://github.com/dotnet-websharper/WebLocks.git cd WebLocks
-
Build the Binding Project:
dotnet build WebSharper.WebLocks/WebSharper.WebLocks.fsproj
-
Build and Run the Sample Project:
cd WebSharper.WebLocks.Sample dotnet build dotnet run
-
Open the hosted demo to see the Sample project in action: https://dotnet-websharper.github.io/WebLocks/
Below is an example of how to use the Web Locks API in a WebSharper project:
namespace WebSharper.WebLocks.Sample
open WebSharper
open WebSharper.JavaScript
open WebSharper.UI
open WebSharper.UI.Client
open WebSharper.UI.Templating
open WebSharper.WebLocks
[<JavaScript>]
module Client =
// The templates are loaded from the DOM, so you just can edit index.html
// and refresh your browser, no need to recompile unless you add or remove holes.
type IndexTemplate = Template<"wwwroot/index.html", ClientLoad.FromDocument>
// Variable to track the lock status
let statusMessage = Var.Create "Lock status: Not acquired"
// Function to acquire a lock using the Web Locks API
let acquireLock () =
promise {
let locks = JS.Window.Navigator.Locks
do! locks.Request("my-lock", fun _ ->
promise {
// Update UI to indicate the lock has been acquired
statusMessage.Value <- "Lock acquired!"
Console.Log("Lock acquired, doing some work...")
// Simulate some work (3-second delay)
do! Async.Sleep 3000
// Release the lock and update the status
Console.Log("Work done, releasing lock...")
statusMessage.Value <- "Lock released!"
} |> As<Promise<unit>>
)
}
[<SPAEntryPoint>]
let Main () =
IndexTemplate.Main()
// Display lock status in the UI
.Status(statusMessage.V)
// Handle button click to acquire the lock
.AcquireLock(fun _ ->
async {
do! acquireLock() |> Promise.AsAsync
}
|> Async.StartImmediate
)
.Doc()
|> Doc.RunById "main"
This example demonstrates how to acquire and release a lock using the Web Locks API in WebSharper.
- Ensuring Safe Resource Access: The Web Locks API helps coordinate shared resources and prevents race conditions.
- Lock Scope: Locks are limited to the same origin and cannot be shared across different tabs or windows.
- Graceful Lock Handling: Always ensure locks are released after work is completed to prevent deadlocks.