Magento – Get Base URL value from JS in adminhtml/frontend (Magento 2)

adminhtmlfrontendjavascriptmagento2

I want to send AJAX request to the REST API on server from popup in adminhtml and I need "Base URL" value to construct complete URL. I see the following code on the HTML page:

<html><head>
    <script>
        var BASE_URL = 'http://host.com/admin/catalog/';
        var FORM_KEY = 'aAopAjLMymxMN17J';
        var require = {
            "baseUrl": "http://host.com/pub/static/adminhtml/Magento/backend/en_US"
        };
    </script>
</head></html>

I can remove /admin/catalog/ from global BASE_URL and get the target value, but is there a better way to get Base URL value in JS in adminhtml?

This global variable does not present on the frontend:

<html><head>
    <script>
        var require = {
            "baseUrl": "http://host.com/pub/static/frontend/Magento/luma/en_EN"
        };
    </script>
</head></html>

Does exist a method to get Base URL value in JS that is common for both adminhtml & frontend?

Best Answer

Put this code line in your block:

  • You should try $block->getBaseUrl().
  • Get base url admin : $block->getUrl('adminhtml') => http://host.com/admin
Related Topic