Search code examples
javascriptfetchgoogle-sheets-apibrowser-extensionmanifest.json

How to retrieve a Google Sheet in a Browser Extension with a JS fetch() call?


So I have been doing several hours of searching on this and cannot find anything that works with the current Google Sheets API (v4) in a browser. I can 100% get data through Postman and even a browser address bar. I have a public Google Spreadsheet. I have an API Key. I can successfully return all of the row data.

As soon as I try to do so in a browser extension, I get nothing.

Is anyone aware of how to configure a JavaScript fetch() call to get a successful return on a public Google Spreadsheet? No editing, no deleting. Just a GET.

Here's what I'm trying but isn't working:

var url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${sheetId}?key=${key}`

var response = await fetch(url, {
        method: "GET",
        mode: "no-cors",
        headers: {
            "Host": "sheets.googleapis.com"
        }
    });

Two things I noticed:

  1. If mode wasn't set to no-cors in the fetch() I would get a NetworkError
  2. In Postman if there wasn't a Host header, I would get an error response

Solution

  • Keep in mind this is an issue that specifically has to do with writing Browser Extensions/Addons, not just the typical fetch() usage in a browser.

    To resolve this, I had to add a host permission in the manifest.json file to allow the URL for the Google API sheets.googleapis.com I am calling, like this:

    {
        "manifest_version": 2,
        "name": "Browser Extension",
        "description": "description",
        "version": "1.0.0",
        "icons": {
            "64": "icons/icon.png"
        },
        "background": {
            "scripts": [
                "background_script.js"
            ]
        },
        "permissions": [
            "*://sheets.googleapis.com/*"
        ],
        "content_scripts": [
        [...]
    
    

    As far as the fetch call, all I need is the URL. No need for any options to be set.