onlinecompiler.io

Widget and iframe embed

Add widget.js and a div with your widget key, and the code inside it becomes an editor readers can run in any of 46 languages, with no account. Sites that only accept iframes get the same editor from an embed URL. This page lists every attribute, the JavaScript API and its events.

Put a runnable code example on any page with one script tag. Readers edit the code, change its input and run it, with no account. The widget uses a CodeMirror 6 editor and runs code over a WebSocket. It renders in Shadow DOM, so your page's styles and the widget's stay separate, and its height is fixed when it loads, so running code never shifts your page.

On WordPress, the free OnlineCompiler.io Code Runner plugin writes this markup for you, as a Code runner block or an [onlinecompiler] shortcode. In Docusaurus and MkDocs, a plugin does it for any code block marked runnable.

Requires a WebSocket key. Create one from the Widgets page in your dashboard. Widget keys are safe to embed in public HTML; they cannot be used to call the REST API.

Quick Start

index.html
<!-- 1. Add the widget script (before </body>) -->
<script src="https://onlinecompiler.io/widget.js"></script>

<!-- 2. Add a div with your key, the code, optional input and the credit link -->
<div class="runcode" data-key="YOUR_API_KEY" data-lang="python-3.14">
<pre>name = input()
print(f"Hello, {name}!")</pre>
<pre data-stdin>Ada</pre>
<a data-credit href="https://onlinecompiler.io/">Runs on OnlineCompiler.io</a>
</div>

Your code and input

Put the code inside the widget's div in a <pre>, and the program's standard input in a <pre data-stdin>. Both must be direct children of the div. The code in a <pre> is readable, and indexed, before the script loads, but < and & must be escaped. For code full of angle brackets, such as C++ includes or generics, use <script type="text/plain"> instead, which needs no escaping. Shared indentation is removed, and Reset brings back your code and input after a reader edits them.

cpp-example.html
<!-- No escaping needed inside <script type="text/plain"> -->
<div class="runcode" data-key="YOUR_API_KEY" data-lang="g++-15">
  <script type="text/plain">
    #include <iostream>
    #include <vector>

    int main() {
        std::vector<int> v{1, 2, 3};
        for (int x : v) std::cout << x * x << "\n";
    }
  </script>
</div>

A widget without code of its own opens with a sample program and a language menu, as a playground.

Output before the first run

To show the output before a reader presses Run, add a <script type="application/json" data-result> holding the result of an earlier run: the runcode:result event's detail, or the run-code response with the same fields. Charts and other files in its files show too. The first run replaces it. A result that isn't valid JSON, or that has no exit_code, is ignored.

saved-output.html
<!-- The output shows before the reader runs anything -->
<div class="runcode" data-key="YOUR_API_KEY" data-lang="python-3.14">
<pre>print("Hello, World!")</pre>
<script type="application/json" data-result>
  {"output": "Hello, World!\n", "error": "", "exit_code": 0, "time": "0.02", "memory": "9216"}
</script>
</div>

Judge with tests on the page

Add a <script type="application/json" data-tests> and the widget gets a Judge button and a Tests tab. Judge runs the reader's code against every test, as run-tests does, and shows each test's verdict and time, what a failing test expected and what it printed, then the overall verdict, how many passed and the score. The script holds the object runTests(options) takes: tests, each with expected_output and optionally input, hidden and weight, and optionally checker (trim if left out, or exact, tokens, float, rows, table or table_ordered), tolerance, scoring (all_or_nothing if left out, or percent or weighted), timeLimit and stopOnFailure. With weighted scoring each test shows its weight. Ctrl or Cmd+Shift+Enter judges; Ctrl or Cmd+Enter still runs. A script the widget can't use is ignored, and the browser console says why.

judge.html
<div class="runcode" data-key="YOUR_WIDGET_KEY" data-lang="python-3.14">
  <pre>a, b = map(int, input().split())
