Repository navigation
Expand file tree
/
Copy pathinjectHtml.js
More file actions
69 lines (66 loc) · 2.63 KB
/
Copy pathinjectHtml.js
File metadata and controls
69 lines (66 loc) · 2.63 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict';
const toString = require('stream-to-string');
const cheerio = require('cheerio');
const stream = require('stream');
const CONSTANTS = require('./constants');
module.exports = async function injectHtml(ctx) {
const INJECT_ID = CONSTANTS.get('INJECT_ID');
// 处理文件注入一些信息
let ok = false;
if (ctx && ctx.method === 'GET' && ctx.type === 'text/html') {
let body = null;
if (ctx.body instanceof stream.Readable) {
body = await toString(ctx.body);
} else if (ctx.body instanceof Buffer) {
body = String(ctx.body);
} else if (typeof ctx.body === 'string') {
body = ctx.body;
}
if (body) {
ctx.body = body;
try {
const $ = cheerio.load(ctx.body);
if ($(`body>#${INJECT_ID}`).length <= 0) {
const INJECT_MICRO_APP = `{
cache: {},
get: function(key) {
if (this.cache[key] == null) {
try {
var text = document.getElementById("${INJECT_ID}_" + key);
if (text) {
var value = JSON.parse(decodeURIComponent(text.value) || null);
this.cache[key] = value;
}
} catch (error) {
console.warn(error);
}
}
return this.cache[key];
},
};`.replace(/[\s]{2,}/gm, '');
$('body').prepend(`<div id="${INJECT_ID}" style="display: none;"><script type="text/javascript" charset="utf-8">window.MicroApp=${INJECT_MICRO_APP}</script></div>`);
ctx.body = $.html();
}
ok = true;
} catch (error) {
ok = false;
}
}
}
if (!ok) return false;
function func(key, value) {
if (ok && key) {
const $ = cheerio.load(ctx.body);
$(`body>#${INJECT_ID}`).append(`<textarea id="${INJECT_ID}_${key}" style="display: none;">${encodeURIComponent(JSON.stringify(value))}</textarea>`);
ctx.body = $.html();
}
}
func.callback = callback => {
if (ok && callback && typeof callback === 'function') {
const $ = cheerio.load(ctx.body);
callback($);
ctx.body = $.html();
}
};
return func;
};