0

I have a chrome-extension with lots lines of code. More and more people demand that I offer that extension on other browsers (like firefox), too.

Because it is a chrome extension, a lot of chrome-specific functions are included. As I start I want to put all chrome-specific methods in a javascript-file "chrome.js" and encapsulate the chrome-functions with my own so I could easily create other browser-specific methods.

This is quite easy for simple methods:

function geti18nMessage(messageId) {
   return chrome.i18n.getMessage(messageId)
}

But how can I encapsulate (asynchronous) methods that return a function?

Example:

chrome.runtime.sendMessage(
            {
                Action: "Load"
            }, function (response)
    {
    console.log("response is "+response);
    });

This isn't really chrome-specific, but the chrome-issue is a real-world-example for my problem.

2
  • Just give it a callback parameter, like the native sendMessage method has? Commented Nov 10, 2014 at 22:45
  • i dont see a problem here , would you clarify the issue ? Commented Nov 10, 2014 at 22:48

1 Answer 1

2

You can just pass the function through like any other argument:

function sendMessage(options, fn) {
   return chrome.runtime.sendMessage(options, fn);
}

This assumes that you are committed to the same Chrome callback scenario on all platforms. If you want to customize the callback to be something of your own design, then you can replace it like this:

function sendMessage(options, fn) {
   return chrome.runtime.sendMessage(options, function() {
       // do any processing of the chrome-specific arguments here
       // then call the standard callback with the standard arguments you want to
       // support on all platforms
       fn(...);
   });
}
Sign up to request clarification or add additional context in comments.

1 Comment

easier than expected. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.