2011-04-03 34 views
4

我試圖做一個擴展,解除網站本身添加的點擊事件。使用Chrome擴展程序解除點擊事件?

網站使用jQuery的,這將使這個出奇的簡單:

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

的問題是,我的分機(使用「content_scripts」)無法訪問該網站的jQuery對象,因此不具備事件函數來解除綁定。我可以在我的擴展中包含一個jQuery,但這沒有幫助,因爲jQuery將數據存儲在jQuery對象中(而不是在DOM元素中)。我的jQuery不會存儲這些事件。

還有別的辦法嗎?它不一定非常漂亮。也許沒有「content_scripts」?

+0

您的分機可以注入一個腳本到它,你需要什麼網頁? – Pointy 2011-04-03 16:34:57

+0

尖尖的,我可以,但比我需要一個外部腳本保存在互聯網上的某個地方。我希望它只是'.crx' ... – Rudie 2011-04-21 19:06:31

回答

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)); 
} 
+0

該函數有點矯枉過正,但'el.parentNode.replaceChild(el.cloneNode(true),el);'巧妙地完成了這個技巧!這個答案正在收藏中! =)謝謝! – Rudie 2011-04-24 12:50:40

-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); 
    } 
    }; 
})(); 
+1

實際上這是行不通的。我認爲解綁定監聽器的唯一方法是使用'HTMLElement.removeEventListener',爲此您需要初始事件/函數/回調/處理程序(存儲在不可訪問的'window.jQuery'中)。 – Rudie 2011-04-21 19:05:47

+0

這只是防止綁定新的事件偵聽器。我沒有看到它解綁定事件監聽器的地方。 – 2011-04-23 21:30:23