print(a + b)</pre>
  <script type="application/json" data-tests>
    {
      "tests": [
        { "input": "1 2", "expected_output": "3" },
        { "input": "2 2", "expected_output": "4" },
        { "input": "40 2", "expected_output": "42", "hidden": true, "weight": 2 }
      ],
      "checker": "tokens",
      "scoring": "weighted"
    }
  </script>
</div>

The tests are in your page's HTML, so anyone can read them, hidden ones included: a hidden test is hidden on screen, not secret. That suits practice and tutorials. For graded work, keep the tests on our servers with a stored problem in problem mode, where hidden tests never reach the browser and every submission is recorded with a signed receipt. To show a judged result before the reader presses Judge, add a <script type="application/json" data-tests-result> holding a run-tests response.

Configuration

Configure each widget instance using data-* attributes:

AttributeRequiredDefaultDescription
data-keyYes-Your API key
data-langNopython-3.14Language of the code (any compiler key)
data-themeNodarkdark, light, or auto to follow the reader's system setting
data-heightNoFits the codeEditor height in pixels. Without it, the editor fits the starting code, from 6 to 20 lines. The whole widget is 227 pixels taller, for the header, console and credit line. fill fills the div's own height instead, so give the div a height.
data-lang-selectNoOnly without codetrue or false to always show or hide the language menu. Edits in each language are kept when a reader switches.
data-readonlyNoOffReaders can run the code and change its input, but not edit the code. setCode still works.
data-autocompleteNoOnSuggestions while typing: names in scope and built-ins for Python and JavaScript, and the words already in the program for other languages. off turns them off, for a class that wants students to type everything.
data-creditNoShownoff hides the "Runs on OnlineCompiler.io" line under the editor, for a key of an account on Business or above (pricing); delete the snippet's <a data-credit> link too. On other plans the line stays: the widget checks with our server when it connects and shows the line again. The snippets on this site end with that link, <a data-credit href="https://onlinecompiler.io/">Runs on OnlineCompiler.io</a>, inside the div: the widget shows it as its credit line, and an embed without it gets the same line from the widget.
data-localeNoEnglishpt for Brazilian Portuguese or es for Spanish (a region such as pt-BR works too). Translates the widget's own text: Run, Reset, the Output and Input tabs, the status line and its notices, including the messages in runcode:error and runTests errors. Text from the server, such as a rate-limit refusal, and your program's output are shown as sent, except a refusal by your account's limits or plan, which the widget words itself.
data-customNoNoneUp to 256 characters of your own, such as a lesson or cohort id, echoed as custom in the detail of every event the widget fires. It stays in the browser: it is not sent to our servers.

Text size

The widget draws inside its own shadow root, so your page's CSS doesn't reach its text. Two CSS custom properties do: set --oc-editor-font-size (the code, 13px by default) and --oc-console-font-size (the output and the input box, 12.5px by default) on the widget's div or any element around it. Any CSS length works; with a pixel size, an editor without data-height still grows to fit its starting code. In WordPress, add the rule under Appearance, Customize, Additional CSS (in a block theme, the Site Editor's Additional CSS); the plugin's widgets have the runcode class too.

text-size.html
<style>
  /* Every widget on the page; use an id such as #exercise for one */
  .runcode {
    --oc-editor-font-size: 20px;  /* the code */
    --oc-console-font-size: 18px; /* the output and the input box */
  }
</style>

Hidden code around the reader's

Add a <script type="text/plain" data-template> (or a <pre data-template>) to run code the reader doesn't see, such as imports, a main function or test calls. The reader's code replaces ##CODE##, and its later lines get the marker's indentation, so it can sit inside a Python function. Without a marker, the reader's code runs after the template. The template applies to the language in data-lang only, and line numbers in errors count its lines too.

template.html
<!-- Readers see and edit only the function body -->
<div class="runcode" data-key="YOUR_API_KEY" data-lang="python-3.14">
  <script type="text/plain" data-template>
    def area(width, height):
        ##CODE##

    print(area(3, 4))
  </script>
  <pre>return width * height</pre>
