Search code examples
shopwareshopware6

Subscribe to a third party Javascript Plugin


I try to subscribe to a javascript event in my own javascript plugin, but its not working properly and I dont have a clue what I am missing here.

In my init function of my javascript plugin I have the following code:

const SwkwebProductSetConfigurator = window.PluginManager.getPluginInstances("SwkwebProductSetConfigurator");
console.log(window.PluginManager.getPluginList());
console.log(SwkwebProductSetConfigurator.length);

if(SwkwebProductSetConfigurator.length > 0){
    SwkwebProductSetConfigurator[0].$emitter.subscribe(
       'swkwebProductSet/onSetAddToCart', this.onSetAddToCart[this]
    );
}

The list is showing the plugin, but console.log(SwkwebProductSetConfigurator.length); is outputting 0?!? When I get the instance of e.g. "AccountMenu" count is one.

When I console.log in the init function of the third party plugin and mine, I see, that mine is executed first.

How can I solve this?

Update: OK, so its important when each Plugin is installed! I uninstalled the other Plugin and reinstalled it. Afterwards I could subscribe to the event from the other plugin. Its no problem to uninstall/install plugins in a dev environment, but how can this be managed in a production shop? Additionally when my plugin is available in the shopware store?


Solution

  • The plugins are initialized on the DOMContentLoaded event so by then all plugins should've been registered and you should be able to subscribe to their events.

    // how the plugins are initialized
    document.addEventListener('DOMContentLoaded', () => PluginManager.initializePlugins(), false);
    
    // how you can do stuff depending on another plugin being registered
    document.addEventListener('DOMContentLoaded', () => {
        const SwkwebProductSetConfigurator = window.PluginManager.getPluginInstances("SwkwebProductSetConfigurator");
        // ...
    });