LoginSignup
0
0

More than 1 year has passed since last update.

Chrome Extensionでオブジェクトの配列をCSVとして保存する方法

Last updated at Posted at 2021-09-12
background.ts
// オブジェクトの配列(例)
const data = [
  { title: 'aaa', published_at: '2021-09-12T06:24:12.175882' },
  { title: 'bbb', published_at: '2021-09-11T07:12:14.174731' },
];

const convertJsonToCsv = <T>(json: T[]): string => {
  const header = `${Object.keys(json[0]).join(',')}\n`;
  const body = json.map((d) => Object.values(d).join(',')).join('\n');
  return header + body;
};

// ダウンロードを実行
const downloadCsv = () => {
  const csv = convertJsonToCsv(data);
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  chrome.downloads.download({
    url,
    filename: 'filename.csv',
  });
};

manifest.jsonのpermissionに 'downloads' を追加するのをお忘れなく!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0