</div>

JavaScript API and events

Each widget sends events to its div. They bubble, so you can also listen on document and read event.target. Use them to check a reader's answer, record progress, or unlock the next step:

exercise.html
<div class="runcode" id="exercise" data-key="YOUR_API_KEY" data-lang="python-3.14">
<pre># Print the sum of the numbers from 1 to 10
print()</pre>
</div>
<p id="verdict"></p>

<script>
  // Check the reader's answer each time they run it.
  document.getElementById("exercise").addEventListener("runcode:result", (event) => {
    const { exit_code, output } = event.detail;
    const correct = exit_code === 0 && output.trim() === "55";
    document.getElementById("verdict").textContent = correct ? "Correct!" : "Not yet, try again.";
  });
</script>
<script src="https://onlinecompiler.io/widget.js"></script>
EventWhen, and what event.detail holds
runcode:readyThe widget has started. detail.widget is the widget.
runcode:beforerunBefore every Run, Judge, sample run and Submit, with detail.kind (run, judge, samples or submit), compiler, code and input (and tests for judge). Call event.preventDefault() to stop it, or change detail.code or detail.input to send something else. A listener that throws is reported by the browser and the run goes ahead.
runcode:runA run started. detail has the reader's code (without the template), input and compiler.
runcode:resultThe program ran. detail is the result: output, error, status, exit_code, signal, truncated, time, total and memory, as in the WebSocket codeoutput event. In problem mode it fires for both Judge and Submit, and detail is the judged result (verdict, score, summary and the tests, with a hidden test reduced to its verdict) with the submission id in detail.submission; a page tells a Submit from Judge by matching that id to the one from runcode:submitted.
runcode:judgedJudge finished. detail is the result: verdict, score, passed, total and the tests, a hidden test with its verdict only.
runcode:languageThe editor switched language, from the menu or setLanguage. detail.compiler is the new compiler id.
runcode:submittedProblem mode: a Submit was queued. detail.submission is its id. Judge never fires it.
runcode:errorThe program didn't run, or its result was lost. detail.message says why: the key was refused, an account limit was hit, the connection dropped, or no result came back within 60 seconds.

To control a widget from your page, get it with OnlineCompilerWidget.get(element):

control.js
// The widget on an element, once the script has started it (null before).
const widget = OnlineCompilerWidget.get(document.getElementById("exercise"));

widget.setCode('print(sum(range(1, 11)))');
widget.setInput("");
widget.run();
MethodWhat it does
getCode()The code in the editor, without the template.
setCode(code)Replaces the code in the editor. Readers can undo it, and Reset still brings back your original.
getInput(), setInput(text)Read or replace the Input tab.
getLanguage(), setLanguage(compiler)Read or change the compiler id the editor is in, as picking it in the language menu does: the code and input written in the old one are kept for when the reader comes back. setLanguage returns false, and changes nothing, for an id the widget doesn't offer.
run()Runs the code, like the Run button. Does nothing while a run is in progress or when the editor is empty.
judge()Judges the code against the page's tests, as the Judge button does: opens the Tests tab, draws each test's verdict and the score, fires runcode:judged and returns a Promise of the result. In problem mode it runs the sample tests, as runSamples() does. Rejects with an Error saying why it didn't judge.
setTests(options), getTests()Set the page's tests from your script, with the same object the data-tests script holds, or remove them with null (Judge and the Tests tab go away). setTests throws an Error saying why for tests it can't use. getTests returns a copy, or null.
runTests(options)Judges the code in the editor against tests, as POST /api/run-tests/ does, and returns a Promise of that response without output files. options holds tests, each { input, expected_output, hidden, weight }, and optionally checker, tolerance, timeLimit, scoring and stopOnFailure. Rejects with an Error saying why when the tests are refused or the answer is lost. Runs and test runs take turns.
getProblem()Problem mode: returns a Promise of the problem's public view (title, statement, languages, starter code, visible tests and limits) once it has loaded, or of null for a widget without data-problem. Each visible test's input and expected_output is cut to 4,096 characters, and input_truncated and expected_output_truncated say whether it was; GET /api/problems/{id}/public has them whole. Rejects with an Error saying why when the problem can't be loaded.
setSession(token)Problem mode: gives the widget a session token from your server, so Submit appears, or takes it away with null. data-session sets the first one.
runSamples()Problem mode: judges the code in the editor against the visible tests, as the Judge button does (judge() does the same), and returns a Promise of the result. Rejects with an Error saying why it didn't run.
submit()Problem mode with data-session: submits the code, as the Submit button does. Fires runcode:submitted once it is queued, then checks for the result every 2 seconds for up to 5 minutes, and returns a Promise of it. Rejects with an Error saying why, including when the 5 minutes run out (the submission is still judged).
reset()Goes back to your original code and input.
disconnect()Closes the connection. The next run reconnects.

