React Native mobile integration
This guide shows how to run SCORM content with scorm-again in a React Native 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
Use react-native-webview and its injectedJavaScriptBeforeContentLoaded prop, which runs a script in the top window before the page's own scripts. Read the bundle, the configuration and the bridge into strings before you render the player. The bridge sends messages through window.ReactNativeWebView, which onMessage receives.
function ScormPlayer({ bundleText, configText, bridgeText, courseUrl, webViewRef }) {
return (
<WebView
ref={webViewRef}
source={{ uri: courseUrl }}
javaScriptEnabled
domStorageEnabled
injectedJavaScriptBeforeContentLoaded={
bundleText + "\n" + configText + "\n" + bridgeText + "\ntrue;"
}
onMessage={(event) => {
const message = JSON.parse(event.nativeEvent.data);
console.log(message);
}}
/>
);
}WebView comes from react-native-webview. In your NetInfo listener, call webViewRef.current.injectJavaScript(script + "\ntrue;") with the connectivity script above, and unsubscribe when the component unmounts.
The examples/react-native-offline app in the repository uses this setup. It serves courses from a local HTTP server, includes a small test course, and commits to the mock LMS from the integration tests.
Course host page
Open a small host page from the course origin, and load the course in an iframe inside it. courseUrl in the native code above is the URL of this host page. Many course wrappers declare their own global API variable, which would replace the scorm-again API if the course ran in the same window. SCORM content searches its parent windows for the API, so the course finds the one in the host page.
<!doctype html>
<html>
<body>
<iframe src="course/shared/launchpage.html" title="Course"></iframe>
</body>
</html>The host page needs no script tags. The document-start script adds the bundle, configuration and bridge before the iframe loads. Run that script in the top window only, so the iframe does not create a second API. Keep the host page and the course on the same origin.
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.
React Native notes
- On Android,
injectedJavaScriptBeforeContentLoadedcan run after the page's first scripts on some WebView versions. If the course cannot find the API on Android, use a local launcher instead. react-native-webviewshowsalert()andconfirm()dialogs on iOS and Android without extra code.