Chrome扩展程序:如何使后台等待执行文件?

时间:2016-01-05 22:10:11

标签: javascript google-chrome google-chrome-extension

我最近开始开发我的第一个Google 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"});
}

所以我需要每个max(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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

chrome.tabs.executeScript回调期望同步结果。然而,您的逻辑是异步的。在这种情况下,您必须设置正确的inter-process communication

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