'TinyMCE iframe is null
I have two custom fields that use wp_editor() on a WordPress custom post type, which basically embeds an iframe where the content is. I'm trying to capture when someone tries to change one of the values, which I'm learning requires the addEventListener function with the keydown approach.
My problem is that I keep getting an error saying the iframe is null or tinyMCE is undefined. My script works fine in the console, but if I add it from my plugin it won't work. I'm assuming it's a loading issue? But how do I force the JavaScript to not load until after the iframe content or tinymce?
// Fields from metabox:
$pf = 'eri_post_field_';
$meta_keys = [ $pf.'part_email_msg_pre', $pf.'part_email_msg_post' ];
foreach ($meta_keys as $meta_key) {
$meta_value = get_post_meta( $post_id, $meta_key, true );
$settings = array( 'media_buttons' => false, 'textarea_rows' => 10, 'textarea_name' => $meta_key );
wp_editor( $meta_value, $meta_key, $settings );
}
// JavaScript underneath the fields
echo '<script>
var saveNotice = document.getElementById("part_email_save_notice");
var saveNoticeHide = document.getElementById("part_email_save_notice_hide");
var emailMessageFields = [
"part_email_msg_pre",
"part_email_msg_post"
];
emailMessageFields.forEach(function callback(value, index) {
var iframeId = "'.$pf.'" + value + "_ifr";
var iframe = document.getElementById(iframeId);
console.log(iframe); // <-- NULL
// ERROR: Cannot read properties of null (reading "contentWindow")
// var editor = iframe.contentWindow.document.getElementById("tinymce");
// editor.addEventListener("keydown", function (e) {
// saveNotice.style.display = "block";
// saveNoticeHide.style.display = "none";
// console.log("Run: " + value);
// }, { once: true });
// ERROR: Uncaught TypeError: Cannot set properties of null (setting "onload")
document.getElementById(iframeId).onload = function() {
var editor = iframe.contentWindow.document.getElementById("tinymce");
editor.addEventListener("keydown", function (e) {
saveNotice.style.display = "block";
saveNoticeHide.style.display = "none";
console.log("Run: " + value);
}, { once: true });
};
// ERROR: Uncaught ReferenceError: tinymce is not defined
// tinymce.init(...);
});
</script>';
I also tried to insert the JavaScript from add_action('admin_footer'...), but that didn't make a difference. Tried admin_enqueue_scripts as well. Any suggestions?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
