@teacharium/embed-sdk
v0.1.0
Published
SDK for embedding Teacharium lessons via iframe
Maintainers
Readme
Teacharium Embed SDK
A lightweight JavaScript SDK for embedding Teacharium lessons into any website using secure iframe-based embedding.
Installation
npm install @teacharium/embed-sdkOr use directly via CDN:
<script src="https://unpkg.com/@teacharium/embed-sdk@latest/dist/teacharium-embed-sdk.umd.js"></script>Quick Start
1. Obtain a JWT Token
First, generate a signed token from your backend using the Teacharium API:
const response = await fetch('https://www.teacharium.io/api/public/sign-token', {
method: 'POST',
headers: {
'Authorization': `Bearer ${publicKey}.${secretKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
lessonId: 'your-lesson-id',
userAttributes: {
userId: 'user_12345',
organizationRole: 'student'
},
timeout: 3600
})
});
const { token } = await response.json();Important: Do not include personally identifiable information (PII) such as email addresses, full names, or phone numbers in userAttributes. Use anonymous identifiers like user IDs or session IDs instead.
2. Embed the Lesson
<div id="lesson-container"></div>
<script type="module">
import { embedLesson } from '@teacharium/embed-sdk';
const embed = embedLesson({
container: '#lesson-container',
token: 'your-jwt-token-here',
// baseUrl and lessonId are optional - defaults to www.teacharium.io and extracts lessonId from token
width: '100%',
height: '600px',
onLoad: () => console.log('Lesson loaded'),
onComplete: (data) => console.log('Lesson completed', data),
onProgress: (data) => console.log('Progress update', data),
onError: (error) => console.error('Error', error)
});
</script>Using UMD (Browser Global)
<div id="lesson-container"></div>
<script src="https://unpkg.com/@teacharium/embed-sdk@latest/dist/teacharium-embed-sdk.umd.js"></script>
<script>
const embed = TeachariumEmbed.embedLesson({
container: '#lesson-container',
token: 'your-jwt-token-here',
onComplete: (data) => {
console.log('Lesson completed!', data);
}
});
</script>API Reference
embedLesson(options: EmbedOptions)
Creates and embeds a lesson iframe.
Options:
container(required): HTMLElement or CSS selector string for the containertoken(required): JWT token from/api/public/sign-token(lessonId is automatically extracted from this token)baseUrl(optional): Base URL of your Teacharium instance, default: "https://www.teacharium.io"width(optional): Iframe width, default: "100%"height(optional): Iframe height, default: "600px"className(optional): Additional CSS classes for the iframeonLoad(optional): Callback when lesson loadsonComplete(optional): Callback when lesson is completedonProgress(optional): Callback for progress updatesonError(optional): Callback for errors
Returns: TeachariumEmbed instance
TeachariumEmbed Methods
destroy()
Removes the embedded lesson from the page.
embed.destroy();reload()
Reloads the embedded lesson.
embed.reload();postMessage(type: string, payload?: any)
Send a custom message to the embedded lesson.
embed.postMessage('custom:action', { data: 'value' });getIframe()
Get the iframe element.
const iframe = embed.getIframe();Events
onLoad
Fired when the lesson iframe has loaded.
onLoad: () => {
console.log('Lesson is ready');
}onComplete
Fired when the user completes the lesson.
onComplete: (data) => {
// data.lessonId - The lesson ID
// data.completedAt - ISO timestamp
// data.score - Optional score
// data.totalSteps - Total number of steps
}onProgress
Fired when the user progresses through the lesson.
onProgress: (data) => {
// data.currentStep - Current step number
// data.totalSteps - Total steps
// data.sectionIndex - Current section index
// data.stepIndex - Current step index
}onError
Fired when an error occurs.
onError: (error) => {
console.error('Lesson error:', error.message);
}Security
- Always generate tokens on your backend, never expose API keys in client-side code
- Tokens expire based on the
timeoutparameter (default 2 hours, max 24 hours) - Tokens are tied to specific lessons and organizations
- User attributes in tokens cannot be modified without re-signing
Examples
Responsive Embed
embedLesson({
container: '#lesson',
token: token,
baseUrl: 'https://your-domain.com',
lessonId: lessonId,
width: '100%',
height: '80vh',
className: 'lesson-iframe'
});With Progress Tracking
const embed = embedLesson({
container: '#lesson',
token: token,
baseUrl: 'https://your-domain.com',
lessonId: lessonId,
onProgress: (data) => {
const percent = (data.currentStep / data.totalSteps) * 100;
document.querySelector('#progress-bar').style.width = `${percent}%`;
}
});React Example
import { useEffect, useRef } from 'react';
import { embedLesson } from '@teacharium/embed-sdk';
function LessonEmbed({ token }) {
const containerRef = useRef(null);
const embedRef = useRef(null);
useEffect(() => {
if (containerRef.current && token) {
embedRef.current = embedLesson({
container: containerRef.current,
token: token,
// lessonId and baseUrl are automatically handled
onComplete: (data) => {
console.log('Lesson completed!', data);
}
});
}
return () => {
if (embedRef.current) {
embedRef.current.destroy();
}
};
}, [token]);
return <div ref={containerRef} style={{ width: '100%', height: '600px' }} />;
}License
MIT
