Skip to content

Instantly share code, notes, and snippets.

@ryoakg
Created January 6, 2020 03:31
Show Gist options
  • Save ryoakg/1110f3ada0887357622367b1b0bc393b to your computer and use it in GitHub Desktop.
Save ryoakg/1110f3ada0887357622367b1b0bc393b to your computer and use it in GitHub Desktop.
<?php
if (PHP_SAPI === 'cli') {
echo <<<EOS
Usage:
run: php -S localhost:8080 {$argv[0]}
browse http://localhost:8080/
EOS;
exit;
}
// routing
if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) === '/worker.js'){
render_js();
return;
}
render_html();
function render_js(){
header('Content-Type: application/javascript;charset=UTF-8');
echo <<<EOJS
self.addEventListener('message', (message) => {
const text = message.data;
if (text.length > 8) throw 'input text is too long!';
self.postMessage('received! '+text);
});
EOJS;
}
function render_html(){
?>
<html>
<head>
<script>
var worker;
function start_worker(){
if (worker) return;
worker = new Worker('worker.js');
worker.addEventListener('message', (message) => {
alert('The WebWorker replies: ' + message.data);
});
worker.addEventListener('error', (error) => {
alert(error.message);
});
}
function terminate_worker(){
if (! worker) return;
worker.terminate();
worker = null;
}
function post_to_worker(){
if (! worker) {
alert('The WebWorker is not started.');
return;
}
worker.postMessage(document.getElementById('input-text').value);
}
</script>
</head>
<body>
<button type="button" onclick="start_worker();">Start the WebWorker!</button>
<button type="button" onclick="terminate_worker();">Terminate the WebWorker!</button>
<p>input from 1 to 8 letters and push the botton.</p>
<input id="input-text" required pattern="\d+" type="text">
<button type="button" onclick="post_to_worker();">POST to the WebWorker!</button>
</body>
</html>
<?php }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment