通过ES6实现个模板操作

const vm = require('vm');
const user = {
  name: '<script>xss</script>'
}
//  中控
const templateMap = {
  templateA: '`<p>${include("templateB")}</p>`',
  templateB: '`<div>templateB</div>`'
}
const context = {
  user,
  _: (v) => {
    var entry = { "'": "&apos;", '"': '&quot;', '<': '&lt;', '>': '&gt;' };
    v = v.replace(/(['")-><&\\\/\.])/g, function ($0) { return entry[$0] || $0; });
    return v;
  },
  include: (name)=>{
    return templateMap[name]()
  }
}

Object.keys(templateMap).forEach(key => {
  const temp = templateMap[key]
  templateMap[key] = vm.runInNewContext(`
    (function(){
      return ${temp}
    })
    `,context)
})

// let str = `<h2>${user.name}</h2>`;
// 把str 看作 eval(str)。需要有括号
const result = vm.runInNewContext("`<h2>${_(user.name)}</h2><h4>${include('templateA')}</h4>`", context);
console.log('result is:', result) 
// result is: <h2>&lt;script&gt;xss&lt;/script&gt;</h2><h4><p><div>templateB</div></p></h4>

 

posted @ 2021-02-09 15:35  anthonyliu  阅读(115)  评论(0编辑  收藏  举报