名もなき未知

エンジニアリングとか、日常とかそういうのをまとめる場所。アクセス解析のためGAを利用、Googleに情報を送信しています。商品紹介のためAmazonアフィリエイトを利用、Amazonに情報を送信しています。記事に関しては私が書いていない引用文を除いて自由にご利用ください。

ブックマークレットでブラウザをメモ帳にするアレをいじってみる

話の発端

結構前ですが、こういうのはやっていたなあと思い出しました。

www.ideaxidea.com

data:text/html, <html contenteditable>

で、合わせて海外のこの記事が貼られているんですが、

coderwall.com

ここに単純なものより優れたブックマークレットが幾つかあるので、そのうちの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; };

出来たもの

f:id:kawasumi_yume:20171105100827g:plain

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とか読み込ませてわかりやすいものを作れるかもしれませんね。

この辺とか読んでもう少し機能付きのものを作ってみようかなとか。

qiita.com

気が向いたらもう少し改良してみます。

参考にした記事