Problem mode: a stored problem in the page

The browser is never trusted for scores. A candidate's page can show a result, but only your server may record one: take the score from the signed webhook or from GET /api/submissions/{id}/, and treat anything the page reports as display only. With data-problem the widget shows one of your stored problems: its statement, its languages and starter code, the visible tests, and a Judge button. With a session from your server it also has a Submit button.

  • data-problem: the problem's id (prob_ and 24 letters and digits), as the answer that created it or GET /api/problems/ gives it. Not its slug: your widget key is in the page's HTML for anyone to read, and a slug can be guessed, so the widget opens a problem by its id only. It opens only problems of its own key's account, so a problem of another account, an archived one and one with no published version are not found. Without data-session the widget has Judge only.
  • data-session: a session token your server created for this candidate (below). It means something only together with data-problem. The token is secret to that candidate's page; give each candidate their own session.
  • In problem mode, data-lang and your own code, input and template inside the div are not read: the problem sets the languages and the starter code, and its tests supply the input. Judge and Submit run with its data files, if it has any, but the widget does not list them. They are not secret: a candidate's program can read and print them, so keep answers out of them. data-key, data-theme, data-height and data-locale work as before. The result's summary sentence comes from the API in English, so a pt or es widget shows it as sent while the rest of its text is translated.
  • A problem widget connects when the page loads, not when it scrolls near.
problem.html
<!-- Judge only: no session, so there is no Submit button -->
<div class="runcode" data-key="YOUR_WIDGET_KEY" data-problem="prob_3x9KpQ2mW7vL4nR8tY1zA6bC" data-locale="es">
  <a data-credit href="https://onlinecompiler.io/">Funciona con OnlineCompiler.io</a>
</div>

<!-- With a session your server created: Judge and Submit -->
<div class="runcode" id="interview" data-key="YOUR_WIDGET_KEY" data-problem="prob_3x9KpQ2mW7vL4nR8tY1zA6bC"
     data-session="pst_...the token your server received...">
  <a data-credit href="https://onlinecompiler.io/">Runs on OnlineCompiler.io</a>
</div>
<script src="https://onlinecompiler.io/widget.js"></script>

Create the session on your server

Call POST /api/problems/{problem}/sessions/ with your REST API key (a widget key is refused there), and render the token from the answer into the page as data-session. The token is shown once. A session lasts up to 24 hours (60 minutes if left out) and takes 1 to 20 Submits, and it is pinned to the problem's version at that moment. Sessions lists the fields, the give-back rule and how to revoke one.

Python (pip install requests)
import requests

