-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
46 lines (40 loc) · 1.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* jslint node: true */
'use strict';
var injector = require('connect-injector');
module.exports = function injectBrowserSync(browserSync, options) {
var snippet = '';
var options = options || {};
if (options.injectHead === true) {
var tag = '</head>';
var find = /<\/head>/gi;
} else {
var tag = '</body>';
var find = /<\/body>(?!(.|\n)*<\/body>)/gi;
}
browserSync.emitter.on('service:running', function(data) {
if (!snippet) {
snippet = data.options.get('snippet');
}
});
return injector(function(req, res) {
var contentType = res.getHeader('content-type');
return contentType && (contentType.toLowerCase().indexOf('text/html') >= 0);
}, function converter(content, req, res, callback) {
function inject() {
var injected = content.toString().replace(find, snippet + tag);
callback(null, injected);
};
if (!snippet) {
// We don't have the snippet from BrowserSync yet.
// Block the response until we get it.
browserSync.emitter.on('service:running', function(data) {
if (!snippet) {
snippet = data.options.get('snippet');
}
inject();
});
} else {
inject();
}
});
};