Skip to content

Instantly share code, notes, and snippets.

@NetOpWibby
Forked from bellbind/app.html
Created February 17, 2016 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NetOpWibby/9b3a02b379b31816656b to your computer and use it in GitHub Desktop.
Save NetOpWibby/9b3a02b379b31816656b to your computer and use it in GitHub Desktop.
[electron]Use electron as a Web Server
<!doctype html>
<html><head><script src="app.js"></script></head><body></body></html>
// utility
var console = {
log: function () {
var ipc = require("ipc");
var args = ["console"].concat([].slice.call(arguments));
return ipc.sendSync.apply(ipc, args)[0];
}
};
var quit = function () {
var ipc = require("ipc");
return ipc.sendSync("app", "quit")[0];
};
// server handler
window.addEventListener("load", function () {
var ipc = require("ipc");
ipc.on("request", function (req, port) {
//console.log(req);
var doc = document.implementation.createHTMLDocument(req.url);
var h1 = doc.createElement("h1");
h1.textContent = "Hello DOM: " + req.url;
doc.body.appendChild(h1);
ipc.send(port, 200, {"content-type": "text/html;charset=UTF-8"},
doc.documentElement.outerHTML);
});
}, false);
// electron main
console.log(process.versions);
var app = require("app");
app.on("ready", function () {
var ipc = require("ipc");
ipc.on("console", function (ev) {
var args = [].slice.call(arguments, 1);
var r = console.log.apply(console, args);
ev.returnValue = [r];
});
ipc.on("app", function (ev, msg) {
var args = [].slice.call(arguments, 2);
ev.returnValue = [app[msg].apply(app, args)];
});
var BrowserWindow = require("browser-window");
var window = new BrowserWindow({show: false});
window.loadUrl("file://" + __dirname + "/app.html");
window.webContents.once("did-finish-load", function () {
var http = require("http");
var crypto = require("crypto");
var server = http.createServer(function (req, res) {
var port = crypto.randomBytes(16).toString("hex");
ipc.once(port, function (ev, status, head, body) {
//console.log(status, head, body);
res.writeHead(status, head);
res.end(body);
});
window.webContents.send("request", req, port);
});
server.listen(8000);
console.log("http://localhost:8000/");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment