我有一个 chrome 扩展,它依赖于检测 Netflix 搜索栏上的点击事件。一旦用户将鼠标悬停在视频播放器上,div ([data-uia=timeline-bar]) 就会动态添加到 dom,因此我尝试使用事件冒泡来监听事件。
//after injecting jquery on page
$('body').on('click','[data-uia=timeline-bar]',function(e){
console.log('click detected');
})
它没有成功,所以我尝试在捕获阶段添加监听器。正在检测所有点击事件,但搜索栏点击。
document.addEventListener('click',
(e) => {console.log('click detected during capture phase')}
,true);
有没有办法监听([data-uia=timeline-bar])上的点击事件?
最佳答案
添加 MutationObserver到 [data-uia=timeline-bar] 元素的父元素,该元素观察其子元素何时发生变化,例如添加了时间轴栏?并在添加时间线栏元素后在回调中附加一个监听器?
// The timeline-bar's parent's data-uia is "timeline" in the Netflix player DOM.
let parent = document.querySelector("[data-uia=timeline]"),
options = {
childList: true
},
observer = new MutationObserver(mCallback);
observer.observe(parent, options);
function mCallback (mutations) {
for (let mutation of mutations) {
if (mutation.type === 'childList') {
for(let node of mutation.addedNodes){
if(node.getAttribute("data-uia") === "timeline-bar"){
node.addEventListener('click', () => {
alert("clicked");
// Do click stuff...
});
}
}
}
}
}
// To test the observer
btnAttr.addEventListener('click', function () {
let el = document.createElement("div");
el.setAttribute("data-uia", "timeline-bar");
el.innerText = "A TIMELINE-BAR";
parent.appendChild(el);
}, false);
关于javascript - 无法捕获 Netflix 搜索栏上的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69153293/