Last active
November 28, 2019 22:05
-
-
Save nfreear/307dfbd47c5b64d21cd0265185535de8 to your computer and use it in GitHub Desktop.
Simple Javascript editor using a Web Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> <title> JS editor using a Web Worker </title> | |
<style> | |
body { font: .95rem/1.5 sans-serif; margin: 1rem auto; max-width: 38rem; } | |
h1 { font-weight: normal; } | |
button, #console, #editor { font-size: 1.3rem; margin: 1rem 0; padding: .5rem 1rem; } | |
button { cursor: pointer; } | |
#editor { cursor: edit; } | |
#console, #editor { background: #e8e8e8; border: 1px solid #999; } | |
</style> | |
<h1> JS editor using a Web Worker </h1> | |
<pre id="editor" contenteditable="true" title="Click to edit!"> | |
// Click to edit! | |
echo('Hello world!') | |
let a = 10 + 12; | |
echo('Answer to the sum:', a) | |
echo(window) | |
function echo(msg, param2 = '') { | |
console.warn('>>', msg, param2) | |
postMessage(msg + ' ' + param2) | |
} | |
</pre> | |
<button id="run"> Run </button> | |
<pre id="console"></pre> | |
<script> | |
((WIN, DOC, selButton, selEditor, selConsole, timeoutSec) => { | |
'use strict'; | |
const $playButton = DOC.querySelector(selButton); | |
const $console = DOC.querySelector(selConsole); | |
const $editor = DOC.querySelector(selEditor); | |
$playButton.addEventListener('click', ev => { | |
const code = $editor.innerText; | |
console.warn('Code >>', code); | |
const codeBlob = new Blob([ code ], { type: 'text/javascript' }); | |
// convert the blob into a pseudo URL | |
const bbURL = URL.createObjectURL(codeBlob); | |
let worker = new Worker(bbURL); | |
// add a listener for messages from the Worker | |
worker.addEventListener('message', ev => { | |
const string = (ev.data).toString(); | |
$console.append(`${string} \n`); | |
}); | |
// add a listener for errors from the Worker | |
worker.addEventListener('error', er => { | |
const string = (er.message).toString(); | |
$console.append(`ERROR: ${string} \n`); | |
}); | |
// Finally, actually start the worker | |
worker.postMessage('start'); | |
// Put a timeout on the worker to automatically kill the worker | |
WIN.setTimeout(() => { | |
worker.terminate(); | |
console.warn('Worker terminated!', worker) | |
worker = null; | |
}, timeoutSec); | |
}); | |
console.debug('Check existence of Worker etc.:', Worker, URL, Blob); | |
})(window, document, '#run', '#editor', '#console', 10 * 1000); | |
</script> | |
<pre> | |
© Nick Freear / 28-Nov-2019. | |
* Source :~ https://gist.github.com/nfreear/307dfbd47c5b64d21cd0265185535de8 | |
* (Inspiration :~ http://blog.namangoel.com/replacing-eval-with-a-web-worker) | |
</pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment