Magento – Magento 2 : add custom JavaScript to CMS page create/edit in admin

adminadminhtmljavascriptrequirejs

I would like to add some custom JavaScript to the CMS page create/edit pages in Magento 2 admin. So basically when you want to create a new page or edit an existing one, it should load some JavaScript preferably before body closing tag.

How would I go about doing this?
I've already looked at the following posts:

The one by Alan Storm did work, but it loaded my js on all admin pages, but that's not the idea, I just want to load my js for the CMS page create and edit pages.

Does anyone know how to do this?

Best Answer

Try following way:

Vendor/Module/view/adminhtml/layout/cms_page_edit.xml


<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Cms\Custom" name="info" before="before.body.end" template="Vendor_Module::cms/custom.phtml" />
        </referenceContainer>
    </body>
</page>

Vendor/Module/Block/Cms/Custom.php


namespace Vendor\Module\Block\Cms;

class Custom extends \Magento\Framework\View\Element\Template
{

}

Vendor/Module/view/adminhtml/templates/cms/custom.phtml


Custom Block
<script>
    require([
        'jquery'
    ], function($){
        $(document).ready(function() {
            console.log('here')
        } );
    })
</script>