Popup widget: “Uncaught TypeError: callback is not a function” in load_tlib()
-
Hi,
I found a JavaScript error in the popup widget (wp-content/plugins/gtranslate/js/popup.js):
Uncaught TypeError: callback is not a function
Cause
load_tlib() is used in two ways: it is called with a callback function, and it is also registered directly as an event listener:
e.addEventListener(‘pointerenter’, load_tlib);
e.addEventListener(‘focusin’, load_tlib);When it is used as a listener, the browser passes the native Event object as the first argument. The current checks only test for truthiness (
if (callback)andcallback && callback()), and an Event object passes that test even though it is not callable.This causes two problems:
- If the library is already loaded (the else branch),
callback()is called on a MouseEvent/FocusEvent and throws “callback is not a function”. - If the library is not loaded yet, the Event object is registered as a ‘load’ listener on the script element. It is not a valid listener (it has no handleEvent method), so an error is also reported when the script finishes loading.
Steps to reproduce
- Open any page with the GTranslate popup widget.
- Hover over the language switcher. This loads lib.min.js.
- Move the pointer away and hover again, or tab into the switcher.
- Check the browser console: “Uncaught TypeError: callback is not a function”.
Suggested fix
Check that the argument is actually a function before using it:
function load_tlib(callback) {
if (!window.gt_translate_script) {
window.gt_translate_script = document.createElement(‘script’);
gt_translate_script.src = ‘https://cdn.gtranslate.net/widgets/latest/lib.min.js’;
document.body.appendChild(gt_translate_script);
if (typeof callback === ‘function’)
gt_translate_script.addEventListener(‘load’, callback, {once: true});
} else {
if (typeof callback === ‘function’) callback();
}
}Environment
- WordPress version: (local development)
- Widget type: Popup
- Reproduced in Chrome/Chromium; likely affects all browsers
Thanks!
- If the library is already loaded (the else branch),
You must be logged in to reply to this topic.