google-sheetsgoogle-apps-script

How to run an onEdit function across multiple Google Sheets using a shared Apps Script library


I have 8 different Google Sheets with the same structure, and I want to run the same onEdit() trigger-based script in all of them.

However:

Each sheet now includes this library. My goal is to have the onEdit() trigger in each spreadsheet call a function from the library, so the logic is centralized and protected.

My Question: Do I need to manually create a basic onEdit(e) function in each spreadsheet that calls the library function, or is there a way to automatically bind the trigger to the library without modifying each sheet?

Requirements:

Thanks in advance!


Solution

  • From your question, I guessed your expected result is as follows.

    In this case, how about using the installable OnEdit trigger? The installable trigger can be also installed by a Google Apps Script project different from the target Google Apps Script project. So, I guessed that when the installable OnEdit trigger is used, your goal might be able to be achieved. The references are as follows.

    When this is used, the usage is as follows.

    1. Prepare Google Apps Script project.

    From I created a new appscript project from google drive pasted my script there, I guessed that you already had a Google Apps Script project. You can use this project.

    2. Sample script.

    Please copy and paste the following script to the script editor of the Google Apps Script project. And, please set the 8 Spreadsheet IDs of your Spreadsheets to spreadsheetIds. And, please set your OnEdit script to the function installedOnEdit. Please be careful about the variable name of the event object.

    // This function is used as the OnEdit trigger.
    function installedOnEdit(e) {
    
      // Please set your script of OnEdit.
    
    }
    
    function sample() {
      const spreadsheetIds = ["### spreadsheetId 1 ###", "### spreadsheetId 2 ###", "### spreadsheetId 3 ###",,, ];
      const functionName = "installedOnEdit";
    
      spreadsheetIds.forEach(id => {
        const ss = SpreadsheetApp.openById(id);
        ScriptApp.newTrigger(functionName).forSpreadsheet(ss).onEdit().create();
      });
    }
    

    Note:

    References: