Ram Ram - 7 months ago 118
Javascript Question

event.preventDefault not working everywhere?

i made a chrome extension to get element from web pages by using click event listener on content page but preventDefault is working for few times only.

for example on this website when i click on the menu bar it redirects to the next page instead of preventing click action to happen.
this is my event listener in content.js

document.addEventListener('click', function xyz(e){
e.preventDefault();
//alert(e);
var target = e.target || event.srcElement;
var attributes = Array.prototype.slice.call(target.attributes).map(function(i) {
return [String(i.name)+": "+String(i.value)]
})
alert(attributes);
prompt("xpath1 :",getPathTo(target));
chrome.runtime.sendMessage({method:"captureElement",data:attributes});
},true)


how to stop click event from occuring !

Answer

You either need to use return false; or use e.preventDefault(); and e.stopPropagation() together. Because this will prevent event from bubbling up to the parent anchor tag.

Comments