Manually setting user bound properties

1k Views Asked by At

I am working on a script, which needs to store a secret API key. In the old editor, there was an option to set user properties directly from the UI of the editor (which was in meantime removed), and I do not see any similar option in the new one. I saw multiple answers detailing how to set them through the UI of the spreadsheet or other "finicky" way. Is it possible to set that property through the Script UI directly?

1

There are 1 best solutions below

0
On

It is not available anymore in the new editor. I have 2 options in mind.

  1. Switch to the legacy editor to set your properties using the Script UI.

  2. You can use Properties Service to store simple data in key-value pairs scoped to one script (Script Properties), one user of a script (User Properties), or one document (Document Properties).


Properties Service Methods:

  • getDocumentProperties(), Gets a property store (for this script only) that all users can access within the open document, spreadsheet, or form.

  • getScriptProperties(), Gets a property store that all users can access, but only within this script.

  • getUserProperties(), Gets a property store that only the current user can access, and only within this script.


Example on how to create user properties key-value pair:

  // Sets several user properties, then retrieves them and logs them.
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperties({
    'cow': 'moo',
    'sheep': 'baa',
    'chicken': 'cluck'
  });

  var animalSounds = userProperties.getProperties();
  for (var kind in animalSounds) {
    Logger.log('A %s goes %s!', kind, animalSounds[kind]);
  }

  var keys = userProperties.getKeys();
  keys.forEach(key=>{
    Logger.log("Key: "+key+", Value: "+userProperties.getProperty(key));
  })

Output:

enter image description here


How it works:

  1. When you get PropertiesService.getUserProperties() it will return a properties object that acts as the interface to access your user properties

  2. You can use setProperties(properties) to set your user specific key-value pair.

  3. You can access your key-value pair using either getProperty(key) or by getProperties() as shown in the sample code.


Test

I modified the script after adding user properties and run the code on 2 different users (owner and another user) to verify if user properties added will only be available to the user who created it.

Code:

  var userProperties = PropertiesService.getUserProperties();

  var keys = userProperties.getKeys();
  Logger.log(keys.length);
  keys.forEach(key=>{
    Logger.log("Key: "+key+", Value: "+userProperties.getProperty(key));
  })

Owner Result:

enter image description here

Another User Result:

enter image description here