10
9

More than 5 years have passed since last update.

Chrome extensionのcontent_scriptsにAjaxを対応してみた

Posted at

したいこと:

ウェブページにある要素の前にリンクを付けたい。

最初のページは簡単ですが、でもその以降のデータ取得はAjaxでとっています(Ajax.onSuccess($('a').html(data))の形で)ので、新たに撮ったデータにリンクが付けられません。

解決策はDOM要素のDOMSubtreeModifiedイベントを利用しました。

function addLinks(){
  $("div[class='question-box']").each(function(){
    // do something ...
  });
}

function DOMModificationHandler(){

  $(this).unbind('DOMSubtreeModified');
  setTimeout(function(){
      addLinks();
      $('.question-list').bind('DOMSubtreeModified',DOMModificationHandler);
  },1500);
}

// add links for first page(loaded not by Ajax).
addLinks();

//after document-load(for ajax response)
$('.question-list').bind('DOMSubtreeModified',DOMModificationHandler);

10
9
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
10
9