I created a custom Gutenberg block using plain JavaScript. That all works well (no build-step yay!). There is nothing done in PHP, it is JavaScript all the way -- aside from the single register_block_type_from_metadata() declaring my custom block.
This is a snippet of my block.json:
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "hvt/tabbed-block",
// ...
"editorScript": "file:./hvt.editor.js",
"script": "file:./hvt.js"
}
My custom block needs some (again plain) JavaScript initializing code in order to work. This initialization code is needed in both the editor and in the regular ('frontend') site. Therefore this code is inside hvt.js. This works fine in the 'frontend', and also in the editor whenever I open a post or page that already contains my custom block.
In short, my initialization code runs after DOMContentLoaded is triggered. The most important thing it does, is to attach some click listeners. The initialization code is called from the content loaded listener like this:
var HVT = {
initializeTabbedBlock: (tabbedBlock) => {
// Here some click listeners are added to descendants of tabbedBlock
}
};
document.addEventListener(
'DOMContentLoaded',
() => {
const tabbedBlocks = document.querySelectorAll('div.tabbed-block-tabs');
if (0 === tabbedBlocks.length) {
return;
}
for (const tabbedBlock of tabbedBlocks) {
HVT.initializeTabbedBlock(tabbedBlock);
}
}
);
Now in the editor, whenever my custom block is inserted on a post or page, I want to run the initialization code (i.e. HVT.initializeTabbedBlock) as well.
A small snippet of hvt.editor.js:
(function(blocks, blockEditor, components, data, element) {
blocks.registerBlockType(
'hvt/tabbed-block',
{
title: 'HVT tabbed block',
edit: () => {
const blockProps = useBlockProps({
className: 'hvt-tabbed-block',
});
// ...
},
save: () => {
const blockProps = useBlockProps.save({
className: 'hvt-tabbed-block',
});
// ...
},
}
);
})(window.wp.blocks, window.wp.blockEditor, window.wp.components, window.wp.data, window.wp.element);
So is there some hook I can attach to, whenever my custom block is inserted / appended in the visual editor?
(I do have tried working around me not finding a great hook to attach to, by adding a MutationObserver on document.body in the editor, and then trying to see if my custom block is added. That does however not work, because of the iframe that Gutenberg inserts. It seems that I do not receive any mutation events of the actual edited content, I only receive mutation events from the editor sidebars... Although I do think there is a much simpler non-shotgun way of achieving what I want.)
EDIT
I've updated my question a bit to iterate that I am solely using block.json to declare my custom block.