blob

blobで作ったテキストファイルをダウンロードする

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charaset="utf-8">
        <title>extension</title>
        <style>
            #results {
                height: 70px;
                width: 300px;
                font-size: 12px;
            }
        </style>
    </head>
    <body>
        <textarea id="results"></textarea>
        <button id="download">DOWNLOAD</button>
        <script src="background.js"></script>
    </body>
</html>
    document.getElementById('download').addEventListener('click', function(){

            const text = 'hello';
            const blob = new Blob([text], {type: "text/plain"});
            const url = URL.createObjectURL(blob);


            const a = document.createElement("a");
            a.href = url;
            a.download = "sample.txt";
            a.click();

            // ブラウザを閉じるまでメモリに常駐し続けるので、明示的に削除(メモリ開放)しないとダメ
            URL.revokeObjectURL(url);

    });

blobで作ったテキストファイルをダウンロードする2

<div class='container'>
  <a href='' download=''>download</a>
</div>

<script>
document.addEventListener("DOMContentLoaded", () => {
  document.querySelector("a").addEventListener("click", createBlob);
});

function createBlob() {
  // 5バイトのBlobオブジェクトを生成
  let array = new ArrayBuffer(5);
  
  // 1文字=1バイトなので5文字分の文字を入れる
  let dataView = new DataView(array);
  dataView.setInt8(0,104); //h
  dateView.setInt8(1,101); //e
  dataView.setInt8(2,108); //l
  dataView.setInt8(3,108); //l
  dataView.setInt8(4,111); //o
  
  // Binary Large Objectの生成
  let blob = new Blob([array], {type: "text/plain"});
  console.log(blob);
  
  // blobオブジェクトを人間が読めるようにしたのがfileオブジェクト
  // fileオブジェクトの生成
  let file = new File([array], "notes.txt", {type: "text/plain"});
  
  // オブジェクトURLの生成
  let url = URL.createObjectURL(file);
  console.log(url);
  
  // aタグにファイルパスとファイル名を代入
  const a = document.querySelector("a");
  a.href = url;
  a.download = file.name;
  
}
</script>