简体   繁体   English

Chrome扩展无限循环

[英]Chrome extension infinite loop

I have an infinite loop that I do not understand 我有一个我不明白的无限循环

function bot(cartInfo, tab) {
    function injector(file, message) {
        chrome.tabs.executeScript(tab.id, {file: file, runAt: 'document_end'}, function(r) {
            chrome.tabs.sendMessage(tab.id, message, function(result) {
            });
        });
    }

    //this section gets repeated over and over
    chrome.tabs.onUpdated.addListener(
        function myListener(tabId, changeInfo, updateTab) {
            injector('addToCart.js', cartInfo.sizeInfo);
            chrome.tabs.onUpdated.removeListener(myListener);  
        } 
    );

}

I want it to enter the addListner section call the injector( which runs another file addToCart) once and return and exit. 我希望它一次进入addListner节,调用喷射器(运行另一个文件addToCart)并返回并退出。 If I remove the line chrome.tabs.onUpdated.removeListener(myListener); 如果删除行chrome.tabs.onUpdated.removeListener(myListener); It will work but calls the injector function infinitely. 它可以工作,但是会无限调用喷油器功能。 If I keep the line it exits the loop, but does not execute the injector. 如果我保留该行,它将退出循环,但不执行注入器。 Is there a way to get around this? 有办法解决这个问题吗? or a way to remove the listener while inside the addToCart file so I know it has been executed at least once? 还是一种在addToCart文件中删除侦听器的方法,以便我知道它至少已执行一次?

I don't recommend having the removeListener within the callback it's removing. 我不建议在要删除的回调中包含removeListener I think if you refactor the code a little you should be able to get it to work. 我认为,只要稍微重构一下代码,就应该可以使它工作。 This makes the listener method more explicit and moves the removeListerner to trigger at the end of injector method. 这使侦听器方法更加明确,并且将removeListerner移动到在injector方法结束时触发。

function bot(cartInfo, tab) {

    var myListener = function(tabId, changeInfo, updateTab) {
        injector('addToCart.js', cartInfo.sizeInfo);
    }

    function injector(file, message) {
        chrome.tabs.executeScript(tab.id, {file: file, runAt: 'document_end'}, function(r) {
            chrome.tabs.sendMessage(tab.id, message, function(result) { });
        });
        chrome.tabs.onUpdated.removeListener(myListener);
    }

    chrome.tabs.onUpdated.addListener(myListener);
}

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

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