firefox-addon-webextensionsapplepayjs

getting a Firefox plugin to detect and mimic attempts to check for Apple Pay support


Now that Apple's credit card offering is out, I can get 2% cash back on purchases on the web made with Apple Pay. Unfortunately, my browser of choice is Firefox, which doesn't yet support Apple Pay.

I'd like to detect attempts to check for Apple Pay support, so I can alert myself in some way and switch over Safari to complete my purchase. Per Apple's docs, this check is performed via window.ApplePaySession.

So, I've attempted the following in an extension:

manifest.json

{
    "manifest_version": 2,
    "name": "applepay",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": [
                "*://*/*"
            ],
            "js": [
                "applepay.js"
            ]
        }
    ]
}

applepay.js

window.ApplePaySession = {
    canMakePayments: function () {
        console.log('canMakePayments');
        return Promise.resolve(true);
    },
    canMakePaymentsWithActiveCard: function () {
        console.log('canMakePaymentsWithActiveCard');
        Promise.resolve(true);
    },
};

I'm able to console.log(window) in applepay.js and get the whole object, but my changes to the object don't appear to take effect - it's acting like window is read-only. What am I missing?


Solution

  • In Firefox, content scripts (addon written in WebExtensions) don't share the same context as page scripts (website scripts).

    In your content script, do something similar to this:

    function notify(message) {
       console.log("do something");
    }
    
    exportFunction(notify, window, {defineAs:'notify'});
    

    After, the page script will see that window.notify exists.

    https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts