3

I have added a payment method renderer javascript file to a magento 2 module. I want one of the functions in the js to redirect to another page on the site.

How do I get the base url so that I can generate the full url correctly?

Currently I have this js method renderer:

define(
    [
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/view/payment/default'
    ],
    function (quote, Component) {
        'use strict';

        return Component.extend({
            defaults: {
                template: 'VendorName_ModuleName/payment/mypaymentmethod'
            },

            startPayment: function(){
                var url = "modulename/mypaymentmethod/generatepaymentrequest"
                console.log(url);
                // TODO prepend base url before redirecting
                window.location.href = url;
            },
        });
    }
);
7

You can use the mage/url module in the javascript to build the URL for you. Just call build with the path you want to append to the base URL and it will return the full URL.

To be specific; add 'mage/url' to the list of modules at the start of the define statement and add an argument to the module's main function, I called it urlBuilder in my example. Then you can call urlBuilder.build("some/path") to generate a full URL.

Something like the following example:

define(
    [
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/view/payment/default',
        'mage/url'
    ],
    function (quote, Component, urlBuilder) {
        'use strict';

        return Component.extend({
            defaults: {
               template: 'VendorName_ModuleName/payment/mypaymentmethod'
            },

            startPayment: function(){
                var url = urlBuilder.build("modulename/mypaymentmethod/generatepaymentrequest");
                window.location.href = url;
            },
        });
    }
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.