Skip to content

Commit 76d2a1a

Browse files
author
Rodrigo Gomez Palacio
committed
Instead of relying on the button class name, switch to detect post-status changes in JS
Motivation: it's fragile to rely on a 3rd party button class name to listen to. Especially since this can potentially change between WP versions. Instead, we can use the 'core/editor' API on `wp.data` to listen to changes in the post status and uncheck the checkbox that way.
1 parent 6309413 commit 76d2a1a

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

v3/onesignal-metabox/onesignal-metabox.js

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,24 +33,37 @@ window.addEventListener("DOMContentLoaded", () => {
3333
setDisabled(customiseWrapChild, !customisePost.checked);
3434
});
3535

36-
// Watch for the Publish button to be added to the DOM
37-
const observer = new MutationObserver((mutations, obs) => {
38-
const publishButton = document.querySelector('.editor-post-publish-button__button');
39-
40-
if (publishButton) {
41-
publishButton.addEventListener('click', function() {
42-
setTimeout(() => {
43-
if (sendPost && sendPost.checked) {
44-
sendPost.click();
45-
}
46-
}, 1000);
47-
});
48-
obs.disconnect(); // Stop observing once we've found and handled the button
49-
}
50-
});
36+
// make sure WordPress editor and API are available
37+
if (typeof wp === 'undefined' || !wp.data || !wp.data.select) {
38+
console.warn('wp.data is not available.');
39+
return;
40+
}
41+
42+
const editorStore = wp.data.select('core/editor');
5143

52-
observer.observe(document.body, {
53-
childList: true,
54-
subtree: true
44+
// track initial state of checkbox
45+
const osUpdateCheckbox = document.querySelector('#os_update');
46+
const wasCheckedInitially = osUpdateCheckbox ? osUpdateCheckbox.checked : false;
47+
48+
// track previous post status to detect changes
49+
let previousStatus = editorStore.getCurrentPostAttribute('status');
50+
51+
// subscribe to state changes
52+
wp.data.subscribe(() => {
53+
const currentStatus = editorStore.getCurrentPostAttribute('status');
54+
55+
// check if the post status changed to "publish"
56+
if (previousStatus !== currentStatus && currentStatus === 'publish') {
57+
previousStatus = currentStatus;
58+
59+
if (wasCheckedInitially) {
60+
// uncheck the os_update checkbox
61+
if (osUpdateCheckbox && osUpdateCheckbox.checked) {
62+
osUpdateCheckbox.checked = false;
63+
}
64+
}
65+
} else {
66+
previousStatus = currentStatus;
67+
}
5568
});
5669
});

0 commit comments

Comments
 (0)