congIA
congIA

Reputation: 25

Declaring and listening to custom Chrome Ext event

I'm trying to make a workaround for the asynchronous nature of Chrome extension function by declaring and listening to custom Chrome Extension events. Thus far, I've not found any relevant solution.

So, this is the structure of my background.js (with "persistent": false set in manifest.json):

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active: true, currentWindow: true},
        function(tabs) {
            //Action 1: chrome.tabs.sendMessage(tabs[0].id, ...
            //Action 2: chrome.tabs.sendMessage(tabs[0].id, ...
            //Action 3: chrome.tabs.create({url: someUrl, ...
        }
    )
});

Action 3 must only be performed after Action 1 and 2 has been completed. I'm thinking along the line of after completing its actions, action 1 and 2 each send an event like Action1CompleteEvent and Action2CompleteEvent and action 3 listens to these event. Once both has been detected, it will perform its action.

Is this possible? What are some ways to achieve the same effect that people have been using?

Thank you for your time.

Upvotes: 0

Views: 33

Answers (1)

Xan
Xan

Reputation: 77482

There is no way "around" asynchronicity.

Every async Chrome API function accepts a callback parameter. The callback is guaranteed to be called after the operation.

So, you need to chain your code:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active: true, currentWindow: true},
        function(tabs) {
            chrome.tabs.sendMessage(/*...*/, function() {
              chrome.tabs.sendMessage(/*...*/, function() {
                chrome.tabs.create(/*...*/);
              });
            });
        }
    )
});

If you want, you can try and employ Promises, though the Chrome API does not natively work with them - you'll need to wrap it with some helper functions. This may make your code more manageable.

Upvotes: 1

Related Questions