話の発端
結構前ですが、こういうのはやっていたなあと思い出しました。
data:text/html, <html contenteditable>
で、合わせて海外のこの記事が貼られているんですが、
ここに単純なものより優れたブックマークレットが幾つかあるので、そのうちの1つを改良します。
改良するもの
これを選びました。Saveボタンがついているのと、タブのタイトルにアイコンが付くのが特徴です。
ffokcuf Here is a modification I made to one of the previous examples so as to include a favicon:
data:text/html,<link rel="shortcut icon" href="https://raw.githubusercontent.com/Microsoft/Windows-classic-samples/master/Samples/Win7Samples/winui/shell/appplatform/aerowizards/migratingtoaerowizardssdksample/wizard97/notepad.ico" type="image/x-icon"><title>Text Editor</title><button onClick="SaveTextArea()">Save</button> <script language="javascript" type="text/javascript"> function SaveTextArea() { window.location = "data:application/octet-stream," + escape(txtBody.value); } </script> <textarea id="txtBody" style="font-size: 2em; width: 100%; height: 100%; boarder: none; outline: none" autofocus> </textarea>
Enjoy. 4 months ago ·
これに私はワードカウント機能が欲しくなりました。
改良手順
ボタンの横に文字列表示機能を追加。
<span>WordCount : </span><span id="wordcount">0</span>
textareaにoninput属性をつけて、変更を検知できるようにする。
<textarea id="txtBody" style="font-size: 2em; width: 100%; height: 100%; boarder: none; outline: none" autofocus oninput="changeWordCount(this)"></textarea>
最後に変更を検知したときに実行するfunctionを定義。
function changeWordCount(target) {document.getElementById("wordcount").innerHTML = target.value.length; };
出来たもの
data:text/html,<link rel="shortcut icon" href="https://raw.githubusercontent.com/Microsoft/Windows-classic-samples/master/Samples/Win7Samples/winui/shell/appplatform/aerowizards/migratingtoaerowizardssdksample/wizard97/notepad.ico" type="image/x-icon"><title>Text Editor</title><button onClick="SaveTextArea()">Save</button> <span>WordCount : </span><span id="wordcount">0</span><script language="javascript" type="text/javascript">function SaveTextArea() { window.location = "data:application/octet-stream," + escape(txtBody.value); } function changeWordCount(target) {document.getElementById("wordcount").innerHTML = target.value.length; };</script> <textarea id="txtBody" style="font-size: 2em; width: 100%; height: 100%; boarder: none; outline: none" autofocus oninput="changeWordCount(this)"></textarea>
ちょっと重い感じがするけど、しっかりしたものを書く用じゃないのでいいかなあ。
感想
bookmarkletだと素のJavaScript縛りみたいなところがあって、ちょっとやりにくいところもあったけど、なんとか出来て良かったです。(イベントの発火とか、oninputとかで本当はやらないほうがいいんだろうなとか)
多分もっと作り込むこともできそうなので、外部のJavaScriptとか読み込ませてわかりやすいものを作れるかもしれませんね。
この辺とか読んでもう少し機能付きのものを作ってみようかなとか。
気が向いたらもう少し改良してみます。
参考にした記事
- inputで「テキストが変更された」時のみなにかしたい。
- oninputを知らなかったので、助かった
- jQuery で innerHTML の書き換え/取得/追記/削除を行う方法