开发者

Callback of chrome.tabs.executeScript is called before I want it to, need workaround

I have written an extension in Google Chrome that opens a tab to a webpage and injects code into that page. I have also registered a callback in chrome.tabs.executeScript to be called after the code's completion. This callback then opens another tab to another page and performs other actions, but I don't want that to happen until the first tab's page has been manipulated.

My is开发者_C百科sue is that this callback is called when it should be called, but not when I want it to be called:

My injected code contains a setInterval that checks to see if certain DOM elements are present before acting on the page, and I don't want the callback to activate until those DOM elements have been acted on.

I don't know of any way to have the injected code interact with the code in my extension page.

Is there any way to tell the code in my extension page that it's okay to keep going and call the callback at the right time?

Here's some code that explains what I'm doing now:

function doStuffWithTabs() {
    chrome.tabs.create({url: 'some/url/here'}, function(tab) {
        chrome.tabs.executeScript(tab.id, code: "var interval = setInterval(function(){if(jQuery(domElement).length){clearInterval(interval);workMagic();}},1);"}, function(){
            goForthAndConquer();
        });
    }
}

workMagic() represents the code that manipulates the DOM of the opened tab and goForthAndConquer() is what I want to happen when the manipulation of the opened tab is complete.

Right now, as you can plainly see, the injected code just registers the setInterval and immediately calls the callback. Again, I want the callback to happen after workMagic().


You need to do it in two steps.

script.js:

//I would ditch setInterval in favor of setTimeout
var interval = setInterval(function(){
    if(jQuery(domElement).length){
        clearInterval(interval);
        workMagic();
    }
},15); //15 is recommended minimum

function workMagic() {
    //manipulate dom
    chrome.extension.sendRequest({action: "finished", other: "data"});
}

background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.action === 'finished') {
        console.log("dom manipulation is finished in tab #", sender.tab.id);
        goForthAndConquer();
    }
});

function doStuffWithTabs() {
    chrome.tabs.create({url: 'some/url/here'}, function(tab) {
        chrome.tabs.executeScript(tab.id, {file: "script.js"});
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