Chrome extension: how to make executescript standby background?

I recently started developing my first Google Chrome extension and I had a problem. In my background.js script, every second I call script.js , smth like:

script.js

/* Some code */
if (condition1) {
    setTimeout(func1, 500);
    result = 1;
} else
if (condition2) {
    setTimeout(func2, 4000);
    result = 2;
} else
/*Some code */

result

background.js:

function func() {
    chrome.tabs.executeScript(null, {file: 'script.js'},
        function (result) {
            console.log(result[0]);
        }
    );    

    /* Some code using results of scipt.js */
};

var interval = null;
function onClickHandler(info, tab) {
    if (info.menuItemId == "addon") {
        if (interval != null) {
            clearInterval(interval);
            interval = null;
        } else {
            interval = setInterval(func, 1000);
        }
    }
};

chrome.contextMenus.onClicked.addListener(onClickHandler);

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({"title": "Addon", "id": "addon"});
}

I need a script call every max (1 second, after the previous execution). It should work as follows:

1. If previous script.js finished and 1 second after previous 
    interval call passed, call new script.js
2. If previos script.js finished and 1 second after previous 
    interval call haven't passed, wait for 1 second and call new script.js
3. If previous script.js haven't finished, wait until it finish 
    and if 1 second passed, call new script.js

Thanks in advance for your help.

+4
source share
1 answer

chrome.tabs.executeScript . . .

background.js

chrome.tabs.executeScript(null, {file: 'script.js'});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
     if (request.action === 'done') {
         console.log(request.result);
         // some code
         sendResponse({ action: 'next', arg: 2 });
     }

     // uncomment this if code is also asynchronous
     // return true;
});

// optional
// chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
//     chrome.tabs.sendMessage(tabs[0].id, { action: 'next', arg: 1 });
// });

script.js

function func1() {
    // some code
    var result = 1;
    done(result);
}
function func1(2) {
    // some code
    var result = 2
    done(result);
}

function runAction(which) {
    switch (which) {
        case 1: setTimeout(func1, 500); break;
        case 2: setTimeout(func2, 500); break;
    }
}

function done(result) {
    var msg = { action: 'done', result: result }};
    chrome.runtime.sendMessage(msg, function(response) {
        if (response.action === 'next') {
            runAction(response.arg);
        }
    });
}

// start
runAction(1);
+2

Source: https://habr.com/ru/post/1622996/


All Articles