Search code examples
google-chromegoogle-chrome-extensiongoogle-drive-apigoogle-sheets-apigoogle-docs-api

Google Docs API see Docs without knowing id


I'm creating a Chrome extension which when highlighting text anywhere will offer the user to save the highlighted text to any Doc in Google Docs. So the idea is to show a list of last 10 Google Docs and the user could save it to any of them or could search for another Doc. I've been reading documentation on Chrome identity API, Docs API and Drive API, and they all mention that we need to know the Doc's id (which is inside the url of the Doc). So it's not possible to display a list of Docs without knowing their actual ids? I guess it would be a security violation if an extension or an app could do this? Or I'm mistaken and it's actually possible?

P.S. This link seems to be what I was looking for (so it's possible): https://developers.google.com/drive/api/v3/reference/files/list


Solution

  • Answer:

    Yes, you can get a list of the last 10 modified files in Google Drive using the modifiedDate, pageSize and mimeType parameters.

    More Information:

    You can make a Files: list query to the Drive API with parameters narrowing down your search. As you do not know the file IDs, you can search for files which have the application/vnd.google-apps.document MIME Type, and then narrow the search down by ordering by the modifiedDate and only requesting 10 results.

    Code:

    As I'm not 100% sure on which language you are using, I've provided a simple Apps Script example below. The relevant references can be seen below though so you can modify this to suit your coding requirements.

    function myFunction() {
      var searchTerms = {
        orderBy: "modifiedDate",
        pageSize: 10,
        q: "mimeType='application/vnd.google-apps.document'"
      };
      
      for (var i = 0; i < 10; i++) {
        Logger.log(Drive.Files.list(searchTerms).items[i].title);
      }  
    }
    

    Don't forget to enable the Advanced Drive Service for this! Also remember that the Advanced Drive service uses Drive v2, though this can be done in both Drive API v2 and Drive API v3.

    References: