diff --git a/pyscriptjs/examples/index.html b/pyscriptjs/examples/index.html index 02e4ed8..592eaba 100644 --- a/pyscriptjs/examples/index.html +++ b/pyscriptjs/examples/index.html @@ -68,5 +68,8 @@

Webgl Icosahedron Example

Demo showing how a Simple Webgl scene would work in PyScript tag

+ +

Textarea Content Download

+

Demo of a programmatic download of a plain text file containing the contents of a textarea tag

diff --git a/pyscriptjs/examples/textarea_download.html b/pyscriptjs/examples/textarea_download.html new file mode 100644 index 0000000..2074af5 --- /dev/null +++ b/pyscriptjs/examples/textarea_download.html @@ -0,0 +1,198 @@ + + + + + + + + py-script demos: textarea download + + + + + + + + + +
+ +
+

py-script Demos: textarea download

+
+ +
+
+
+
+ +
+
+ Enter text and download as .txt +
    +
  1. + + +
  2. +
+
+
+ +
+
+ +
+ + + + + + +from js import ( + document, + Blob, + URL +) + +import datetime +import pyodide +import re + +loading = document.getElementsByClassName("loading-container")[0] +loading.style.display = "none" +form = document.getElementById("entry_form") +form.style.display = "block" + +def download(path, filename): + """Create an anchor with a data URL object, insert into DOM, trigger anchor to + download file + """ + anchor = document.createElement("a") + anchor.href = path + anchor.download = filename + anchor.style.visibility = "hidden" + document.body.appendChild(anchor) + anchor.click() + document.body.removeChild(anchor) + +def ts_for_filename(): + now = datetime.datetime.now() + ts = now.strftime("%Y%m%d-%H%M%S") + return ts + +def get_text(): + textarea = document.getElementById("text_data") + text = textarea.value + return text + +def download_handler(event): + text = get_text() + blob = Blob.new([text], type="text/plain") + url = URL.createObjectURL(blob) + filename = ts_for_filename() + "-pyscript.txt" + download(url, filename) + +submit = document.getElementById("submit") +submit.addEventListener("click", pyodide.create_proxy(download_handler)) + + + + + + +
+
+ + +