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

Google Slides API deleteObject() when object not exists


I want to update an existing object/image in a Google Slide. This works as long as the object exists:

var requests = [
    {
      "deleteObject": {
        "objectId": 'image01'
      }
    },
    {
      "createImage": {
        "url": imageUrl,
        "objectId": 'image01',
        "elementProperties": {
          "pageObjectId": pageId,
          "size": {
            "width": {
              "magnitude": 250,
              "unit": "PT"
            },
            "height": {
              "magnitude": 250,
              "unit": "PT"
            }
          },
          "transform": {
            "scaleX": 1,
            "scaleY": 1,
            "translateX": 200,
            "translateY": 100,
            "unit": "PT"
          }
        }
      }
    }
  ];
  var response = Slides.Presentations.batchUpdate({'requests': requests}, presentationId);

However, if a user previously deleted the object in the presentation, it is not re-created.

The following error message appear:

Invalid requests[0].deleteObject: The object (image01) could not be found.

How can I query whether an object exists in presentation?


Solution

  • How about retrieving a object list using slides.presentations.get? In order to confirm whether objects exist, it uses slides/pageElements/objectId for fields of slides.presentations.get. You can know the exist of objects using the object list.

    Sample script :

    var response = Slides.Presentations.get(presentationId);
    response.slides.forEach(function(e1, i1){
      e1.pageElements.forEach(function(e2){
        Logger.log("Page %s, objectId %s", i1 + 1, e2.objectId);
      });
    });
    

    Result :

    Page 1.0, objectId ###
    Page 2.0, objectId ###
    Page 3.0, objectId ###
    

    If this was not useful for you, I'm sorry.

    Edit :

    If you want to search a value from whole JSON, you can use following simple script. When value2 is included in sampledata, ~JSON.stringify(sampledata).indexOf('value2') becomes true. In this sample, ok is shown, because value2 is included in sampledata.

    But it's a bit of a stretch. If you can know the complete structure of JSON, I think that the compare of value using key is better.

    var sampledata = {key1: "value1", key2: "value2"};
    if (~JSON.stringify(sampledata).indexOf('value2')) { 
      Logger.log("ok")
    }