Skip to content

fix(core): Prevent error when hasListeners is empty #7975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 21, 2025

Conversation

michaelwolz
Copy link
Contributor

This PR fixes a bug in the WebPlugin implementation where a TypeError is thrown if hasListeners() is called before a listener of the requested eventName is registered.

Problem

return !!this.listeners[eventName].length;

throws a TypeError if no event of the requested eventName is yet defined.

Fix

Changed the line to use optional chaining:

return !!this.listeners[eventName]?.length;

Safely check for the existence of the requested listener before accessing .length.

@jcesarmobile jcesarmobile added the needs reproduction needs reproducible example to illustrate the issue label Apr 14, 2025
@michaelwolz
Copy link
Contributor Author

@jcesarmobile here is a minimal example: https://github.com/michaelwolz/multipart-form-data-not-working-on-ios/blob/fix/web-plugin-type-error/src/js/capacitor-welcome.js#L74-L87

image

I mean this is not a super urgent issue. It just came up for me while developing a plugin and I though it's an easy fix.

Since the hasListeners method is protected, it will normally not be accessed from the outside of the plugin implementation (as I did for demonstrating it my example). But I think it's clear to see why this will fail instead of returning false what I would expect from this method.

@jcesarmobile jcesarmobile changed the title Prevent TypeError in hasListeners check in WebPlugin fix(core): Prevent error when hasListeners is empty Apr 16, 2025
@jcesarmobile jcesarmobile removed the needs reproduction needs reproducible example to illustrate the issue label Apr 16, 2025
@jcesarmobile jcesarmobile merged commit a4a0942 into ionic-team:main Apr 21, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants