Chrome扩展:如何使后台等待执行

Chrome Extension: How to make background wait executescript?

本文关键字:后台 等待 执行 何使 扩展 Chrome      更新时间:2023-09-26

我最近开始开发我的第一个谷歌Chrome扩展,遇到了一个问题。在我的background.js脚本中,我每秒调用script.js

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"});
}

因此,我需要每次调用脚本的最大值(1秒,在前一个executeScript之后)。它应该以这种方式工作:

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

提前感谢您的帮助。

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);