Search code examples
javascriptgoogle-chrome-extension

Confused about comma separated functions looking at chrome extension code


I'm attempting to learn more about chrome extensions and the best way I learn is by looking at stuff that works and trying to understand what it is doing. Well I've gotten a decent understanding of one I've been looking at but I see quite a few odd things that I'm not really sure why they are written that way. Here is a snippet of what I'm looking at:

chrome.runtime.onMessage.addListener((o, s, c) => {
  c(),
  (function(o, s, c) {
    <code>
  })
  (o.url, o.headers)
});

What I don't understand is why the first 2 statements are separated by a comma while the 3rd is just wrapped in parenthesis. If I remove the comma, then there is an error in the console stating

Error in event handler: TypeError: c(...) is not a function

It almost seems like somehow that is linking the c function with the function after the comma. I really don't know what is happening with it and it's not the only place that I see it. In the background.js the chrome.webRequest.onSendHeaders.addListener() is separated by a comma from the next function of chrome.runtime.onMessage.addListener()

chrome.webRequest.onSendHeaders.addListener(
  <code>
),
chrome.runtime.onMessage.addListener(
  <other code>
)

Tried to look up as best I could but couldn't quite find anything that answered my question. Can anyone explain it to me?


Solution

  • This is essentially equivalent to this code:

    The minified code is using the comma operator instead of semicolon between statements.

    It's using an IIFE to create a nested variable scope for <code>. (o.url, o.headers) are the arguments to the IIFE. In modern ES6 syntax this can be done using a block and let variable bindings.

    I've renamed the o parameter to the listener to o1 so it doesn't conflict with the o variable in the nested block.

    chrome.runtime.onMessage.addListener((o1, s, c) => {
      c(); 
      {
        let o = o1.url;
        let s = o1.headers;
        let c;
        // <code>
      }
    });