11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ChromeExtensionでGoogle検索結果に要素を挿入する処理を実装する時のちょっとしたコツ

Last updated at Posted at 2014-09-30

ChromExtensionでGoogle検索結果に要素を追加する処理を考えます。

Google検索時に要素を追加する1

まず、簡単なやり方です。以下のようにmanifest.jsoncontent_scriptsに検索を実行した際に検索結果に要素を挿入するスクリプトを実行するよう記述します。

manifest.json
{
  "name": "SearchResult1",
  "version": "1.0",
  "manifest_version": 2,
  "description": "SearchResult1",
  "content_scripts": [
    {
      "matches": ["*://www.google.co.jp/*",
                  "*://www.google.com/*"
                  ],
      "js": ["jquery.min.js","script.js"],
          "run_at": "document_end"
    }
  ]
}

script.js
$(function(){
        $("h3.r>a").each(function(){
                $(this).prepend("<span>[Insert]</span>");
        });
});

上記のスクリプトをChromeに読み込ませた上で検索を実行すると、一応は下図のように要素の挿入に成功します。
ScreenClip.png

問題点

ただし、例えば上記のページで検索フォームの虫眼鏡ボタンをクリックした際等は、検索がAjaxで処理されるため、今の状態だとスクリプトが実行されません。

Google検索時に要素を追加する2

そこで、Ajaxで検索実行された時もスクリプトが実行されるよう、DOMNodeInsertedをイベントリスナーに登録することで要素の挿入を実現します。
下記のコードでは、タイマーを設定(①)して、何度もイベントが発行されるのを防いでいます。また、②の部分で、要素が挿入済かを判定し、何度も挿入されるのを防いでいます。

script.js
var timer = 0;
document.addEventListener('DOMNodeInserted', function(){
        if(timer) return;
        timer = setTimeout(function(){//①
                timer = 0;
                $("h3.r>a").each(function(){
                        if(!$(this).children('span')[0]){//②
                                $(this).prepend("<span>[Insert]</span>"); 
                        }
                });
        }, 3000);
}, false);

参考:
junion-org/GoogleWithFavicons https://github.com/junion-org/GoogleWithFavicons
DOM Mutation Events は非同期にして使おう - JavaScriptで遊ぶよ - g:javascript http://javascript.g.hatena.ne.jp/edvakf/20100204/1265312155

11
13
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
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?