2

How to correctly get site url inside js file within magento module?

It should contain protocol (http | https) and domain name.

No path required.

Format http://example.com

2 Answers 2

6

If you are following best practices and using Require JS to load your Javascript this is a simple task. If you are not following best practices, now is the time to start ;)

I believe the best way is to pass the URL to the JS file via the PHTML template like so:

Template file

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "tenLooks": {
                        "component": "Ben_AppTest/js/ten-looks",
                        "dataUrl": "<?php echo $block->getViewFileUrl('Ben_AppTest::js/data.js'); ?>"
                    }
                }
            }
        }
    }
</script>

Javascript File

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            console.log(this.dataUrl);
        }
    });
});

enter image description here

4

You should not get the base url in your JS files.
Write your js files are ui widgets and the base url should be a parameter.
Then pass that parameter from the template that uses the ui widget.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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