Zend certified PHP/Magento developer

Magento 2: Properly access an external js variable in the checkout

Pure HTML Example

I’m trying to do something as simple as the following html code:




Just to explain, the MyExtVar is generated by the external script url which uses the window.MyExtApiKey variable. When you click the button, it runs. Simple as that.

Magento 2 simple test

Just for testing purpose, I know this is not the right way of dealing with JS, I just want to test so I’ve added a block via a module in view/frontend/layout/checkout_index_index.xml

< ?xml version="1.0"?>

    
        
            
        
    

And then, in my view/frontend/templates/init.phtml I use the exact same code as the HTML example :




BUT, when I click the button I get a MyExtVar is not defined error.

Note that the external JS is properly loaded, I can see it from the Network tab in the console.

So two questions:

  • First, why is that behaving differently that the pure HTML example?
  • Second, how can I fix that ?