在 AEM Dialog 中注入 JavaScript

在 AEM 的对话框(Dialog)中,有时需要实现特定功能,例如自动填充数据或进行字段验证。以我的案例为例,我想在打开某些页面的属性配置界面时自动填充页面的虚拟URL (Vanity URL)

 1. 添加 extraClientlibs 属性
在组件的 cq:dialog 节点中,添加一个名为 extraClientlibs 的属性。该属性的值应与创建的自定义 Client Library 的 categories相匹配。

2. 创建 Client Library
按照常规方式创建 Client Library。请确保在 clientlibs 中定义的 categories与在 extraClientlibs 中设置的值一致。

3. 监听 dialog-loaded事件
为了确保自定义代码在dialog完全加载后执行,需要监听 dialog-loaded 事件,并将代码放在事件处理函数中。这样可以避免脚本过早执行导致的问题。

$(document).on("dialog-loaded", function () {
  // write code in handler
});

4. 使用 Coral UI
AEM 使用 Coral UI 来渲染dialog。在我的需求中,我需要确认 Vanity URL 字段所使用的 Coral UI 元素。经过检查,发现它是一个 coral-multifield


根据 Coral UI 文档,可以使用 instance.items.add 方法向 multifield 中添加新值。

示例代码
;
(function (document, $) {
    'use strict';

    const SLASH = '/';
    const CURRENT_PAGE_PATH = new URLSearchParams(window.location.search).get('item');
    let vanityURL = '/content/mysite/community/';

    if (CURRENT_PAGE_PATH) {
        const pattern = /^\/content\/mysite\/community\/([a-z]+)\/([a-z]+)\/knowledge\/([a-zA-Z0-9-]+)\/([a-zA-Z0-9-]+)\/([a-zA-Z0-9-]+)$/;
        if (pattern.test(CURRENT_PAGE_PATH)) {
            const matches = CURRENT_PAGE_PATH.match(pattern);
            if (matches) {
                vanityURL += matches[1] + SLASH + matches[2] + '/knowledge/' + matches[3] + SLASH + matches[5];
                console.log(vanityURL);
            }
            $(document).on("dialog-loaded", function () {
                addVanityURL();
            });
        }
    }

    const addVanityURL = function () {
        const multifieldEl = document.querySelector('coral-multifield[data-granite-coral-multifield-name="./sling:vanityPath"]');
        if (multifieldEl.items.length === 0) {
            multifieldEl.items.add({
                content: {
                    innerHTML: `<input is="coral-textfield" name="./sling:vanityPath" value=${vanityURL}>`
                }
            });
        }
    }

})(document, Granite.$);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值