ChromExtensionでGoogle検索結果に要素を追加する処理を考えます。
Google検索時に要素を追加する1
まず、簡単なやり方です。以下のようにmanifest.json
のcontent_scripts
に検索を実行した際に検索結果に要素を挿入するスクリプトを実行するよう記述します。
{
"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"
}
]
}
$(function(){
$("h3.r>a").each(function(){
$(this).prepend("<span>[Insert]</span>");
});
});
上記のスクリプトをChromeに読み込ませた上で検索を実行すると、一応は下図のように要素の挿入に成功します。
問題点
ただし、例えば上記のページで検索フォームの虫眼鏡ボタンをクリックした際等は、検索がAjaxで処理されるため、今の状態だとスクリプトが実行されません。
Google検索時に要素を追加する2
そこで、Ajaxで検索実行された時もスクリプトが実行されるよう、DOMNodeInsertedをイベントリスナーに登録することで要素の挿入を実現します。
下記のコードでは、タイマーを設定(①)して、何度もイベントが発行されるのを防いでいます。また、②の部分で、要素が挿入済かを判定し、何度も挿入されるのを防いでいます。
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