Question

I want to created a public database so other extensions can access it, create tables, add entities, remove entities what they want.

I saw that the only way to do this is to use message passing between multiple extensions, but this solutions is problematic for me, because I need permission to "management" in order to know the other extensions IDs.

There is an option for sending messages to all extensions without knowing their ID? or there is another way of implementing public db without pub-sub synchronization?

btw - I can use localStorage or WebSQL.

Was it helpful?

Solution

Could you create an extension, hub, that is used to register other extensions and has a messaging hub.

All of the extensions that wanted to communicate with the public DB could then do it via the hub. Upon initialization from the background page, each extension could register with the hub their ID and which events they want to subscribe to.

Register action from each extension

chrome.tabs.sendRequest("hub", {
    action: "register",
    key: "somePrivKey",
    id: "extId", 
    subscribeTo: ["createFoo", "deleteFoo"]
});

Then, each action performed would be communicated to the hub:

chrome.tabs.sendRequest("hub", {
    action: "createFoo",
    key: "somePrivKey",
    context: 1
});

The hub extension would then listen to events. For "register" actions the hub would register the extension as an endpoint for the "subscribeTo" actions. For other actions ("createFoo" or "deleteFoo") the hub would iterate over the list of registered extensions for the event and perform a sendRequest that sends the "action" name and an optional "context".

A shared "key" could be known between the hub and all the extensions that want to communicate to prevent the hub from listening to events not from a known source.

Hub extension background.js:

var actionToExtMap = {};

chrome.extension.onRequestExternal.addListener(function(request, sender, sendResponse) {
    if (request.key === "somePrivKey") {
        if (request.action === "register") {
            for (i = 0; i < request.subscribeTo.length; i++) {
                var action = request.subscribeTo[i];

                var extsionsForAction = actionToExtMap[action] || [];
                extsionsForAction.push(request.id)
            }

        } else if (request.action) {
            var extensionsToSendAction = actionToExtMap[request.action];
            for (i = 0; i < extensionsToSendAction.length; i++) {
                chrome.extension.sendRequest(extensionsToSendAction[i], {
                    action: request.action,
                    context: request.context //pass an option context object
                }
            }
        }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top