# On your server, with your REST API key (never in the browser).
reply = requests.post(
    "https://api.onlinecompiler.io/api/problems/prob_3x9KpQ2mW7vL4nR8tY1zA6bC/sessions/",
    headers={"Authorization": "YOUR_API_KEY"},
    json={
        "external_ref": "candidate-8841",
        "max_submits": 3,
        "expires_in": 3600,
        "callback_url": "https://example.com/hooks/judge",
    },
    timeout=30,
)
reply.raise_for_status()
session = reply.json()
# Render session["token"] into the page as data-session. It is shown once.
# Keep session["session"] to read or revoke the session later.
Node.js 18+
// Node.js 18+, on your server, with your REST API key (never in the browser).
const reply = await fetch("https://api.onlinecompiler.io/api/problems/prob_3x9KpQ2mW7vL4nR8tY1zA6bC/sessions/", {
  method: "POST",
  headers: { Authorization: "YOUR_API_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({
    external_ref: "candidate-8841",
    max_submits: 3,
    expires_in: 3600,
    callback_url: "https://example.com/hooks/judge"
  })
});
if (!reply.ok) throw new Error("Session refused: " + (await reply.text()));
const session = await reply.json();
// Render session.token into the page as data-session. It is shown once.
// Keep session.session to read or revoke the session later.

The Problem tab, Judge and Submit

