简体   繁体   English

Javascript 单击事件侦听器仅触发一次

[英]Javascript click event listener fires only once

I have a Chrome extension that intercepts and checks tweets before they get posted.我有一个 Chrome 扩展程序,可以在推文发布之前拦截并检查它们。 To do this, I've add an event listener to the Tweet button.为此,我向Tweet按钮添加了一个事件侦听器。 Sine the content is dynamic, I use the solution proposed in this thread :由于内容是动态的,我使用此线程中提出解决方案

initialize : function() {
    let that = this;
    let jsInitChecktimer = setInterval(checkForJsFinished, 111);
    function checkForJsFinished () {
        if (document.querySelector("div[data-testid='tweetButtonInline']")) {          
            clearInterval (jsInitChecktimer);
            console.log("Button found");
            that.addSubmitNewTweetClickHandler();
        }
    }
},

addSubmitNewTweetClickHandler : function() {
    let that = this;
    let buttonSubmitTweet = document.querySelector("div[data-testid='tweetButtonInline']");
    buttonSubmitTweet.addEventListener('click', function(e) {
        console.log("CLICK");
        // Stop default event from happening
        e.preventDefault();
        e.stopImmediatePropagation();
        // Do stuff
    });
},

If the tweet passed the checks alright, it gets submitted by programmatically triggering the event using .trigger('click') .如果推文通过了检查,它会通过使用.trigger('click')以编程方式触发事件来提交。

This works fine, but only once.这工作正常,但只有一次。 After a tweet has been submitted and posted, the event listener on the Tweet button is gone, and I cannot intercept the next tweet to check it.鸣叫已经提交并公布后,对事件侦听Tweet按钮消失了,我不能拦截下一条推文进行检查。 I've tried calling initialize() after submitted again -- maybe the button gets removed and newly added to the DOM (it actually disappears fire a moment when submitting a tweet) -- but the querySelector finds the button immediately.我已经尝试在再次提交后调用initialize() - 也许按钮被删除并新添加到 DOM (它实际上在提交推文时消失了一会儿) - 但querySelector立即找到了按钮。 But even after calling initialize() again, no click even on the Tweet button fires.但即使在再次调用initialize()之后,也不会触发Tweet按钮。

What could be the issue here?这里可能是什么问题? My problem is that I don't even know where to look for and how to debug this.我的问题是我什至不知道在哪里寻找以及如何调试它。

After many more hours, I've finally figured it out.几个小时后,我终于弄明白了。 The problem was essentially the highly dynamic content of the new Twitter website.问题本质上是新 Twitter 网站的高度动态内容。 After submitting a tweet, the Tweet button gets indeed removed and added again.提交鸣叫后, Tweet按钮被确实移走后又重新加入。 In needed to do a serious of changes:在需要做一个严重的变化:

  • Use a MutationObserver to keep track of any changes.使用MutationObserver来跟踪任何更改。 Every time there's a change, call the initialize() function.每次有变化时,调用initialize()函数。 To avoid too many calls, I do this in case of certain changes (unnecessary detail here)为避免调用过多,我会在发生某些更改时执行此操作(此处为不必要的详细信息)

  • Change the addSubmitNewTweetClickHandler() method so that the event listener first gets removed in order to avoid duplicate listeners (please note that I use objects hence the use of this compared to my original question)更改addSubmitNewTweetClickHandler()方法,以便首先删除事件侦听器以避免重复的侦听器(请注意,我使用对象,因此与我的原始问题相比使用了this

     addSubmitNewTweetClickHandler : function() { let that = this; let buttonSubmitTweet = document.querySelector("div[data-testid='tweetButtonInline']"); buttonSubmitTweet.removeEventListener('click', this.handleSubmitNewTweetClick ); this.handleSubmitNewTweetClick = this.handleSubmitNewTweetClick.bind(this) buttonSubmitTweet.addEventListener('click', this.handleSubmitNewTweetClick ); },

    This change required to create the reference function handleSubmitNewTweetClick此更改需要创建参考函数handleSubmitNewTweetClick

Overall, it's still not a perfect solution since I call initialize() many unnecessary time.总的来说,它仍然不是一个完美的解决方案,因为我调用了initialize()很多不必要的时间。 However, I failed to reliably identify when the Tweet button was added to the document.但是,我无法可靠地确定何时将Tweet按钮添加到文档中。 When I used the MutationObserver none of the added nodes had the attribute data-testid which I need to identify the correct button.当我使用MutationObserver ,所有添加的节点都没有我需要识别正确按钮的属性data-testid I have node idea why this attribute was not there.我知道为什么这个属性不存在。 Maybe the attribute is added some times after added to button, but even with an additional MutationObserver looking for attribute changes I could detect this.也许该属性在添加到按钮后会添加几次,但即使使用额外的MutationObserver寻找属性更改,我也可以检测到这一点。

Anyway, it works now and it's only for a prototype.无论如何,它现在可以工作,并且仅适用于原型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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