Search code examples
google-apps-scriptgoogle-slides-apigoogle-slides

How to assign custom properties to Google Slides contents using Google-App-Script


I would like certain images have an extra property. Essentially my goal is to uniquely identify the images i've added using App Script code and not in the Google Slides app. This is what I have so far

const dataBlob = Utilities.newBlob(dataBaseEight);
const presentation = SlidesApp.openByUrl('https://docs.google.com/presentation...');
const slides = presentation.getSlides();
const x = slides[0].insertImage(dataBlob);
x.isAddedUsingAppScript = true;
Logger.log(x.isAddedUsingAppScript);//true
Logger.log(slides[0].getImages()[0].isAddedUsingAppScript);//false

FYI I always make sure to have no images in the first slide prior to testing the code.


Solution

  • Looking at the Image Class, there are no methods to add custom attributes to the images, but you have a couple workarounds.

    insertImage(blobSource) returns the image that was inserted, so you can use setDescription() on it to add your true/false value and call it later with getDescription():

    const dataBlob = Utilities.newBlob(dataBaseEight);
    const presentation = SlidesApp.openByUrl('https://docs.google.com/presentation...');
    const slides = presentation.getSlides();
    const x = slides[0].insertImage(dataBlob);
    
    x.setDescription("true")
    
    Logger.log(slides[0].getImages()[0].getDescription()) //returns "true"
    

    The problem with this is that the "Description" field is also editable by right-clicking the image and selecting "Alt text", so users could mess with it or you may also want to use it for something else.

    Another way to identify the images is by their getObjectID() method which returns a unique ID. You can get these unique IDs and store using the the Properties Service along with their true/false value:

    const dataBlob = Utilities.newBlob(dataBaseEight);
    const presentation = SlidesApp.openByUrl('https://docs.google.com/presentation...');
    const slides = presentation.getSlides();
    const x = slides[0].insertImage(dataBlob);
    
    var id = x.getObjectID() // returns "some-id"
    
    var props = PropertiesService.getDocumentProperties() // call the properties service
    props.setProperty(id, true) // set "true" to the some-id key
    
    Logger.log(slides[0].getImages()[0].getObjectID()) //returns "some-id" again
    Logger.log(props.getProperty("some-id")) // returns "true"
    

    This doesn't use up the description field and it's harder for users to accidentally change the values, but you may have to keep closer track of the images and their saved properties since the properties will remain even if the images are deleted.

    Do note that in both cases the saved values are string, not boolean.

    References