简体   繁体   中英

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 !

This is because you attach the event handler on the document itself instead of some child. So if you click on a child element the event will be prevented only when it will reach the document through bubbling, but in the mean time it will have been triggered.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM