0

I'm trying to share functions across multiple backgrounds scripts in a chrome-extension. This works easily / by design in general as long as you add the scripts to the manifest.json, then a function called from the background.js can call code in another script as long as that other script is loaded first.

HOWEVER, I've tried a few Chrome extension generator templates that have a compilation step with gulp or webpack. (e.g. This one: https://github.com/samuelsimoes/chrome-extension-webpack-boilerplate)

But unfortunately function sharing breaks in the compiled background.js scripts.

I don't know what "magic" in the chrome-extension architecture is broken when compiled code is used.

Any advice/insights on what could be preventing function sharing appreciated. For details on the implementation e.g. webpack.config etc. please see the boilerplate as that's what I'm working with as well.

Omid Nikrah
  • 2,444
  • 3
  • 15
  • 30
sarora
  • 913
  • 9
  • 20
  • Sounds like a problem with that boilerplate because the ability to use multiple scripts in one page is not magic, it's a basic ability of any DOM-based page such as the extension background page, and it should just work. I guess that boilerplate doesn't want you to share the functions, it wants you to use modules either via `require()` or ES-modules. – wOxxOm Sep 16 '18 at 17:21
  • Still researching but i think it might be due to what webpack does as part of the bundling process as described here: https://stackoverflow.com/questions/34357489/calling-webpacked-code-from-outside-html-script-tag – sarora Sep 17 '18 at 15:53
  • Also, discovered that if i reveal all the functions using module.exports = { functionA: function A} etc. in the shared script, i can use these functions using require. Previously i wasn't exporting the functions (and didn't need to when webpack was not in use) but I guess this could be a solution. – sarora Sep 17 '18 at 16:07

1 Answers1

0

Answering my own question after some further research:

The issue appeared to be that webpack compiled each file into a module, necessitating changes to accomodate function sharing between these files.

Rather than adding module.exports statements to each background script, and having to prefix all my function references with the module name, I decided it was easier to rely on webpack (specifically the webpack-concat-plugin) to concat the background files together.

sarora
  • 913
  • 9
  • 20