4

Web サイト自体によって追加されたクリック イベントのバインドを解除する拡張機能を作成しようとしています。

この Web サイトでは jQuery を使用しているため、これは非常に簡単です。

jQuery('a[rel]').unbind('click');

問題は、私の拡張機能 (「content_scripts」を使用) が Web サイトの jQuery オブジェクトにアクセスできないため、バインドを解除するイベント関数がないことです。拡張機能に jQuery を含めることはできますが、jQuery は「データ」を (DOM 要素ではなく) jQuery オブジェクトに格納するため、役に立ちません。私のjQueryには、これらのイベントが保存されません。

別の方法はありますか?それはきれいである必要はありません。多分「content_scripts」なしで?

4

2 に答える 2

4
var unbind_event_listeners = function (node) {
    var parent = node.parentNode;
    if (parent) {
        parent.replaceChild(node.cloneNode(true), node);
    } else {
        var ex = new Error("Cannot remove event listeners from detached or document nodes");
        ex.code = DOMException[ex.name = "HIERARCHY_REQUEST_ERR"];
        throw ex;
    }
};

unbind_event_listeners(a_node)ノードからリスナーをアンバインドするために呼び出すだけです。これは、それ自体を除くドキュメント内のすべてのノードで機能しますdocument。に関してはwindow、あなたは運が悪いです。unbind_event_listeners(document.documentElement)ドキュメント内のノードにアタッチされているほとんどのイベント リスナーを削除する必要があります。

の場合a[rel]、次のようにします。

var nodes = document.querySelectorAll("a[rel]"), i = nodes.length;
while (i--) {
    unbind_event_listeners(nodes.item(i));
}
于 2011-04-23T21:08:38.687 に答える
-1

きれいにする必要がなく、ハックのようなことをしても構わない場合は、その要素にバインドされているすべてのクリック リスナーを強制的にアンバインドする必要があります。

var el = document.querySelector('a[rel]');
el.onclick = function() {};
el.addEventListener = function() {};

またはすべての要素に対して:

Array.prototype.slice.call(document.querySelectorAll('a[rel]')).forEach(function(el) {
  el.onclick = function() {};
  el.addEventListener = function() {};
});

編集:さらに醜いことをして、「document_start」でコンテンツスクリプトを実行して、次のことを行うこともできます。

Element.prototype.addEventListener = (function() {
  var real = Element.prototype.addEventListener;
  return function(ev) {
    if (ev === 'click' && this.tagName === 'A' && this.hasAttribute('rel')) {
      console.log('try again, jquery!');
    } else {
      return real.apply(this, arguments);
    }
  };
})();
于 2011-04-20T22:12:57.427 に答える