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

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

copy(object) copies a string representation至于具体是怎么实现的嘛,猜测类似于.toString() of the specified object to the clipboard.(参考https://developer.chrome.com/docs/devtools/console/utilities/#copy-function)

 

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);


不过复制出来有一些长的转义格式化有问题

posted @ 2023-05-01 23:37  hrdom  阅读(81)  评论(0编辑  收藏  举报