Anna Miroshnichenko
Anna Miroshnichenko

Reputation: 1213

How to get the name of the Google doc only with js?

I have a link to the google doc in this format: https://docs.google.com/document/d/googleDocId/edit

When I post it in slack or skype, these programs display me the real name of this doc:

enter image description here

enter image description here

I need to display "Test document" name on my site. Is it possible to do it only with javascript? Without creating any services on the server?

Thank you for your help!

Upvotes: 2

Views: 693

Answers (2)

Anna Miroshnichenko
Anna Miroshnichenko

Reputation: 1213

I created the full example based on the David's answer with loading needed api and getting fileId from the link:

<html>
<head>
    <script src="https://apis.google.com/js/api.js"></script>
    <script>
        function printFile(fileId) {
            var request = gapi.client.drive.files.get({
                'fileId': fileId
            });
            request.execute(function (resp) {
                console.log('Title: ' + resp.title);
                console.log('Description: ' + resp.description);
                console.log('MIME type: ' + resp.mimeType);
            });
        }

        function makeRequest() {
            var url = 'https://docs.google.com/document/d/15vISe8Lw841LqdVRtZM3egniCeRcsPXtivqxuh76t6o/edit',
                    fileId;

            fileId = url.match(/[-\w]{25,}/);

            if (fileId && fileId[0]) {
                fileId = fileId[0];
            }
            printFile(fileId);
        }

        function init() {
            gapi.client.setApiKey('your api should be here');
            gapi.client.load('drive', 'v2').then(makeRequest);
        }

        gapi.load('client', init);
    </script>
</head>
<body>
</body>
</html>

Upvotes: 0

David R
David R

Reputation: 15637

You need to use the get method of the Google Drive's API which takes one required field which is the fileId which will be 15vISe8Lw841LqdVRtZM3egniCeRcsPXtivqxuh76t6o in your case,

To retrieve your file metadata programatically, Try this,

function printFile(fileId) {
  var request = gapi.client.drive.files.get({
    'fileId': fileId
  });
  request.execute(function(resp) {
    console.log('Title: ' + resp.title);
    console.log('Description: ' + resp.description);
    console.log('MIME type: ' + resp.mimeType);
  });
}

I have tried with your document ID, and here is the output which I had received upon a successful response,

enter image description here

So you can use the title attribute to print your document tile in your site.

Hope this helps!

Upvotes: 3

Related Questions