ポイントとしてはコンテンツデータをBlob形式にして、ObjectURLを作成して、それをaタグ経由で利用します。その際にaタグのdownload属性を指定することで、画面に表示するのではなくダウンロード挙動としています。 これを応用すれば例えばCanvasで描いた内容のダウンロードとか、編集したJSONファイルのダウンロードとか色々とできそうです。
Last active
January 4, 2017 16:22
-
-
Save mojagehub/75aa23f42a211a5d722ace35fda50a7c to your computer and use it in GitHub Desktop.
Webページで編集した内容をJavascriptから動的にダウンロードする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// クリック時の動作を指定する | |
var btn = document.getElementById('download'); | |
btn.addEventListener('click', function() { | |
// テキストエリアから入力内容を取得する | |
var content = document.getElementById('content').value; | |
// テキストファイルをBlob形式に変換する | |
let blob = new Blob([content]); | |
// Blobデータに対するURLを発行する | |
let blobURL = window.URL.createObjectURL(blob); | |
// URLをaタグに設定する | |
let a = document.createElement('a'); | |
a.href = blobURL; | |
// download属性でダウンロード時のファイル名を指定 | |
a.download = 'content.txt'; | |
// Firefoxの場合は、実際にDOMに追加しておく必要がある | |
document.body.appendChild(a); | |
// CLickしてダウンロード | |
a.click(); | |
// 終わったら不要なので要素を削除 | |
a.parentNode.removeChild(a); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta charset="utf-8"> | |
<title></title> | |
<meta name="description" content=""> | |
<meta name="author" content=""> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<link rel="stylesheet" href=""> | |
<!--[if lt IE 9]> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script> | |
<![endif]--> | |
<link rel="shortcut icon" href=""> | |
</head> | |
<body> | |
<textarea id="content"></textarea> | |
<button id="download">テキストファイルとしてダウンロードする</button> | |
<!-- SCRIPTS --> | |
<script src="download.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment