Skip to content

Flutter mobile integration ​

This guide shows how to run SCORM content with scorm-again in a Flutter 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.

  1. Copy dist/scorm-again.min.js from the scorm-again package into your app. This full bundle defines both window.Scorm12API and window.Scorm2004API.
  2. Copy the bridge script below into your app as mobile-bridge.js.
  3. Write a configuration script, config.js, for each launch.
  4. 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.

js
// 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.

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 courseId and learner id on every launch. Unsent commits are kept per course and learner, and Initialize restores them.
  • a commit endpoint that answers with a 2xx status. If the body is JSON with a result field, 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.

MessageExample
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:

javascript
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 ​

Use webview_flutter with a JavaScript channel named ScormBridge. Its controller cannot register a script to run at document start, so open the local launcher described below.

dart
final controller = WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..addJavaScriptChannel(
    'ScormBridge',
    onMessageReceived: (JavaScriptMessage message) {
      final payload = jsonDecode(message.message);
      debugPrint('$payload');
    },
  );
await controller.loadRequest(Uri.parse(localLauncherUrl));
// In your widget:
// WebViewWidget(controller: controller)

This needs dart:convert and package:webview_flutter/webview_flutter.dart. In your connectivity listener, call controller.runJavaScript(script) with the connectivity script, and cancel the subscription when you close the player.

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 point android:networkSecurityConfig in 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 NSAllowsLocalNetworking to YES in the app's NSAppTransportSecurity settings. It allows local addresses without turning off App Transport Security for other hosts.
html
<!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 version in the configuration matches the course. SCORM 2004 courses look for window.API_1484_11, and SCORM 1.2 courses look for window.API.
  • Check the WebView console. The bridge throws an error if version is missing or wrong.
  • Use the full scorm-again.min.js bundle. The bridge needs the global for the course's SCORM version.

Commits do not reach the LMS ​

  • Check that lmsCommitUrl is 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 CommitError messages, 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 courseId and 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.

Flutter notes ​

  • Keep JavaScriptMode.unrestricted. Without it, no script runs.
  • To show alert() and confirm(), register handlers with setOnJavaScriptAlertDialog and setOnJavaScriptConfirmDialog on the WebViewController.

Released under the MIT License.