The problem's title and statement, its time limit per test and how many of its tests are hidden open in the Problem tab, beside the code. Judge and Submit open the Tests tab: each test's verdict and time, what a failing visible test expected and what it printed, then the verdict, how many passed and the score, and after a Submit a link to the submission's signed receipt page (none when the session was created with share_receipts: false; see session receipts). A session can also arrive after the widget has started: call setSession(token) and Submit appears.

  • Judge (named Run samples before November 2026) judges the code against the visible tests only, and the candidate sees the result at once, with the program's output for each visible test. It does not use up the session, and it counts as runs on your account. Ctrl+Enter (Cmd+Enter on Mac) runs the samples, never a Submit.
  • Submit judges every test, hidden ones included, in your account's queue, and uses one of the session's Submits. The widget shows that it was queued, then checks for the result every 2 seconds for up to 5 minutes and shows it. When the session or your API key has a callback URL, your server gets the signed webhook with the result and the receipt, whatever the page does or shows; otherwise read the result with GET /api/submissions/{id}/.
  • What a candidate never sees: hidden tests (a hidden test shows as "Hidden test" with its verdict only), drivers, the reference solution, checker code and checker output. Neither a candidate nor a session holder can read them through the widget.
  • What the candidate's page does get: each result with its receipt, which holds the session's external_ref and your account reference, and, unless the session keeps receipts private, the link to the receipt's public page. Make external_ref an opaque reference, such as an id from your own system, never a candidate's name or email. The session's metadata never reaches the page.
  • Your account's limits stay yours. When your account can't take a run (its monthly allowance or a key's monthly limit is used up, its per-minute or pending limit is reached, its queue is full, or your plan is paused), the socket's answer carries only "The site's account can't run this right now. Try again later." with code account_limit, and the widget shows a neutral message to that effect in the page's language. The editor's Run and runTests() do the same. Your API and webhooks give you the full reason.
  • How long results can be read. The widget reads a Submit's result until one hour after the session expires, and no longer once you revoke the session. The webhook and GET /api/submissions/{id}/ on your server are not affected.
problem-events.js
const el = document.getElementById("interview");
let submitted = null;

// A Submit is queued: remember its id. Judge never fires this.
el.addEventListener("runcode:submitted", (event) => {
  submitted = event.detail.submission;
});

// Both Judge and Submit end here. A Submit's result carries the id from runcode:submitted.
el.addEventListener("runcode:result", (event) => {
  const result = event.detail;
  const wasSubmit = submitted !== null && result.submission === submitted;
  if (wasSubmit) showSubmittedNotice();      // update the page; do not record a score from here
  else showSampleResult(result.summary);
});

const widget = OnlineCompilerWidget.get(el);
const problem = await widget.getProblem(); // the public view; null without data-problem
await widget.runSamples();                 // as the Judge button
await widget.submit();                     // as the Submit button; needs data-session

Multiple Widgets

Add as many widgets as you need. Use class="runcode" for multiple widgets or id="runcode" for a single one. Each widget works independently, and connects only when it scrolls near the viewport, so a long page of examples doesn't open a connection for each one up front (a problem widget connects when the page loads). Widgets added to the page later, as single-page sites and docs generators with instant navigation do, start on their own, and a widget taken off the page closes its connection. For setups in Docusaurus, MkDocs, Sphinx, Mintlify and WordPress, see runnable code examples in docs. For a live demo and how the widget compares with other embeddable code editors, see embeddable code editor.

multiple-widgets.html
<!-- Follows the reader's light or dark setting; editor fits the code -->
<div class="runcode"
  data-key="YOUR_API_KEY"
  data-lang="python-3.14"
  data-theme="auto">
<pre>print("Hello")</pre>
</div>

<!-- A Java playground: light theme, 300px editor, language menu shown -->
<div class="runcode"
  data-key="YOUR_API_KEY"
  data-lang="openjdk-25"
  data-theme="light"
  data-height="300"
  data-lang-select="true">
</div>

<!-- Multiple widgets on the same page work independently -->
<script src="https://onlinecompiler.io/widget.js"></script>

Sites that only take an iframe

Many course platforms, site builders and wikis strip script tags but allow an <iframe>. For those, https://api.onlinecompiler.io/embed/ is a page holding one widget that fills the frame. Fill in your widget key and code, and paste the iframe it gives you:

Paste into your page's HTML
<iframe src="https://api.onlinecompiler.io/embed/?key=YOUR_WIDGET_KEY&amp;lang=python-3.14&amp;theme=light#code=name%20%3D%20input(%22Your%20name%3F%20%22)%0Aprint(f%22Hello%2C%20%7Bname%7D!%22)&amp;input=Ada"
  title="Runnable Python example" width="100%" height="420" style="border: 0" loading="lazy"></iframe>
<p><a href="https://onlinecompiler.io/">Runs on OnlineCompiler.io</a></p>
ParameterWhat it sets
keyYour widget key (required)
langThe compiler id, such as python-3.14 or g++-15; python-3.14 if left out
themedark (the default), light or auto
readonly1 to stop readers editing the code
creditoff to hide the "Runs on OnlineCompiler.io" line, for a key of an account on Business or above; on other plans the line stays
localept for Brazilian Portuguese or es for Spanish: the editor's buttons and messages, and the embed's own notices. English if left out, whatever the reader's browser language
#code=The starting code, URL-encoded, after the #
#input=The starting standard input, URL-encoded, after the #
  • The code and input go after the #, which browsers never send to a server, so they don't appear in our logs and long programs fit. Reset brings them back after a reader edits them.
  • A key restricted to your domain can only be framed by pages on that domain, and every frame around the embed must be on it too. Opened on its own, outside a frame, the embed shows a notice instead of running.
  • The console is 156 pixels tall and the editor gets the rest of the frame's height.
Features included: CodeMirror 6 editor with syntax highlighting for all 46 languages, Run with Ctrl+Enter (Cmd+Enter on Mac), Reset, a console with Output and Input tabs, the exit code with run time and memory, a resizable split that puts the console beside the editor on wide pages, and dark, light and auto themes.

Questions

Do readers need an account to run the code?
No. Runs use your widget key and count towards your account's allowance. Give the key its own monthly limit to cap a public page.
Can I check a reader's answer?
Yes. Listen for the runcode:result event on the widget's element and compare event.detail.output with the answer, as in the JavaScript API example.
Can I make the code or output text bigger?
Yes. Set --oc-editor-font-size (the code, 13px by default) and --oc-console-font-size (the output and the input box, 12.5px by default) in CSS on the widget's div. The widget draws inside its own shadow root, so other page CSS does not reach its text.
Can readers edit only part of the program?
Yes. Put the whole program in a script tag with data-template and mark the editable part with ##CODE##; readers see and edit only that part.