Skip to content

Instantly share code, notes, and snippets.

@joelrbrandt
Last active December 15, 2015 12:49
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 joelrbrandt/5263092 to your computer and use it in GitHub Desktop.
Save joelrbrandt/5263092 to your computer and use it in GitHub Desktop.
example server that wraps html content in an iframe
node_modules

To use this:

  1. Clone it into a directory
  2. run npm install in that directory
  3. run node app in that directory
  4. Open that directory in brackets
  5. In the project settings for that directory, set the live preview base url to http://localhost:3000/
  6. Start live development
  7. Modify the CSS file
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, node: true */
/*global $, define */
(function () {
"use strict";
var connect = require("connect");
function wrap(req, res, next) {
var oldWrite = res.write,
oldEnd = res.end,
doWrap = false;
// Wrap the original "write" and "end" methods for the response object
res.write = function (chunk, encoding) {
if (!this.headerSent) {
this._implicitHeader();
}
if (doWrap) {
var s = "<html><body><iframe src='" + req.url + "?real' /></body></html>";
return oldWrite.call(res, s);
} else {
return oldWrite.call(res, chunk, encoding);
}
};
res.end = function (chunk, encoding) {
if (doWrap) {
this.write(chunk, encoding);
return oldEnd.call(res);
} else {
return oldEnd.call(res, chunk, encoding);
}
};
// When the header is sent, decide if we want to rewrite
res.on("header", function () {
var parsedUrl = require("url").parse(req.url);
doWrap = parsedUrl.search !== "?real" && /html/.test(res.getHeader("Content-Type"));
});
// Make sure to have the next middleware handle the request
next();
}
var app = connect();
app.use(connect.logger("dev"));
// Include our response wrapper before the rest of our middleware
// so that it gets the first shot at all response objects
app.use(wrap);
// Other middleware goes here
app.use(connect["static"](__dirname));
app.listen(3000);
}());
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Hi there!</h1>
</body>
</html>
{
"name": "iframe-wrapper",
"version": "0.0.0",
"description": "ERROR: No README.md file found!",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": "",
"author": "Joel Brandt",
"license": "MIT",
"dependencies": {
"connect": "~2.7.3"
}
}
body {
background-color: red;
}
h1 {
font-family: sans-serif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment