samedi 26 septembre 2020

How to trigger custom code before every method of a class is executed

I am trying to create a pattern for Chrome Extensions where every time a method is called, based on whether the object is in "background script" or in "content script", either the method code is executed or a message is sent to background and the method is executed there. Manually written code would look like this:

class UnicornSpotter {

    constructor() {
         let that = this;
         listenToMessages((message) => {
             if(message === 'execute_unicorn_spotter') {
                 that.spot();
             }
         });
    }

    spot() {
        if(window.isBackgroundScript) {
             // Do the actual unicorn spotting here
        } else {
             sendMessageToBackgroundScript('execute_unicorn_spotter');
        }
    }

}

This works fine but I want to automate this message sending process so that I don't have to write code for each and every method separately. Is there a way in javascript that allows me to execute the message sending part automatically in the beginning of each method? Ideally, the methods would just contain the actual code and the message sending part is automatically triggered before the actual code.

Aucun commentaire:

Enregistrer un commentaire