TyGoss
TyGoss

Reputation: 157

Firefox extension development: How do I create a global function inside a content script, so other loaded script files can access it?

In my main.js file, I have a PageMod that includes a base.js file:

pageMod.PageMod({
    contentScriptFile: ["./base.js"]

I have a function inside of my base.js file

function setupPayment(){ /* DO STUFF HERE */ }

Inside my base.js file, I'm also loading other JS files

$.getScript("https://checkout.stripe.com/checkout.js", function(){
    $.getScript( self.options.stripe );
});

Inside of my stripe.js file, I'm trying to call the setupPayment function that's in my base.js file

var yearhandler = StripeCheckout.configure({
    key: "pk_live_...",
    image: "image.png",
    name: "SHINE",
    description: "Subscription",
    panelLabel: "Subscribe",
    allowRememberMe: false,
    token: function(token) {

        plan = "yearly";

        setupPayment(token,plan);

    }
});

But setupPayment returns undefined.

And after doing some testing, it looks like any script included via $.getScript can't access any functions inside of my base.js content script? Is there any way to make a function inside of my base.js content script global across all my other scripts files that I load?

Thanks for your help!

Edit: the reason setupPayment() has to be in the base.js file, is so that it can communicate with the main.js file and store some information.

Upvotes: 1

Views: 254

Answers (2)

therealjeffg
therealjeffg

Reputation: 5830

You can now export a function from the content script into the page, see this blog post for the gory details. The code would look like this:

function setupPayment(args, callback) {
  // some code
  callback(result); 
  // your callback should use postMessage to send data back to the
  // content script, see these docs:
  // https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/Interacting_with_page_scripts#Communicating_with_page_scripts 
}

exportFunction(setupPayment, unsafeWindow, {defineAs: "setupPayment"});

Upvotes: 1

the8472
the8472

Reputation: 43052

ContentScripts run in sandboxes, I don't know what jquery does internally, but it certainly is not designed to be aware of multiple javascript contexts and mozilla's xray wrappers, so it probably just injects a <script> tag into the DOM which then runs the loaded javascript inside the page context instead of the contentScript sandbox.

And I'm not even sure how you get access to jquery in your sandbox, considering that you only load base.js.

So it looks like a good chunk of your addon code is actually running in/loading scripts into the untrusted page context.

the reason setupPayment() has to be in the base.js file, is so that it can communicate with the main.js file and store some information.

Not quite. You can export a privileged function to the page context via exportFunction, which is available inside the sandbox.

Upvotes: 0

Related Questions