json 一个 html 的安全方法

Safe way to json a html?

本文关键字:安全 方法 html 一个 json      更新时间:2023-09-26

我的问题很简单,我想用json重新创建一个html页面,但我不想弄乱现有的 html、框架和合作......

例:

var myDiv = { tag : "div", style : "color:blue", class : "jj", content : "Hello"};

var myDiv = { tag : "div", style : "color:blue", class : "jj", content : "Hello"};
var param = { forbid : { tag : true, content : true } };
var createTag = function(o) {
    var node = document.createElement(o.tag);
    for (att in o) {
      if (!param.forbid[att]) node.setAttribute(att, o[att]);
    }
    node.appendChild(document.createTextNode(o.content))
    return node;
}
document.body.textContent = createTag(myDiv).outerHTML;

此代码的结果是:

<div style="color:blue" class="jj"> Hello </div>

如何确保"标签"和"内容"不会弄乱现有/未来属性?并保持简单?

为了避免与属性冲突,我会将它们分开

var myDiv = {
  tagName: "div",
  attributes: {
    style: "color: blue",
    class: "jj"
  },
  childNodes: ["Hello"]
};

function parseTree(node) {
  if(typeof node === 'string') // Text node
    return document.createTextNode(node);
  // Otherwise, assuming an element. Consider adding
  // `node.nodeType` if you want multiple node types
  var el = document.createElement(node.tagName);
  if(node.hasOwnProperty('attributes'))
    for(var attr in node.attributes)
      if(node.attributes.hasOwnProperty(attr))
        el.setAttribute(attr, node.attributes[attr]);
  if(node.hasOwnProperty('childNodes'))
    node.childNodes.forEach(function(child) {
      el.appendChild(parseTree(child));
    });
  return el;
}
document.body.textContent = parseTree({
  tagName: "div",
  attributes: {
    style: "color: blue",
    class: "jj"
  },
  childNodes: ["Hello"]
}).outerHTML;

或者,您可以使用带有属性名称中不允许的某些字符的字符串。例如,'u0000.

var myDiv = {
  " tagName": "div",
  style: "color: blue",
  class: "jj",
  " childNodes": ["Hello"]
};

function parseTree(node) {
  if(typeof node === 'string') // Text node
    return document.createTextNode(node);
  // Otherwise, assuming an element. Consider adding
  // `node[" nodeType"]` if you want multiple node types
  var el = document.createElement(node[" tagName"]);
  for(var attr in node)
    if(node.hasOwnProperty(attr) && attr[0] !== " ")
      el.setAttribute(attr, node[attr]);
  if(node[" childNodes"])
    node[" childNodes"].forEach(function(child) {
      el.appendChild(parseTree(child));
    });
  return el;
}
document.body.textContent = parseTree({
  " tagName": "div",
  style: "color: blue",
  class: "jj",
  " childNodes": ["Hello"]
}).outerHTML;

如果你

愿意,你可以尝试这样的事情:

["div", {style: "color:blue", class: "jj"}, ["Hello"]]

使用内部元素,您可以执行以下操作:

["div", {style: "color:blue", class: "jj"}, [[
  "p",
  "hello"
]]]

这是解析代码(只是CC_3函数) - 我还添加了一种尝试方法(HTML 是用基于 json 的格式编写

的,例如)

html = ["div", [["div",
  [
    ["p", ["Try it out:"]],
    [
      "code", {
        id: "try",
        style: "display:block",
        contentEditable: true
      },
      ['["div", { style: "color:blue;", class: "jj"}, ["Hello"]]']
    ],
    ["button", {
        "onclick": "return tryOut();"
      },
      ["Run"]
    ]
  ]
],["div", {id: "result-wrapper"}]]]
window.tryOut = function() {
  var el = parseTree(eval(document.querySelector("code#try").innerText));
  var holder = document.createElement("div");
  holder.appendChild(el);
  document.querySelector("#result-wrapper").innerHTML = holder.innerHTML;
}
document.body.appendChild(parseTree(html));
function parseTree(tree) {
  if (typeof tree === 'string') {
    return document.createTextNode(tree);
  }
  var el = document.createElement(tree[0]),
    attrs, simple, inner;
  if (tree.length == 2) {
    if (Array.isArray(tree[1])) {
      inner = tree[1];
    } else {
      attrs = tree[1];
    }
  } else if (tree.length == 3) {
    attrs = tree[1];
    inner = tree[2];
  } else {
    simple = true;
  }
  if (!simple) {
    if (attrs) {
      for (var attr in attrs)
        if (attrs.hasOwnProperty(attr)) {
          console.log(attr)
          console.log(attrs[attr])
          el.setAttribute(attr, attrs[attr]);
        }
    }
    if (inner) {
      inner.forEach(function(child) {
        el.appendChild(parseTree(child));
      });
    }
  }
  return el;
}
if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}