Xamarin and .NET MAUI mobile integration
This guide shows how to run SCORM content with scorm-again in a MAUI WebView, with offline support. The bridge script and its configuration are the same on every platform. Only the native setup differs.
Shared bridge
All the mobile guides use the same bridge script. It runs inside the WebView before the course, creates the scorm-again API, and sends logs and events to your native code.
- Copy
dist/scorm-again.min.jsfrom the scorm-again package into your app. This full bundle defines bothwindow.Scorm12APIandwindow.Scorm2004API. - Copy the bridge script below into your app as
mobile-bridge.js. - Write a configuration script,
config.js, for each launch. - Run the three scripts in that order, before any course script: the bundle, the configuration, then the bridge.
The bridge puts the API on window.API for SCORM 1.2, or on window.API_1484_11 for SCORM 2004. Do not call Initialize from native code. The course calls it.
// Inject the bundle, configuration, then this file before any course script.
(function () {
function send(message) {
var json = JSON.stringify(message);
var handlers = window.webkit && window.webkit.messageHandlers;
if (window.ReactNativeWebView) window.ReactNativeWebView.postMessage(json);
else if (handlers && handlers.scormBridge) handlers.scormBridge.postMessage(json);
else if (handlers && handlers.csharpBridge) handlers.csharpBridge.postMessage(json);
else if (window.AndroidBridge) window.AndroidBridge.postMessage(json);
else if (window.ScormBridge) window.ScormBridge.postMessage(json);
else if (window.CSharpBridge) window.CSharpBridge.postMessage(json);
}
var config = window.scormBridgeConfig;
if (!config || (config.version !== "1.2" && config.version !== "2004")) {
throw new Error("Set scormBridgeConfig.version to 1.2 or 2004");
}
var settings = {};
var key;
for (key in config.settings) {
if (Object.prototype.hasOwnProperty.call(config.settings, key)) {
settings[key] = config.settings[key];
}
}
settings.onLogMessage = function (level, message) {
send({ type: "log", level: Number(level), message: String(message) });
};
var is12 = config.version === "1.2";
var api = is12 ? new window.Scorm12API(settings) : new window.Scorm2004API(settings);
var events = is12
? ["LMSInitialize", "LMSCommit", "LMSFinish"]
: ["Initialize", "Commit", "Terminate"];
events.forEach(function (name) {
api.on(name, function (element, value) {
send({ type: "event", name: name, CMIElement: element, value: value });
});
});
api.on("CommitError", function (errorCode, context) {
send({ type: "event", name: "CommitError", errorCode: errorCode, context: context });
});
["OfflineDataSyncing", "OfflineDataSynced", "OfflineDataSyncFailed"].forEach(function (name) {
api.on(name, function () {
send({ type: "event", name: name });
});
});
if (config.cmi) api.loadFromJSON(config.cmi);
if (is12) window.API = api;
else window.API_1484_11 = api;
})();This is an example config.js. Use the commit URL, course ID and learner data from your LMS. Build the file with a JSON serializer rather than by pasting strings into JavaScript.
window.scormBridgeConfig = {
version: "2004",
settings: {
lmsCommitUrl: "https://lms.example.com/scorm/commit",
enableOfflineSupport: true,
courseId: "course-123",
logLevel: 3, // 1 DEBUG, 2 INFO, 3 WARN, 4 ERROR (the default), 5 NONE
},
cmi: { learner_id: "learner-123" },
};For SCORM 1.2, set version to "1.2" and use cmi: { core: { student_id: "learner-123" } }. The cmi object is optional. The bridge passes it to loadFromJSON before the course starts.
Offline support needs:
- localStorage turned on in the WebView, and the same page origin on every launch, because the queue of unsent commits lives in localStorage
- the same
courseIdand learner id on every launch. Unsent commits are kept per course and learner, andInitializerestores them. - a commit endpoint that answers with a 2xx status. If the body is JSON with a
resultfield, such as{"result":"true","errorCode":0}, that field decides whether the commit succeeded. - CORS and authentication on the commit endpoint that accept requests from the page origin
- the course files stored on the device, if the course must open without a connection
Messages and connectivity
The bridge sends each message to native code as a JSON string. Parse it in your message handler.
| Message | Example |
|---|---|
| Log line | {"type":"log","level":3,"message":"..."} |
| API call | {"type":"event","name":"Commit"} |
| Commit failure | {"type":"event","name":"CommitError","errorCode":101,"context":{...}} |
| Offline sync | {"type":"event","name":"OfflineDataSynced"} |
The API call names are Initialize, Commit and Terminate for SCORM 2004, and LMSInitialize, LMSCommit and LMSFinish for SCORM 1.2. A Commit message only means the course called Commit. It does not mean the LMS stored the data.
Each offline sync sends OfflineDataSyncing when it starts, then OfflineDataSynced or OfflineDataSyncFailed.
The bridge has no network code of its own. When the device goes online or offline, run this script in the window that holds the API, with the current value of online:
window.dispatchEvent(new CustomEvent("scorm-again:network-status", { detail: { online: false } }));Send the current status again when the Initialize message arrives, so a device that starts offline is handled. When online becomes true, scorm-again replays the queued commits by itself. Do not call its internal storage or sync methods.
Native setup
The MAUI WebView cannot register a script to run at document start on every platform, so open the local launcher described below. Set up the message channel in each platform's WebView handler before you set Source to the launcher URL.
On Android, turn on JavaScript and DOM storage, and register this receiver with platformWebView.AddJavascriptInterface(new ScormChannel(), "CSharpBridge").
public sealed class ScormChannel : Java.Lang.Object
{
[Android.Webkit.JavascriptInterface]
[Java.Interop.Export("postMessage")]
public void PostMessage(string json)
{
using var message = System.Text.Json.JsonDocument.Parse(json);
System.Diagnostics.Debug.WriteLine(message.RootElement.ToString());
}
}On iOS, register a csharpBridge message handler on the configuration's content controller before the handler creates its WKWebView. Keep the receiver alive while the view exists, and remove it when you close the view. The bridge sends strings on both platforms.
public sealed class ScormMessageHandler : Foundation.NSObject, WebKit.IWKScriptMessageHandler
{
public void DidReceiveScriptMessage(WebKit.WKUserContentController controller,
WebKit.WKScriptMessage message)
{
using var payload = System.Text.Json.JsonDocument.Parse(message.Body.ToString());
System.Diagnostics.Debug.WriteLine(payload.RootElement.ToString());
}
}
// In the iOS handler, before constructing WKWebView with this configuration:
configuration.UserContentController.AddScriptMessageHandler(receiver, "csharpBridge");Here receiver is a ScormMessageHandler. Then open the launcher, and send connectivity changes to it:
webView.Source = localLauncherUrl;
// From the native connectivity callback, on the UI thread:
await webView.EvaluateJavaScriptAsync(script);Here webView is the MAUI WebView and script is the connectivity script above. Unsubscribe from connectivity changes when the player closes. In Xamarin.Forms, register the same platform channels in a WebView renderer.
Local launcher
Use a launcher page when the WebView has no reliable way to run a script at document start. The launcher loads the bundle, configuration and bridge with ordinary script tags, then loads the course in an iframe. Script tags without async or defer run before the browser reaches the iframe, so the API is ready when the course looks for it. SCORM content searches its parent windows for the API.
Serve the launcher, the scripts and the course from a local HTTP server in the app, at a fixed loopback address such as http://127.0.0.1:8080/launcher.html. localLauncherUrl in the native code above is this URL. Keep the address and port the same between launches. The WebView keeps localStorage per origin, and the origin includes the port, so a launcher on a new port cannot see data queued earlier. Set up the native message channel before you open the launcher.
Both platforms limit plain HTTP, even to the device itself:
- On Android, apps that target API level 28 or higher block cleartext HTTP by default. Allow it for the loopback address only: add
<domain-config cleartextTrafficPermitted="true"><domain>127.0.0.1</domain></domain-config>to a network security config, and pointandroid:networkSecurityConfigin the manifest at it. Android 17 (API level 37) and later allow cleartext to loopback addresses by default. - On iOS 17 and later, App Transport Security blocks HTTP to IP addresses. Set
NSAllowsLocalNetworkingtoYESin the app'sNSAppTransportSecuritysettings. It allows local addresses without turning off App Transport Security for other hosts.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script src="scorm-again.min.js"></script>
<script src="config.js"></script>
<script src="mobile-bridge.js"></script>
</head>
<body>
<iframe src="course/shared/launchpage.html" title="Course"></iframe>
</body>
</html>Run connectivity updates in the launcher window, because that is where the API is.
Troubleshooting
The course cannot find the API
- Check that the bundle, configuration and bridge run before the course's first script. A script added after the page has loaded is too late.
- Check that
versionin the configuration matches the course. SCORM 2004 courses look forwindow.API_1484_11, and SCORM 1.2 courses look forwindow.API. - Check the WebView console. The bridge throws an error if
versionis missing or wrong. - Use the full
scorm-again.min.jsbundle. The bridge needs the global for the course's SCORM version.
Commits do not reach the LMS
- Check that
lmsCommitUrlis set. Without it, scorm-again does not send or queue anything. - Check that the endpoint accepts requests from the page origin (CORS) and accepts your authentication.
- Watch for
CommitErrormessages, and for log lines at level 3 (WARN) or 4 (ERROR).
Offline commits are lost
- Check that localStorage is turned on and that the page origin is the same on every launch. A new origin starts with an empty queue.
- Check that every launch uses the same
courseIdand learner id. Commits for another course or learner stay queued, but they are not replayed or restored.
Alerts do not appear
Some courses use alert() or confirm(), for example to confirm exit. A WebView shows these dialogs only if the app handles them.
MAUI notes
- On Android, turn on DOM storage in the platform WebView settings. Without it, localStorage is not available and nothing can be queued.
- The Java method must be exported as lowercase
postMessage, as in the code above, because that is the name the bridge calls. - If dialogs do not appear, check that the platform handlers still use a
WebChromeClienton Android and aWKUIDelegateon iOS.