js 复制/转换 window对象的全部属性内容 为字符串

发布时间 2023-05-01 23:41:39作者: hrdom

控制台copy(window)不行,只得到[object Window]

copy(JSON.stringify(window))也不行,报错Uncaught TypeError: Converting circular structure to JSON

需要定义一个处理循环结构的函数,可以参考https://stackoverflow.com/questions/11616630/how-can-i-print-a-circular-structure-in-a-json-like-format

我是用的这个

const circularReference = {otherData: 123};
circularReference.myself = circularReference;

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        return;
      }
      seen.add(value);
    }
    return value;
  };
};

const stringified = JSON.stringify(circularReference, getCircularReplacer());

console.log(stringified);