LoginSignup
0
2

More than 1 year has passed since last update.

ブックマークレットの作り方と実装例

Posted at

化石のようなテクニックで何番煎じかわかららないが、ここ最近でいくつかブックマークレットを作る機会があったので、作り方をまとめておく。今日においても、ブラウザでやるちょっとしたことを自動化するのに便利である。(ブラウザの拡張ツールは要求される権限が広くて心配なことがあるので。)

ブックマークレットのつくり方

基本的には下記の形式で記述したJavaScriptコードをブックマークのURLとして登録すればよい。コード量が多い場合はGoogle Closure Compiler等でminifyをかけるとよい。

javascript: (function () { 
    // ここに処理を記述する。
})();

表示しているページのDOMにアクセスできるため、そのページでできることはたいてい実現できる。

IDEやエディタで効率よく開発する方法もあるかもしれないが、そこまで複雑なものでなければブラウザの開発者ツールのConsoleでインタラクティブにJavaScriptを実行しながら作る、というスタイルで十分である。

実装例

Amazonの商品ページURLを簡易化+コピーする

javascript: (function () { 
    var e = document.createElement("span");
    e.textContent = "https://amazon.co.jp/dp/" + ue_pti;
    document.body.appendChild(e);

    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.selectAllChildren(e);
    document.execCommand("copy");
    window.location.href = e.textContent;
})();

参考:AmazonのURLを短縮するブックマークレットを作った話 - kick the base

WebページのURLをタイトルにリンクした形式でコピーする

javascript: (function () {
    var e = document.createElement('a');
    e.textContent = document.title;
    e.setAttribute('href', document.URL);
    document.body.appendChild(e);

    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.selectAllChildren(e);
    document.execCommand('copy');
    selection.removeAllRanges();
    e.remove();
})();
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2