Can I use Google drive for chrome extensions (not App)

后端 未结 3 1874
礼貌的吻别
礼貌的吻别 2020-12-24 07:06

I have a chrome extension (not App),Its a mashup of data from free third parties. I don\'t maintain a server for my extension.

Can i use Google drive to save user\'s

相关标签:
3条回答
  • 2020-12-24 07:51

    The answer by Nick Park is correct, but I've learned the painful way that simply setting up the project is not as simple as it sounds. If you follow this tutorial from the Chrome doc, you'll probably get face-planted at the first step.

    So here's a recap for setting up your project coupled with a few modifications to make it work.

    Upload to the Developer Dashboard

    1. Compress your project files into a zip file
    2. Go to the Developer Dashboard to create a new item.
    3. Upload the zip file, fill in required fields and return to the dashboard.
    4. Here's the trick: At the time of my writing, the Developer Dashboard will always default to the new interface, which doesn't come with the public key that you need to include into your project.

    Expand the Welcome popup on the bottom right and click on opt out to revert to the legacy view.

    1. On the legacy dashboard view, locate your extension and click on more info.

    2. Copy the public key and paste it as value to the key field of the manifest file inside your unzipped directory

    Load the unpacked extension

    1. Navigate to chrome://extensions, enable Developer mode and upload the unzipped directory. You should see that the app id on this page matches the one at the Developer Dashboard.

    Create OAuth Client ID

    1. Go to Google Api Console and create a new project for your extension.
    2. Navigate to the newly created project and click Credentials on the left sidebar.
    3. Click Create Crendentials and choose OAuth Client ID.
    4. On the next screen, select Chrome App under Application Type and enter your application id.

    If you go to your extension's Chrome webstore URL, such as https://chrome.google.com/webstore/detail/abcdefghjik, you'll see 404 Not Found error. Don't fret. You haven't published your app, so of course that URL won't exist. But you can still use the app id to register your unpublished extension with Google OAuth.

    1. Once ready, hit the Save button and you should see a client id for your app. It can be accessed anytime by clicking the Credentials tab on the left sidebar.

    Register OAuth in the manifest file

    1. In the manifest file of your working directory, include oauth2 field and add the following information:
    "oauth2": {
      "client_id": <your client id>,
      "scopes": ["https://www.googleapis.com/auth/userinfo.email"]
    }
    

    Please note that the year is 2020 and you can no longer leave the the Scopes field empty as told by the ancient doc.

    You need to add the scope above because your app will request the users to select one of their Gmail accounts. That means your app will be able to view the users' email address and we need to be upfront about that.

    That's all for the tricky, time-consuming part. Now you can follow the rest of the tutorial, and Nick Park's answer on making HTTP Request to any Google API you want.

    0 讨论(0)
  • 2020-12-24 07:56

    Yes, you can! Check out this other StackOverflow answer that explains how to use the google-api-javascript-client library to send data to the Google Drive API.

    You might also be interested in this blog post explaining how to mash up Web Intents and the Google Drive API.

    0 讨论(0)
  • 2020-12-24 08:03

    Yes, here is a short guide :)


    Setting up Your Project

    First, you will need to:

    1. Follow the steps outlined in the official Google Drive API docs to create a "Cloud Platform project" and enable the "Drive API".
    2. Follow steps outlined in the official Chrome Extension developer docs to get an "OAuth2 Client ID" for your extension and setup your manifest.json.

    Your manifest.json should now have some extra fields, something like this:

    // manifest.json
    
    "permissions": [
        "identity",
        "https://www.googleapis.com/*"
    ],
    
    "oauth2": {
        "client_id": "YOUR_CLIENT_ID",
        "scopes": [
            "https://www.googleapis.com/auth/drive.appdata",
            "https://www.googleapis.com/auth/drive.file"
        ]
    },
    
    "key": "YOUR_APPLICATION_KEY",
    

    You are now ready to use the Google Drive API!


    Documentation

    The docs for using Google APIs can be found here (this is not specific to Google Drive):

    1. How to make API requests using the JavaScript Client Library
    2. How to use CORS to access Google APIs

    The reference for the Google Drive API can be found here, with examples found here.

    Note: User authentication can be handled somewhat differently in chrome extensions compared to the methods used in the above docs. Refer to the examples below to see how the Chrome Identity API can be used for authentication.


    Examples

    To create a file:

    chrome.identity.getAuthToken({interactive: true}, token => {
        var metadata = {
            name: 'foo-bar.json',
            mimeType: 'application/json',
            parents: ['appDataFolder'],
        };
        var fileContent = {
            foo: 'bar'
        };
        var file = new Blob([JSON.stringify(fileContent)], {type: 'application/json'});
        var form = new FormData();
        form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
        form.append('file', file);
    
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        xhr.responseType = 'json';
        xhr.onload = () => {
            var fileId = xhr.response.id;
            /* Do something with xhr.response */
        };
        xhr.send(form);
    });
    

    To fetch file content:

    chrome.identity.getAuthToken({interactive: true}, token => {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://www.googleapis.com/drive/v3/files/YOUR_FILE_ID?alt=media');
        xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        xhr.responseType = 'json';
        xhr.onload = () => {
            /* Do something with xhr.response */
        };
        xhr.send();
    });
    

    To overwrite existing file content:

    chrome.identity.getAuthToken({interactive: true}, token => {
        var xhr = new XMLHttpRequest();
        xhr.open('PATCH', 'https://www.googleapis.com/upload/drive/v3/files/YOUR_FILE_ID?uploadType=media&access_token=' + token);
        xhr.responseType = 'json';
        xhr.onload = () => {
            /* Do something with xhr.response */
        };
        xhr.send(JSON.stringify({foo: 'bar'}));
    });
    

    Note: the above examples all use CORS, but you can also use the javascript client library.

    For example, to fetch file content with the library:

    gapi.client.init({
        apiKey: 'YOUR_API_KEY',
        discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
    }).then(() => {
        chrome.identity.getAuthToken({interactive: true}, token => {
            gapi.auth.setToken({
                'access_token': token,
            });
    
            gapi.client.drive.files.get({
                'fileId': 'YOUR_FILE_ID',
                'alt': 'media'
            }).then(res => console.log(res))
        });
    });
    

    Further reading:

    Cross-Origin XMLHttpRequest in Chrome Extensions

    OAuth 2.0 for JavaScript Web Apps

    0 讨论(0)
提交回复
热议问题