javascripturlurl-rewritinggoogle-api

Uncaught TypeError: Cannot read property 'urlshortener' of undefined


I am receiving the following error:

Uncaught TypeError: Cannot read property 'urlshortener' of undefined

I am essentially trying to store into parse a url generated from google drive that has been shorten.

Below is the entire code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>upload</title>

        <script type="text/javascript">
            // The Browser API key obtained from the Google Developers Console.
            var developerKey = 'ID';

            // The Client ID obtained from the Google Developers Console.
            var clientId = 'ID';

            // Scope to use to access user's photos.
            var scope = ['https://www.googleapis.com/auth/photos'];

            var pickerApiLoaded = false;
            var oauthToken;

            // Use the API Loader script to load google.picker and gapi.auth.
            function onApiLoad() {
                gapi.load('auth', {'callback': onAuthApiLoad});
                gapi.load('picker', {'callback': onPickerApiLoad});
            }

            function onAuthApiLoad() {
                window.gapi.auth.authorize(
                    {
                        'client_id': clientId,
                        'scope': scope,
                        'immediate': false
                    },
                    handleAuthResult
                );
            }

            function onPickerApiLoad() {
                pickerApiLoaded = true;
                createPicker();
            }

            function handleAuthResult(authResult) {
                if (authResult && !authResult.error) {
                    oauthToken = authResult.access_token;
                    createPicker();
                }
            }

            // Create and render a Picker object for picking user Photos.
            function createPicker() {
                if (pickerApiLoaded && oauthToken) {
                    var picker = new google.picker.PickerBuilder().
                        enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
                        addView(google.picker.ViewId.PDFS).
                        setOAuthToken(oauthToken).
                        setDeveloperKey(developerKey).
                        setCallback(pickerCallback).
                        build();
                    picker.setVisible(true);
                }
            }

            // A simple callback implementation.
            function pickerCallback(data) {
                var url = 'nothing';
                if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
                    var doc = data[google.picker.Response.DOCUMENTS][0];
                    url = doc[google.picker.Document.URL];
                    var message =  url;
                    document.getElementById('result').innerHTML = message;
                }

                var longUrl=url;
                var request = gapi.client.urlshortener.url.insert({
                    'resource': {
                        'longUrl': longUrl
                    }
                });
                request.execute(function(response) {
                    if(response.id != null) {
                        str ="<a href='"+response.id+"'>"+response.id+"</a>";
                        document.getElementById("output").innerHTML = str;

                        Parse.initialize("ID", "ID");
                        var PDFUpload = new Parse.Object("Scan");

                        PDFUpload.set("PDFDocument", response.id);

                        PDFUpload.save(null, {
                            success: function(uploadResult) {
                                // Execute any logic that should take place after the object is saved.
                            },
                            error: function(uploadResult, error) {
                                // Execute any logic that should take place if the save fails.
                                // error is a Parse.Error with an error code and description.
                                alert('Failed to create new object, with error code: ' + error.description);
                            }
                        });
                    } else {
                        alert("error: creating short url");
                    }
                });
            }

            function load()
            {
                gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
                gapi.client.load('urlshortener', 'v1',function(){});
            }
            window.onload = load;
        </script>
        <script src="https://apis.google.com/js/client.js"> </script>
    </head>
    <body>
        <div id="result"></div>
        <div id="demo">
        <div id="output">
        <!-- The Google API Loader script. -->
        <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
    </body>
</html>

In particular, this where I attempt to shorten the URL to store into Parse:

var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
    'resource': {
        'longUrl': longUrl
    }
});
request.execute(function(response) {
    if(response.id != null) {
        str ="<a href='"+response.id+"'>"+response.id+"</a>";
        document.getElementById("output").innerHTML = str;

        Parse.initialize("ID", "ID");
        var PDFUpload = new Parse.Object("Scan");

        PDFUpload.set("PDFDocument", response.id);

        PDFUpload.save(null, {
            success: function(uploadResult) {
                // Execute any logic that should take place after the object is saved.

            },
            error: function(uploadResult, error) {
                // Execute any logic that should take place if the save fails.
                // error is a Parse.Error with an error code and description.
                alert('Failed to create new object, with error code: ' + error.description);
            }
        });
    } else {
        alert("error: creating short url");
    }
});

Update: Please try out this code. It shortens a url from the input value you insert. In the sense that you enter example yahoo.ca in the input field, and once you hit convert it shortens it into a url and store in parse. This works succesfully, but I wanted to integrate that into my code where the url is derived from the url that is generated from the item the user has selected from their google drive:

<html>
    <head>
        <script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>          
        <script type="text/javascript">
            function makeShort() {
                var longUrl=document.getElementById("longurl").value;
                var request = gapi.client.urlshortener.url.insert({
                    'resource': {
                        'longUrl': longUrl
                    }
                });
                request.execute(function(response) {
                    if(response.id != null) {
                        str ="<a href='"+response.id+"'>"+response.id+"</a>";
                        document.getElementById("output").innerHTML = str;

                        Parse.initialize("ID", "ID");
                        var PDFUpload = new Parse.Object("Scan");

                        PDFUpload.set("PDFDocument", response.id);

                        PDFUpload.save(null, {
                            success: function(uploadResult) {
                                // Execute any logic that should take place after the object is saved.
                            },
                            error: function(uploadResult, error) {
                                // Execute any logic that should take place if the save fails.
                                // error is a Parse.Error with an error code and description.
                                alert('Failed to create new object, with error code: ' + error.description);
                            }
                        });
                    } else {
                        alert("error: creating short url");
                    }
                });
            }

            function load() {
                gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
                gapi.client.load('urlshortener', 'v1',function(){});
            }
            window.onload = load;
        </script>
        <script src="https://apis.google.com/js/client.js"></script>
    </head>

    <body>
        URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
        <input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
        <div id="output"></div>
    </body>
</html>

Solution

  • I dug through your example and tried to see what is going on, but I opted to start fresh and try to accomplish this in a simple way. I see that you are using Angular, so I made a little fiddle to try and shorten the URL to this question.

    The main issue I think, is that you need to generate a new key and follow the configuration steps. I did so in minutes and it worked fine. Be sure to choose the API you want (urlshortener) in your dashboard!

    Here is the link I was able to generate: Comment in "Uncaught TypeError: Cannot read property 'urlshortener' of undefined" question

    function googleOnLoadCallback() {
      var key = '{ YOUR KEY }';
      var apisToLoad = 1; // must match number of calls to gapi.client.load()
      var gCallback = function () {
        if (--apisToLoad == 0) {
          // Manual bootstraping of the application
          var $injector = angular.bootstrap(document, ['app']);
        };
      };
      gapi.client.setApiKey(key);
      gapi.client.load('urlshortener', 'v1', gCallback);
    }
    
    <script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
    

    And inside my shorten() function

    var request = 
      gapi.client.urlshortener.url.insert({
        'longUrl': '{ YOUR LONG URL }'
      });
    
    request.execute(function(response) {
      console.log(response.id);
    });