codepan icon indicating copy to clipboard operation
codepan copied to clipboard

[Question] Embedding into HTML presentations?

Open sesm opened this issue 8 years ago • 6 comments

Can one embed CodePan snippets into an HTML presentation and show the presentation offline?

My specific usecase is teaching JS, and sometimes classrooms have internet connection issues.

sesm avatar Mar 31 '17 11:03 sesm

It's possible to store/save snippets in browser like using indexeddb

egoist avatar Mar 31 '17 11:03 egoist

Fair enough.

But what if later the presentations are stored on github pages, and students expect to see code examples in the presentation?

It's possible to create some script, that injects iframes with CodePan into the page and then updates the content of the panes. The usage could be something like this:

<div class='codepan-embed'
      data-html='...'
      data-js='...'
      data-css='...'
></div>

sesm avatar Mar 31 '17 11:03 sesm

Interesting idea, could be easier to implement than my solution 😄

egoist avatar Mar 31 '17 11:03 egoist

Here's the solution, what do you think?

<iframe id="iframe" src="https://codepan.js.org"></iframe>
<script>
  const boilerplate = {
    js: {
      code: 'console.log(1)',
      transformer: 'JSX'
    }
  }
  const iframe = document.getElementById('iframe')
  window.addEventListener('message', ({ data = {} }) => {
    if (data.type === 'codepan-ready') {
      iframe.contentWindow.postMessage({ 
        type: 'codepan-set-boilerplate', 
        boilerplate: JSON.stringify(boilerplate) 
      }, '*')
    }
  })
</script>

egoist avatar Mar 31 '17 13:03 egoist

Looks good to me!

sesm avatar Mar 31 '17 15:03 sesm

The example code above is actually working now.

egoist avatar Apr 01 '17 15:04 egoist