0

I have a background.js script that has functions for storage, API calls and all main functionalities.

My chrome extension has multiple pages. I want each of these pages to call functions of background.js.

Which concepts should I be looking at?

Sahil Maniar
  • 31
  • 1
  • 7
  • Don't overcomplicate: those scripts are probably small so you should simply include them in each page. Many people like to call the background functions directly via getBackgroundPage() call but it's usually bad design as it causes memory leaks. Some people use chrome.runtime messaging but again this may be an overcomplication. P.S. Depending on what the extension does, the background script may be even unnecessary. – wOxxOm May 09 '21 at 16:28

1 Answers1

0

Since you're talking about multiple pages, I'll just describe how to do it within a pop-up. According to Mozilla, The popup is just specified as an HTML file, which can include CSS and JavaScript files, as a normal web page does. Unlike a normal page, though, JavaScript can use all the WebExtension APIs that the extension has permissions for.

So you can simply include it in a <script> tag before your main script like so:


    <head>
        <title>Your Extension</title>
        <script defer src="background.js"></script>
        <script defer src="your_script.js"></script>
    </head>

It's better to just have functions in this background.js because like any normal page, it'll just run everything in the file. In case you want to include these in your content or background scripts, check out this StackOverflow question

Nayana Chandran
  • 1,416
  • 1
  • 16
  • 30