1

Update: It seems the problem comes from the fact that Webpack executes each module in its own function, meaning that no modules can exist in the global scope. Is there any elegant way to solve this problem, so that I can define a function in a Webpacked content script and access it from a different content script?

Original:

in my primary content script I define a function

function foo() {
    console.log("foo")
}

In my background.js, I inject a new content script like so:

browser.tabs.query({currentWindow: true, active: true}).then(res => {
    browser.tabs.executeScript(res.id, {code: "foo()"})
})

In my tab's console, I see

VM181:1 Uncaught ReferenceError: foo is not defined
at <anonymous>:1:1

Both content scripts should be in the same execution environment, so I should be able to share functions and variables in both scripts.

I've recently added Webpack for building my Chrome extension, and I'm using Webextension-Polyfill to promisify the chrome.* API as browser.

In the old version of my code this worked fine, but now it's not working. I have a feeling it's because of Webextension-Polyfill but I honest' can't figure it out.

EDIT:

The executeScript code IS being run in the tab. I can console.log and it appears in the console. However, it doesn't seem to have access to the namespace of my existing content script.

EDIT 2:

I added another content script with

function foo() {
    console.log("foo")
}

And it's accessible from the injected script. So I guess it's something to do with Webpack.

Is it something to do with scoping in Webpack bundles?

Rory Byrne
  • 923
  • 1
  • 12
  • 22
  • _Both content scripts should be in the same execution environment._ You're wrong. Each content script is executed in its own environment isolated from others. If you want some function to be available in multiple content scripts, you have to place it in background script. – hindmost Mar 04 '19 at 13:27
  • Well I just added another content script with ``` function foo() { console.log("foo") }``` and it was accessible from the `executeScript` injected content script. So it should be possible - **see my edit** – Rory Byrne Mar 04 '19 at 13:29
  • 1
    @hindmost likely misunderstood that the OP meant the content scripts of **one extension** in a given tab share a single common isolated world environment, which is correct. What the OP wants to do is totally correct and it works without webpack. The OP's problem here is how to configure webpack to export/expose functions from the auto-generated closure into the global context. – wOxxOm Mar 04 '19 at 17:48
  • I see some similar questions when googling for "how to expose functions globally in webpack" and apparently you need to do it manually (or maybe there's a plugin) by assigning window.foo = foo where foo is the name of your function. – wOxxOm Mar 04 '19 at 17:50

0 Answers0